2012-08-23 5 views
0

Android에서 새로운 기능, JSON 데이터에서 listview를 만들려고합니다.Android "스크립트가 예외를받을 때 알림을 표시하는 방법"

스크립트가 예외 처리 될 때 사용자에게 경고를 표시 할 수 없다는 점을 제외하면 모든 것이 정상입니다.

내 목표는 JSON을 얻기 위해 서버에 요청하기 전에 인터넷 연결을 먼저 청취하는 것입니다. 연결이없는 경우 앱은 사용자에게 인터넷 연결을 켜라는 경고를 표시합니다.

현재 인터넷에 연결되어 있지 않으면 응용 프로그램이 강제로 대화 상자를 닫고 응용 프로그램을 닫습니다.

public class HargaActivity extends ListActivity { 


//SET URL 
private static String url = "http://www.jualanmotor.com/JmApi/DaftarMotor/?username=elis&password=puspasarikeisha"; 

// JSON Node names 
private static final String TAG_data   = "data"; 
private static final String TAG_Parent   = "Parent"; 
private static final String TAG_Parent_name  = "parent_name"; 
private static final String TAG_Category  = "Category"; 
private static final String TAG_Category_name = "category_name"; 
private static final String TAG_product_title = "product_title"; 

// contacts JSONArray 
JSONArray data = null; 

// Hashmap for ListView 
ArrayList<HashMap<String, String>> productList = new ArrayList<HashMap<String, String>>(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.harga_layout); 
    new ProgressTask(HargaActivity.this).execute(); 
} 

private class ProgressTask extends AsyncTask<String, Void, Boolean> 
{ 
    private ProgressDialog dialog; 
    private ListActivity activity; 
    private Context context; 

    public ProgressTask(ListActivity activity) { 
     this.activity = activity; 
     context = activity; 
     dialog = new ProgressDialog(context); 
    } 

    @Override 
    protected void onPreExecute() { 
     this.dialog.setMessage("Trying get content"); 
     this.dialog.show(); 
    } 

    protected void onPostExecute(final Boolean success) 
    { 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(HargaActivity.this, productList, 
       R.layout.list_item, 
       new String[] {TAG_product_title}, new int[] { 
         R.id.product_title}); 
     setListAdapter(adapter); 
     dialog.dismiss(); 
    } 

    @Override 
    protected Boolean doInBackground(final String... args){ 
     // Creating JSON Parser instance 
     JSONParser jParser = new JSONParser(); 

     // getting JSON string from URL 
     JSONObject json; 
     json = jParser.getJSONFromUrl(url); 

     try { 
      // Getting Array of Contacts 
      data = json.getJSONArray(TAG_data); 

      // looping through All Contacts 
      for(int i = 0; i < data.length(); i++){ 
       JSONObject c = data.getJSONObject(i); 

       // Parent is again JSON Object 
       JSONObject parent  = c.getJSONObject(TAG_Parent); 
       String parent_name  = parent.getString("name"); 

       // Category is again JSON Object 
       JSONObject category  = c.getJSONObject(TAG_Category); 
       String category_name = category.getString("name"); 
       String product_title = parent_name + "-" + category_name; 
       // creating new HashMap 
       HashMap<String, String> map = new HashMap<String, String>(); 

       // adding each child node to HashMap key => value 
       map.put(TAG_Parent_name, product_title); 
       map.put(TAG_Category_name, category_name); 
       map.put(TAG_product_title, product_title); 
       // adding HashList to ArrayList 
       productList.add(map); 
      } 
      return true; 
     } catch (Exception e) { 
      /* 
         **I WANT TO SHOW ALERT MESSAGE HERE** 
        */ 
      return false; 
     } 
    } 
} 
} 

그리고이 내 JSONParse.java

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent();   

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 
} 

답변

0

사용

: 나 ... 난 이것에 대한 좌절을 받고 있어요 도와 줘요 것은

이 내 주요 활동 클래스입니다 :)

runonUithread(new Runnable() 
{ 
    Toast.makeText(ReadWebpageAsynTask.this, "Got Error " + e.getMessage().toString(), Toast.LENGTH_LONG).show(); 
}); 
0

같은 변수를 만들 수 있습니다.

boolean error = false; 

AsyncTask의 모든 기능에 대해 표시되어야합니다. catch 블록에서 true로 설정하십시오.

그런 다음 postExcecute() 기능에서 알림을 표시 할 수 있습니다.

if (error == true){ 
    // show your allert here 
}else{ 
    // Do things here when everything is ok 
} 
0

UI가 아닌 스레드 (doInBackGround AsyncTask)에서 AlertDialog (UI 요소)를 푸시하려고합니다.

내가 예외가 어떤 인터넷이 없을 때 발생지고 있다고 생각하고 URL을 액세스하려고

runOnUiThread(new Runnable() { 

public void run() { 
    // show your dialog here :) you can build it both here or somewhere else 

    } 
    }); 
    } 
}).start(); 
0

를 사용할 수 있습니다. 당신의 ProgressTask 용)이 함수는 doInBackground (호출되고 바로 옆

jParser.getJSONFromUrl(url); 

에 시도-catch 블록에 다음 줄을 이동하십시오. try-catch 내부로 이동하면 인터넷을 사용할 수없고 예외가 발생하는 경우 해당 예외를 catch하여 사용자에게 메시지를 표시 할 수 있습니다.

메시지를 표시하려면 catch 블록 내부에서 Toast 또는 AlertDialog를 사용할 수 있습니다.

관련 문제