1

这是我的活动代码(我从 >> http://itweb-projects.com/wordpress/android-connecting-to-mysql-using-php获取)我面临的问题是它抛出 JSON 错误处理它的解析?>>

 package com.database_demo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class Database_demo extends ListActivity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        List<String> r = new ArrayList<String>();

        try{

        //http post
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://winacro.com/nishant/andRHOME.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        }
        catch(Exception e){
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
       }

        //Convert response to string  
        try
        {
          BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

          sb = new StringBuilder();

          String line = null;

          while ((line = reader.readLine()) != null) 
          {
             sb.append(line + "\n");
          }

          is.close();

          result = sb.toString();
        }
        catch(Exception e)
        {
            Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
        }
        //END Convert response to string   
        try{
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data=null;
                for(int i=0;i<jArray.length();i++)
                {
                   json_data = jArray.getJSONObject(i);
                   r.add(json_data.getString("category"));
               }
               setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
            }
            catch(JSONException e1){
                Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
        }

    }
}

这是我的 Manifest.xml>>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.database_demo"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />      
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Database_demo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>


</manifest> 

这是 LOGCAT 的回复>>

07-28 09:02:17.435: I/Process(27270): Sending signal. PID: 27270 SIG: 9
07-28 09:02:37.985: D/AndroidRuntime(27812): Shutting down VM
07-28 09:02:37.985: W/dalvikvm(27812): threadid=1: thread exiting with uncaught exception (group=0x420442a0)
07-28 09:02:37.985: E/AndroidRuntime(27812): FATAL EXCEPTION: main
07-28 09:02:37.985: E/AndroidRuntime(27812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.database_demo/com.database_demo.Database_demo}: java.lang.NullPointerException
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.os.Looper.loop(Looper.java:137)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.main(ActivityThread.java:4898)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at java.lang.reflect.Method.invokeNative(Native Method)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at java.lang.reflect.Method.invoke(Method.java:511)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at dalvik.system.NativeStart.main(Native Method)
07-28 09:02:37.985: E/AndroidRuntime(27812): Caused by: java.lang.NullPointerException
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONArray.<init>(JSONArray.java:87)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at org.json.JSONArray.<init>(JSONArray.java:103)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at com.database_demo.Database_demo.onCreate(Database_demo.java:78)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.Activity.performCreate(Activity.java:5206)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
07-28 09:02:37.985: E/AndroidRuntime(27812):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
07-28 09:02:37.985: E/AndroidRuntime(27812):    ... 11 more

崩溃的主要原因可能是什么,我该如何解决? 我已经检查了成功返回 JSON 的 php 文件!

运行异步任务以减轻 UI 线程的更新代码:

package com.database_demo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class Database_demo extends ListActivity {

    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    List<String> r = new ArrayList<String>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute("sleepTime");
     }
    private class AsyncTaskRunner extends AsyncTask<String, String, String> {
        // Do the long-running work in here

        // This is called each time you call publishProgress()

        // This is called when doInBackground() is finished
        @Override
        protected void onPostExecute(String result) {

        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            try{

                //http post
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://winacro.com/nishant/andRHOME.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                }
                catch(Exception e){
                    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
               }

                //Convert response to string  
                try
                {
                  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

                  sb = new StringBuilder();

                  String line = null;

                  while ((line = reader.readLine()) != null) 
                  {
                     sb.append(line + "\n");
                  }

                  is.close();

                  result = sb.toString();
                }
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
                }
                //END Convert response to string   
                try{
                        JSONArray jArray = new JSONArray(result);
                        JSONObject json_data=null;
                        for(int i=0;i<jArray.length();i++)
                        {
                           json_data = jArray.getJSONObject(i);
                           r.add(json_data.getString("category"));
                       }
                       setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
                    }
                    catch(JSONException e1){
                        Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
                    } catch (ParseException e1) {
                        Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
                }


            return null;
        }


    }
}

最新日志>>

4

3 回答 3

2

首先,您在 UI 线程上进行网络访问。这是一个很大的禁忌,如果您使用 API 11 或更高版本运行,它会抛出一个NetworkOnMainThreadxception. 但是,如果您确实遇到异常,您将继续尝试解析(空)响应流。

您需要将网络处理移至单独的线程,并且需要改进错误处理。显示 aToast并继续好像没有出错一样是灾难的根源。如果接收响应出现问题,您需要停止处理并提醒用户。请参阅保持您的应用响应文章。

于 2013-07-28T04:05:35.400 回答
0
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, r));

而不是this使用filename.this

于 2013-07-28T06:30:35.690 回答
0

我希望您参考http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/http://www.androidhive.info/2012/01/android -json-parsing-tutorial/关于json解析

于 2013-07-28T04:09:43.033 回答