我试图从网址获取数据。我已经阅读了很多关于同一问题的帖子,但没有任何效果。请帮我解决这个问题...发布我的代码
JsonParser.class
import android.util.Log;
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String json = EntityUtils.toString(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(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
这是我的 MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://localhost:8083/android/search";
// contacts JSONArray
JSONArray dataJsonArr = null;
@Override
protected void onPreExecute() {}
@SuppressLint("NewApi")
@Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = new JSONArray(json.getJSONArray("searchlist"));
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
//JSONObject c = dataJsonArr.getJSONObject(i);
//String firstname = c.getString("firstname");
String firstname= dataJsonArr.getString(i);
// show the values in our logcat
Log.e(TAG, "firstname: " + firstname
);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
AndroiManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsing"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidjsonparsing.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>
</application>
</manifest>
这是我们从网址获取的 json文件:
{"searchlist":["Micromax Ninja A89 Smartphone","Capdase Fliptop Case for Samsung Galaxy S II I9100","IFB Microwave Convection 20SC2, 20 litres","Samsung Microwave Convection CE1041DFB, Black, 28 litres"]}
这是我的日志文件:
04-23 13:34:49.621: E/JsonParser.java(955): Error converting result java.lang.NullPointerException: lock == null
04-23 13:34:49.622: E/JsonParser.java(955): Error parsing data org.json.JSONException: End of input at character 0 of
04-23 13:34:49.622: E/JsonParser.java(955): --------- beginning of crash
04-23 13:34:49.662: E/AndroidRuntime(955): FATAL EXCEPTION: AsyncTask #1
04-23 13:34:49.662: E/AndroidRuntime(955): Process: com.example.androidjsonparsing, PID: 955
04-23 13:34:49.662: E/AndroidRuntime(955): java.lang.RuntimeException: An error occured while executing doInBackground()
04-23 13:34:49.662: E/AndroidRuntime(955): at android.os.AsyncTask$3.done(AsyncTask.java:304)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-23 13:34:49.662: E/AndroidRuntime(955): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.lang.Thread.run(Thread.java:818)
04-23 13:34:49.662: E/AndroidRuntime(955): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
04-23 13:34:49.662: E/AndroidRuntime(955): at com.example.androidjsonparsing.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:50)
04-23 13:34:49.662: E/AndroidRuntime(955): at com.example.androidjsonparsing.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:1)
04-23 13:34:49.662: E/AndroidRuntime(955): at android.os.AsyncTask$2.call(AsyncTask.java:292)
04-23 13:34:49.662: E/AndroidRuntime(955): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-23 13:34:49.662: E/AndroidRuntime(955): ... 4 more
答案 0 :(得分:1)
在 MainActivity
中更改此行:
dataJsonArr = new JSONArray(json.getJSONArray("searchlist"));
要:
dataJsonArr = new json.getJSONArray("searchlist");
否则编码就可以了。
检查您提供的网址是否正确。