我需要从MySQL数据库中收集数据并在Listview中显示,因此我创建了一个Web服务并将其托管在服务器上。然后我开始开发应用程序,但我无法得到结果,我的应用程序崩溃,错误日志没有错误。
这是我显示结果的代码
package com.hotelapp.test;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AllProductsActivity extends ListActivity {
//Progress Dialog
private ProgressDialog pDialog;
//JSONPraser
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String,String>> productsList;
//url to get records
private static String url_all_products = "http://54.243.58.156/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_HID="hid";
private static final String TAG_NAME="name";
JSONArray products = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
//Hashmap for List
productsList = new ArrayList<HashMap<String, String>>();
//Load Products In Backgound
new LoadAllProducts().execute();
//GEt Listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String hid = ((TextView) view.findViewById(R.id.hid)).getText().toString();
//Starting new Intnet
Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
in.putExtra(TAG_HID,hid);
startActivityForResult(in,100);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String,String,String>{
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPerExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading Products...Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
@Override
protected String doInBackground(String... strings) {
// Building Parameters
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_products,"GET",param);
Log.d("All Products: ",json.toString());
try {
//Cehck for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if(success ==1){
//Get Product Arra
products = json.getJSONArray(TAG_PRODUCTS);
//Looping arrays
for(int i=0; i<products.length();i++){
JSONObject c = products.getJSONObject(i);
String id = c.getString(TAG_HID);
String name = c.getString(TAG_NAME);
//creating new Hashmap
HashMap<String, String>map = new HashMap<String, String>();
map.put(TAG_HID,id);
map.put(TAG_NAME,name);
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute (String file_url){
//dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this,productsList,R.layout.list_item,new String[]{TAG_HID,TAG_NAME},
new int[]{R.id.hid,R.id.name}
);
setListAdapter(adapter);
}
});
}
}
}
这是我的Json Parser
package com.hotelapp.test;
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 :(得分:3)
我的猜测是你的问题是因为你的AsyncTask中的一个方法没有正确命名:
protected void onPerExecute(){
应该是:
protected void onPreExecute(){
您可能正在获取NULL指针,因为您要在此方法中创建的资源实际上并未创建。
答案 1 :(得分:0)
要检测此类拼写错误,最好使用注释@overwrite。如果名称不正确,它将产生编译错误。它似乎被意外删除