0

基本上,我有一个 Android 应用程序和一个 MySQL 数据库,我正在使用 PHP 尝试使用其中的条目填充 ListView。现在由于某种原因,以下代码似乎崩溃了,Logcat 说 WindowManager 有问题

代码是:

AllComediansActivity.java:

package com.example.connecttest;

public class AllComediansActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String,String>> comedianList;

    // url to get all comedian names
    private static String url_all_comedians = "http://localhost/connect/get_all_comedians.php";

    //JSON Node Names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_COMEDIAN = "comedian";
    private static final String TAG_PID = "id";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray comedians = null;

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_comedians);

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

        //Loading comedians in background thread
        new LoadAllComedians().execute();

        // Get Listview
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener(){

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

                //
            }

        });
    }

    class LoadAllComedians extends AsyncTask<String, String, String>{

        // Before Starting background thread show Progress Dialog
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(AllComediansActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // Getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_comedians, "GET", params);

            //Check log cat for JSON response
            Log.d("All Comedians: ", json.toString());

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

                if(success == 1){
                    // Comedians found
                    // Getting Array of Comedians
                    comedians = json.getJSONArray(TAG_COMEDIAN);

                    // Looping through All Comedians
                    for(int i = 0; i < comedians.length(); i++){
                        JSONObject c = comedians.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
                        comedianList.add(map);                      
                    }
                } else {
                    // no products found
                    // Launch Add New Comedian Activity
                    Intent i = new Intent(getApplicationContext(), NewComedianActivity.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 comedians
            pDialog.dismiss();
            // Updating UI from Background Thread
            runOnUiThread(new Runnable(){
                public void run(){
                    // Updating JSON data into ListView
                    ListAdapter adapter = new SimpleAdapter(AllComediansActivity.this, comedianList, R.layout.list_item, new String[] {TAG_PID, TAG_NAME}, new int[] {R.id.id,R.id.name});
                    setListAdapter(adapter);
                }
            });
        }

    }

}

为了简洁起见,我刚刚删除了正确的导入。

它引用的 JSONParser 是:

JSONParser.java:

package com.example.connecttest;

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 method
    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;

    }
}

当我在浏览器中导航到 PHP 文件时,它会返回以下信息:

{"comedian":[{"id":"1","name":"Mike Coombes","address":"Test","email":"test@test.com","tel":"xxxxxxxx"},{"id":"2","name":"Test","address":"Test","email":"Tester@test.com","tel":"xxxxxxx"}],"success":1}

所以我的 PHP 正在正确查询数据库并使用 JSON 返回它。

现在调试程序表明它似乎达到了以下行:

 JSONObject json = jParser.makeHttpRequest(url_all_comedians, "GET", params);

在它解开之前,我已经把头发拉了几个小时试图让它也能正常工作,但无济于事,我想知道人们是否可以帮助我解决这里的问题!

当问到我的 Logcat 错误是:

03-21 05:57:10.319: E/Buffer Error(3500): Error converting result java.lang.NullPointerException: lock == null
03-21 05:57:10.319: E/JSON Parser(3500): Error parsing data org.json.JSONException: End of input at character 0 of 
03-21 05:57:10.329: E/AndroidRuntime(3500): FATAL EXCEPTION: AsyncTask #1
03-21 05:57:10.329: E/AndroidRuntime(3500): java.lang.RuntimeException: An error occured while executing doInBackground()
03-21 05:57:10.329: E/AndroidRuntime(3500):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.lang.Thread.run(Thread.java:856)
03-21 05:57:10.329: E/AndroidRuntime(3500): Caused by: java.lang.NullPointerException
03-21 05:57:10.329: E/AndroidRuntime(3500):     at com.example.connecttest.AllComediansActivity$LoadAllComedians.doInBackground(AllComediansActivity.java:93)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at com.example.connecttest.AllComediansActivity$LoadAllComedians.doInBackground(AllComediansActivity.java:1)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-21 05:57:10.329: E/AndroidRuntime(3500):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-21 05:57:10.329: E/AndroidRuntime(3500):     ... 4 more
4

1 回答 1

0

我设法让它工作最终有两个问题

将 localhost 切换到 10.0.2.2 并且必须向 URL 添加协议

权限也有错字,必须将其从用户权限更改为使用权限,现在一切正常

于 2013-03-21T16:22:19.040 回答