0

我是 Android 新手,我尝试从 JSON 数据创建列表视图。

一切都很好,除了当脚本出现异常时我无法向用户显示警报。

我的目标是,在请求服务器获取 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;

}
}
4

4 回答 4

0

利用

runonUithread(new Runnable()
{
   Toast.makeText(ReadWebpageAsynTask.this, "Got Error " + e.getMessage().toString(),  Toast.LENGTH_LONG).show();
});
于 2012-08-23T11:20:22.453 回答
0

我认为当没有互联网并且您尝试访问该网址时会引发异常。尝试将以下行移动到它旁边的 try-catch 块中

jParser.getJSONFromUrl(url);

在 doInBackground() 中为您的 ProgressTask 调用此函数。将其移入 try-catch 将确保如果互联网不可用并且引发异常,您将捕获该异常并能够向用户显示消息。

要显示消息,您可以在 catch 块内使用 Toast 或 AlertDialog。

于 2012-08-23T12:00:13.963 回答
0

您可以创建一个变量,如

boolean error = false;

它必须对 AsyncTask 中的所有函数可见。在你的 catch 块中将它设置为 true;

然后你可以在你的 postExcecute() 函数中显示警报。

if (error == true){
    // show your allert here
}else{
    // Do things here when everything is ok
}
于 2012-08-23T11:37:28.777 回答
0

问题是您正试图从非 UI 线程(AsyncTask 的 doInBackGround)推送 AlertDialog(UI 元素)。

你可以使用

runOnUiThread(new Runnable() {

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

    }
    });
   }
}).start();
于 2012-08-23T11:38:39.457 回答