1

ここに私のActivityコードがあります(私は>> 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 スレッドを軽減するために実行中の ASYNC TASK を使用して更新されたコード:

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. ただし、例外が発生した場合は、引き続き (null) 応答ストリームを解析しようとします。

ネットワーク処理を別のスレッドに移動する必要があり、エラー処理を改善する必要があります。を表示し、Toast何も問題がなかったかのように続行することは、災害のレシピです。応答の受信に問題がある場合は、処理を停止してユーザーに警告する必要があります。アプリの応答性を維持するの記事を参照してください。

于 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 に答える