这是我的活动代码(我从>> 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&gt;&gt;
<?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回复&gt;&gt;
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
崩溃的主要原因是什么?如何解决? 我已经检查了php文件,它成功返回了JSON!
使用ASYNC TASK运行的更新代码来缓解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;
}
}
}
最新的LOGCAT&gt;&gt;
答案 0 :(得分:2)
首先,您正在UI线程上进行网络访问。这是一个很大的禁忌,如果你运行API 11或更高版本,它将抛出一个NetworkOnMainThreadxception
。但是,如果确实遇到异常,则继续尝试解析(null)响应流。
您需要将网络处理移至单独的线程,并且需要改进错误处理。显示Toast
并继续,好像什么都没有出错是灾难的一个秘诀。如果收到响应时出现问题,您需要停止处理并提醒用户。请参阅Keeping Your App Responsive文章。
答案 1 :(得分: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解析
答案 2 :(得分:0)
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, r));
而不是this
使用filename.this