Android onPreExecute()、progressDialog 和 json.toString() 错误

Posted

技术标签:

【中文标题】Android onPreExecute()、progressDialog 和 json.toString() 错误【英文标题】:Android onPreExecute(), progressDialog and json.toString() error 【发布时间】:2016-01-11 03:05:02 【问题描述】:

我正在做一个项目,从我的服务器加载来自 mysql 数据库的数据并以 ListView 的形式显示。但是,我在实现这一目标时遇到了一些障碍,每当我打开ContentActivity 时,应用程序最终都会强制关闭。从我的 logcat 中,我得到了两组错误:

首先我在第 196 行 (class LoadAllContent extends AsyncTask<String, String, String> ) 和第 221 行 (Log.d("All Posts: ", json.toString());) 遇到错误。此段的完整错误是:

10-13 13:42:58.978  20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
10-13 13:42:58.978  20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
10-13 13:42:58.980  20090-20315/? E/androidRuntime? FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:838)
 Caused by: java.lang.NullPointerException
        at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
        at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:838)
10-13 13:42:59.007     553-3073/? W/ActivityManager? Force finishing activity com.app.appname/.ContentActivity

第二组错误位于第 85 行 (new LoadAllContent().execute();) 和第 208 行 (pDialog.show();)

10-13 13:42:59.856  20090-20090/? E/WindowManager? Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView41ec1f80 V.E..... R......D 0,0-480,96 that was originally added here
android.view.WindowLeaked: Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView41ec1f80 V.E..... R......D 0,0-480,96 that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        at android.app.Dialog.show(Dialog.java:281)
        at com.app.appname.ContentActivity$LoadAllContent.onPreExecute(ContentActivity.java:208)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        at android.os.AsyncTask.execute(AsyncTask.java:534)
        at com.app.appname.ContentActivity.onCreate(ContentActivity.java:85)
        at android.app.Activity.performCreate(Activity.java:5122)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
        at android.app.ActivityThread.access$600(ActivityThread.java:165)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5370)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
        at dalvik.system.NativeStart.main(Native Method)

我不确定这两个错误是否相关。我的 ContentActivity.javaindex.php 文件如下。

ContentActivity.java

public class ContentActivity extends ListActivity implements ISideNavigationCallback 

Utils util;

final Context context = this;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> contentList;

// url to get all content
private static String getContent = "http://192.168.43.87/app/index.php?act=getContent";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_PID = "id";
private static final String TAG_TITLE = "title";

// products JSONArray
JSONArray posts = null;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content);

    util = new Utils(this);

    TextView appTit = (TextView) findViewById(R.id.appTitle);
    String pageTitle = "MySql Database Content";
    appTit.setText((CharSequence)pageTitle);

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

    new LoadAllContent().execute();

    // Get listview
    ListView lv = getListView();

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) 
            // getting values from selected ListItem
            String postId = ((TextView) view.findViewById(R.id.postId)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), ContentViewActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, postId);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        
    );


/**
 * Background Async Task to Load all content by making HTTP Request
 * */
class LoadAllContent extends AsyncTask<String, String, String> 

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

    /**
     * getting All content from url
     * */
    protected String doInBackground(String... args) 
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(getContent, "GET", params);

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

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

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

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

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

                    // 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_TITLE, title);

                    // adding HashList to ArrayList
                    contentList.add(map);
                
             else 
                // no content found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NoPostActivity.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(
                        ContentActivity.this, contentList,
                        R.layout.list_item, new String[]  TAG_PID,
                        TAG_TITLE,
                        new int[]  R.id.postId, R.id.title );
                // updating listview
                setListAdapter(adapter);
            
        );
    



index.php

<?php
$action = $_GET['act'];

if ($action == 'getallposts') 
$posts = get_posts('numberposts=10&order=DESC&orderby=post_desc_gmt');
$numPosts = count($posts);
if ($numPosts > 0) 

    $response["posts"] = array();

    foreach ($posts as $postr) : setup_postdata( $post );
        // temp user array
        $post = array();
        $post['id'] = $postr->ID;
        $post["title"] = $postr->post_title;
        $post["desc"] = substr($postr->post_content,0,50).'...';
        $post['comments'] = $postr->comment_count;
        $post["created"] = $postr->post_date_gmt;
        array_push($response["posts"], $post);
    endforeach; 

    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
 else 
    // no products found
    $response["success"] = 0;

    echo json_encode($response);

 
?>

我非常感谢任何解决这个问题的建议,因为我所做的所有研究都没有取得任何成果。

【问题讨论】:

我不想重复自己,但是:androidhive 是一个糟糕的教程来源 ... ...但仍然可能与What is a Null Pointer Exception, and how do I fix it?重复 尝试设置new ProgressDialog(getApplicationContext());检查你的pDialognull json=jParser.makeHttpRequest(getContent, "GET", params); 在你的doInBackground 中是null @Rastum,当我在浏览器上运行链接时,它会返回 json 格式的数据。如何检查 pDialog 是否为空? 【参考方案1】:

只有几个厘米:

    Log.d("All Posts: ", json.toString()); 移动到try .. catch 也阻止并捕获NullPointerException

    您不需要在postExecute 上使用runOnUiThread 作为 postExecute 始终运行在 UI 线程(主线程)上

    不要从doInBackground 开始活动(它可能是 可能但不要这样做);从postExecute 执行此操作,就像这样:

    如果(成功!= 1)

        Intent i = new
    Intent(getApplicationContext(),NoPostActivity.class);
    
          // Closing all previous activities
           i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
           startActivity(i);
    
    
    

【讨论】:

以上是关于Android onPreExecute()、progressDialog 和 json.toString() 错误的主要内容,如果未能解决你的问题,请参考以下文章

从片段调用 Android AsyncTask 没有调用其成员 - doInbackground、onpreexecute、onpostexecute

Android onPreExecute()、progressDialog 和 json.toString() 错误

在 onPreExecute() 内部调用时 TextView.setText() 的 NullPointerException

android AsyncTask的方法在哪几个线程中调用

如何从 onPreExecute() 方法中取消 ProcessDialog

异步任务;调用方法 onPreExecute() 后未调用 doInbackground()