【问题标题】:Android: AsyncTask causes app to crash, no error logs printedAndroid:AsyncTask 导致应用程序崩溃,没有打印错误日志
【发布时间】:2017-08-19 21:59:17
【问题描述】:

我目前正在尝试将 android 应用程序与服务器连接的教程(链接:https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/)。 但是,我对应该加载数据库元素的 AsyncTask 有困难。它会导致应用程序崩溃并且不会在 logcat 中留下错误日志(也尝试过“无过滤器”)。我也用 try catch 块包围了执行调用,但应用程序仍然崩溃。任何想法是什么导致了错误?

以下是代码摘录:

public class AllProductsActivity extends ListActivity {
private static String url_all_products = "https://api.androidhive.info/android_connect/get_all_products.php";
... 
@Override
    public void onCreate(Bundle savedInstanceState) {
try {
            new LoadAllProducts().execute();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

...

/**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            List<Pair> params = new ArrayList<Pair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            AddNewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                            TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }

【问题讨论】:

  • 告诉我我可以在你的代码中看到的一件事 // 检查你的日志猫是否有 JSON 响应 Log.d("All Products: ", json.toString());请告诉我你可以在日志中看到 json.toString() 代码的内容吗?

标签: android android-studio android-asynctask


【解决方案1】:

问题不在于您的代码实现。我可以在您的代码中看到 webservice url

private static String url_all_products = "https://api.androidhive.info/android_connect/get_all_products.php";

问题出在这个网络服务上。那不再起作用了。正如您提到的 postman 教程的链接,我测试了 web 服务,它不再工作了。希望你明白我的意思。如果您有任何困惑,请随时问我。

【讨论】:

  • 我已经这么认为了,这个“api”不是真正的交易 x)。但是为什么没有抛出异常或打印日志?另外,你是如何测试服务的,设置xamp并在浏览器中输入url就足够了吗?
  • 是的,这是您提出的有效问题。请检查您是否错误地在日志猫中应用了任何过滤器,或者检查您的设备是否已连接并在 Android 监视器中可见。
  • 在这种情况下,我仍然应该在 try catch 块周围发现一些异常,不是吗?但我会尝试使用服务器,这样我就可以使用工作的网络服务器测试代码。感谢您的回答:)
猜你喜欢
  • 1970-01-01
  • 2020-02-17
  • 2012-11-15
  • 2011-06-08
  • 1970-01-01
  • 2018-08-27
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多