我编写了这段代码来从webserver(mysql数据库)读取和写入数据,然后所有数据都会显示在我的andriod应用程序上。
在这方面,我使用PHP服务从Web服务器读取和写入数据。一切正常,它可以正确地从Web服务器获取数据,但是当它到达这一行时:
int success = jsonObject.getInt(TAG_SUCCESS);
它显示了一个空指针异常,我不知道为什么但它实际上让我疯了。
代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.commons.collections.*;
//import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.*;
public class MiddleActivity extends Activity {
Button btnMiddleDB;
ProgressDialog pDialog ;
JSONParser jsonParser = new JSONParser();
JSONArray places = null;
private static final String URL = "http://192.168.1.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> placesList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_middle);
new LoadGettingFromDatabase().execute();
btnMiddleDB = (Button) findViewById(R.id.button1);
btnMiddleDB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
}
运行后台线程以从网络服务器获取数据
class LoadGettingFromDatabase extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MiddleActivity.this);
pDialog.setMessage("Getting from database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
**after getting data from webserver parse it to json and store it into string**
@Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.d("Seen","seen1");
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params);
Log.d("String","JSON 2");
//Log.d("All entries","Entries" + jsonObject.toString());
try{
Log.d("Seen","seen2");
实际上问题在这里
int success = jsonObject.getInt(TAG_SUCCESS);
Log.d("Seen","seen5");
if(success == 1){
//Entries found
Log.d("Seen","seen6");
places = jsonObject.getJSONArray(TAG_PRODUCTS);
for(int i=0;i<places.length();i++){
JSONObject temp = places.getJSONObject(i);
String id = temp.getString(TAG_PID);
String name = temp.getString(TAG_NAME);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TAG_PID, id);
hashMap.put(TAG_NAME, name);
placesList.add(hashMap);
}
}
} catch (Exception e) {
Log.e("success","success status " + e);
}
return null;
}
public void onProExecute(String file_url){
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
ListAdapter listAdapter = new SimpleAdapter(MiddleActivity.this, placesList, R.layout.list_item, new String[]{
TAG_PID, TAG_NAME},new int[]{R.id.ID, R.id.Name});
ListView listView = (ListView) findViewById(R.layout.list_item);
listView.setAdapter(listAdapter);
};
});
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_middle, menu);
return true;
}
}
**and log cat is**
05-07 00:29:54.419: D/Seen(30282): seen1
05-07 00:29:54.569: D/Seen(30282): seen3
05-07 00:29:54.909: D/Seen(30282): seen4
05-07 00:29:54.979: D/String(30282): JSON get_all_products.php
05-07 00:29:54.979: D/String(30282): db_connect.php
05-07 00:29:54.979: D/String(30282): db_config.php
05-07 00:29:54.979: D/String(30282): {"success":0,"message":"No products found
05-07 00:29:55.300: D/String(30282): JSON 1
05-07 00:29:55.300: D/String(30282): JSON 2
05-07 00:29:55.310: D/Seen(30282): seen2
**05-07 00:29:55.310: E/success(30282): success status
java.lang.NullPointerException**
and here is my jsonparser class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
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();
} 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;
}
}
答案 0 :(得分:0)
您的jsonObject为null,通过在line-&gt;
设置断点来调试应用程序JSONObject jsonObject = jsonParser.makeHttpRequest(URL, "GET" ,params);
并检查jsonObject的值。