我已经将数据库中的数据读取到了android。我复制了代码并在我的其他应用程序中再次使用它它给了我这个错误。
LOGCAT:
07-08 08:52:24.422: E/Buffer Error(2636): Error converting result java.lang.NullPointerException: lock == null
07-08 08:52:24.422: E/JSON Parser(2636): Error parsing data org.json.JSONException: End of input at character 0 of
07-08 08:52:24.423: D/AndroidRuntime(2636): Shutting down VM
07-08 08:52:24.424: E/AndroidRuntime(2636): FATAL EXCEPTION: main
07-08 08:52:24.424: E/AndroidRuntime(2636): Process: com.example.purplerose, PID: 2636
07-08 08:52:24.424: E/AndroidRuntime(2636): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.purplerose/com.example.purplerose._Appetizer}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
PHP CODE数据已经显示
<?PHP
include_once("connection.php");
$sql = "SELECT MenuID, Name, Description2, Price FROM menu";
$result = mysqli_query($con,$sql);
$json = array();
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$json['menu'][]=$row;
}
}
mysqli_close($con);
echo json_encode($json); ?>
JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
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;
}}
JAVA代码
ListView mListView = (ListView) findViewById(R.id.listView1);
String url = "http://10.0.2.2/purple/readMenu.php";
try {
JSONParser jParser = new JSONParser();
JSONObject table = jParser.getJSONFromUrl(url);
JSONArray data = table.getJSONArray("menu");
//JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("MenuID", c.getString("MenuID"));
map.put("Name", c.getString("Name"));
map.put("Description2", c.getString("Description2"));
map.put("Price", c.getString("Price"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(_Appetizer.this, MyArrList, R.layout.menulist_arrangement,
new String[] {"Name", "Description2", "Price", "MenuID"}, new int[] {R.id.lblName, R.id.lblDesc2, R.id.lblPrice, R.id.lblMenuID});
mListView.setAdapter(sAdap);
final AlertDialog.Builder viewDetail = new AlertDialog.Builder(this);
// OnClick Item
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView,
int position, long mylng) {
String _Name = MyArrList.get(position).get("Name")
.toString();
String _Desc2 = MyArrList.get(position).get("Description2")
.toString();
String _Price = MyArrList.get(position).get("Price")
.toString();
String _MenuID = MyArrList.get(position).get("MenuID")
.toString();
//String sMemberID = ((TextView) myView.findViewById(R.id.ColMemberID)).getText().toString();
// String sName = ((TextView) myView.findViewById(R.id.ColName)).getText().toString();
// String sTel = ((TextView) myView.findViewById(R.id.ColTel)).getText().toString();
viewDetail.setIcon(android.R.drawable.btn_star_big_on);
viewDetail.setTitle(_Name);
viewDetail.setMessage("Name : " + _Name + "\n"
+ "Description : " + _Desc2 + "\n" + "Price : " + _Price + "\n" + "ID: " + _MenuID);
viewDetail.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
viewDetail.show();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("Log", "Failed" +e);
e.printStackTrace();
}
仔细检查JSONParser类。或者我的java代码。我真的不知道空指针在哪里。
答案 0 :(得分:0)
在阅读完源代码和异常日志之后,我认为您的NPE的根本原因是您尝试在UI线程上执行网络操作,这是Google在Android 3+上禁止的。您可以使用AsyncTask
访问网络。