我是android新手我使用以下代码来解析数据并与数据库连接,从而获得服务器中存在的数据库中的值。
我使用的代码是: -
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
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(); <------Here
} 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;
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "Prathamesh");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
}
我正在使用另一个代码来使用json的值并显示它。它如下: -
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity
{
//url to make request
private static String url = "http://192.168.0.100:3000/users.json";
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_FIRST = "first_name";
private static final String TAG_MIDDLE = "middle_name";
private static final String TAG_LAST = "last_name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_MOBILE = "mobile";
private static final String TAG_USERS = "user";
// users JSONArray
JSONArray users = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_test1);
// Hashmap for ListView
ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url); <---url I am using is http://192.168.0.100:3000/users.json
try {
// Getting Array of Contacts
users = json.getJSONArray(TAG_USERS);
// looping through All Contacts
for(int i = 0; i < users.length(); i++){
JSONObject c = users.optJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String first = c.getString(TAG_FIRST);
String middle = c.getString(TAG_MIDDLE);
String last = c.getString(TAG_LAST);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String mobile = c.getString(TAG_MOBILE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST, first);
map.put(TAG_MIDDLE,middle);
map.put(TAG_LAST, last);
map.put(TAG_ADDRESS, address);
map.put(TAG_MOBILE, mobile);
map.put(TAG_EMAIL, email);
// adding HashList to ArrayList
userList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
我的错误日志文件是: -
04-30 16:24:05.697: E/AndroidRuntime(687): FATAL EXCEPTION: main
04-30 16:24:05.697: E/AndroidRuntime(687): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.library/com.example.library.SecondActivity}: java.lang.IllegalArgumentException: HTTP entity may not be null
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1487)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.widget.TabHost.setCurrentTab(TabHost.java:326)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:132)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:456)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.view.View.performClick(View.java:2485)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.view.View$PerformClick.run(View.java:9080)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.os.Handler.handleCallback(Handler.java:587)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.os.Handler.dispatchMessage(Handler.java:92)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.os.Looper.loop(Looper.java:123)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-30 16:24:05.697: E/AndroidRuntime(687): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 16:24:05.697: E/AndroidRuntime(687): at java.lang.reflect.Method.invoke(Method.java:507)
04-30 16:24:05.697: E/AndroidRuntime(687): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-30 16:24:05.697: E/AndroidRuntime(687): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-30 16:24:05.697: E/AndroidRuntime(687): at dalvik.system.NativeStart.main(Native Method)
04-30 16:24:05.697: E/AndroidRuntime(687): Caused by: java.lang.IllegalArgumentException: HTTP entity may not be null
04-30 16:24:05.697: E/AndroidRuntime(687): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:110)
04-30 16:24:05.697: E/AndroidRuntime(687): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
04-30 16:24:05.697: E/AndroidRuntime(687): at com.example.library.JSONParser.getJSONFromUrl(JSONParser.java:55)
04-30 16:24:05.697: E/AndroidRuntime(687): at com.example.library.SecondActivity.onCreate(SecondActivity.java:51)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-30 16:24:05.697: E/AndroidRuntime(687): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
使用代码json = sb.toString();
时,我得到了value.where,json从第二个代码中调用数据库中的一些值。
如果代码有任何问题,请帮助我并告诉我
答案 0 :(得分:1)
String retSrc = EntityUtils.toString(httpEntity);
// parsing JSON
JSONObject json = new JSONObject(retSrc); //Convert String to JSON Object
而不是
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(); <------Here
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
编辑:我对方法的看法如下:
public JSONArray getJSONFromUrl(String url) {
JSONArray json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
String retSrc = EntityUtils.toString(httpEntity);
// parsing JSON
json = new JSONArray(retSrc); //Convert String to JSON Object
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return JSON String
return json;
}
答案 1 :(得分:0)
您也可以使用:
final String result = EntityUtils.toString(httpEntity);
而不是:
json = sb.toString();
答案 2 :(得分:0)
我的预感是charset
错了,JSON通常应该在UTF-8
中,请尝试:
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 1024);
同时将缓冲区大小从8增加到1024.