ANDROID:执行doInBackground时发生错误

时间:2014-08-25 00:17:11

标签: php android mysql

我目前正在学习构建一个通过我网站上的php webservice连接到mySQL数据库的Android应用程序,并从中提取有关不同商店的信息。

我一直在从一个教程中学习并且遇到错误'java.lang.RuntimeException:执行doInBackground时发生错误'。我在这里搜索了很多年,已经回答的问题似乎对我的情况没有帮助。因此想知道你是否可以提供帮助?

我的代码:

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.HashMap;    
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllShopsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> shopsList;

    // url to get all shops list
    private static final String url_all_shops = "http://www.mywebsitename.biz/android_connect/get_all_shops.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_SHOPS = "shops";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // shops JSONArray
    JSONArray shops = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_shops);

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

        // Loading shops in Background Thread
        new LoadAllshops().execute();

        // Get listview
        ListView lv = getListView();


        // on seleting single shop
        // launching Edit shop Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

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

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

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

    // Response from Edit shop Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted shop
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

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

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

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

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

            try {

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

                if (success == 1) {
                    // shops found
                    // Getting Array of shops
                    shops = json.getJSONArray(TAG_SHOPS);

                    // looping through All shops
                    for (int i = 0; i < shops.length(); i++) {
                        JSONObject c = shops.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
                        shopsList.add(map);
                    }
                } else {
                    // no shops found
                    // Launch Add New shop Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewshopActivity.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 shops
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllShopsActivity.this, shopsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }    
}

我注意到行protected String doInBackground(String... args)有'字符串......'我之前没有看到过这是一个问题,还是意味着

退出投注:

08-24 23:44:50.837: E/AndroidRuntime(1709): FATAL EXCEPTION: AsyncTask #1
08-24 23:44:50.837: E/AndroidRuntime(1709): java.lang.RuntimeException: An error occured while executing doInBackground()
08-24 23:44:50.837: E/AndroidRuntime(1709):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.lang.Thread.run(Thread.java:856)
08-24 23:44:50.837: E/AndroidRuntime(1709): Caused by: java.lang.NullPointerException
08-24 23:44:50.837: E/AndroidRuntime(1709):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:138)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-24 23:44:50.837: E/AndroidRuntime(1709):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-24 23:44:50.837: E/AndroidRuntime(1709):     ... 5 more 

我检查了我的db_config.php文件,服务器,密码和用户都是正确的。有什么建议吗?

编辑: 添加清单详细信息:

 <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:configChanges="keyboardHidden|orientation"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- All Product Activity -->
        <activity
            android:name=".AllProductsActivity"
            android:label="All Products" >
        </activity>

编辑2:JSONPARSER

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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;

    }
}

1 个答案:

答案 0 :(得分:3)

鉴于您的JSONParser代码,似乎返回值保持为null并返回如下:jObj

您正在捕捉大多数例外并打印出一些消息,请检查它们。

此外,主要原因似乎是您的网址没有返回任何内容,就像您在评论中所说的那样。

所以,基本上,只需确保URL确实返回您所期望的并调试JSONParser组件。