我正在尝试在片段中生成列表视图。代码显示没有错误,但是当我尝试启动应用程序时,在progressdialog显示之后,应用程序crashed.below是我的HomeFragment.java文件。请帮忙。我是Android开发的新手。
HomeFragment.java
public class HomeFragment extends ListFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser2 jParser = new JSONParser2();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://gemini888.tk/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";
// products JSONArray
JSONArray products = null;
//@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
return inflater.inflate(R.layout.all_products,container,false);
}
@Override
public void onStart() {
super.onStart();
initControls();
}
//@SuppressLint("NewApi")
public void initControls(){
//testing
// if (android.os.Build.VERSION.SDK_INT > 9)
// {
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
// }
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(),EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
public 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 = getActivity().getIntent();
getActivity().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
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pDialog;
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
我得到的logcat:
04-20 00:04:09.071: I/Choreographer(1257): Skipped 54 frames! The application may be doing too much work on its main thread.
04-20 00:04:09.251: I/Choreographer(1257): Skipped 109 frames! The application may be doing too much work on its main thread.
04-20 00:04:09.331: D/All Products:(1257): {"success":1,"products":[{"created_at":"2015-04-15 21:52:09","pid":"1","updated_at":"0000-00-00 00:00:00","price":"1111.00","description":"good","name":"iphone "},{"created_at":"2015-04-18 02:41:49","pid":"13","updated_at":"0000-00-00 00:00:00","price":"25.00","description":"cheap\n\n","name":"Samsung "},{"created_at":"2015-04-18 03:26:40","pid":"14","updated_at":"0000-00-00 00:00:00","price":"1000.00","description":"bad\n","name":"xiaomi"}]}
04-20 00:04:09.391: I/Choreographer(1257): Skipped 46 frames! The application may be doing too much work on its main thread.
04-20 00:04:09.451: D/AndroidRuntime(1257): Shutting down VM
04-20 00:04:09.451: W/dalvikvm(1257): threadid=1: thread exiting with uncaught exception (group=0xb2a26ba8)
04-20 00:04:09.551: E/AndroidRuntime(1257): FATAL EXCEPTION: main
04-20 00:04:09.551: E/AndroidRuntime(1257): Process: mygp.gptrade, PID: 1257
04-20 00:04:09.551: E/AndroidRuntime(1257): java.lang.NullPointerException
04-20 00:04:09.551: E/AndroidRuntime(1257): at mygp.gptrade.HomeFragment$LoadAllProducts.onPostExecute(HomeFragment.java:200)
04-20 00:04:09.551: E/AndroidRuntime(1257): at mygp.gptrade.HomeFragment$LoadAllProducts.onPostExecute(HomeFragment.java:1)
04-20 00:04:09.551: E/AndroidRuntime(1257): at android.os.AsyncTask.finish(AsyncTask.java:632)
04-20 00:04:09.551: E/AndroidRuntime(1257): at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-20 00:04:09.551: E/AndroidRuntime(1257): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
04-20 00:04:09.551: E/AndroidRuntime(1257): at android.os.Handler.dispatchMessage(Handler.java:102)
04-20 00:04:09.551: E/AndroidRuntime(1257): at android.os.Looper.loop(Looper.java:136)
04-20 00:04:09.551: E/AndroidRuntime(1257): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-20 00:04:09.551: E/AndroidRuntime(1257): at java.lang.reflect.Method.invokeNative(Native Method)
04-20 00:04:09.551: E/AndroidRuntime(1257): at java.lang.reflect.Method.invoke(Method.java:515)
04-20 00:04:09.551: E/AndroidRuntime(1257): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-20 00:04:09.551: E/AndroidRuntime(1257): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-20 00:04:09.551: E/AndroidRuntime(1257): at dalvik.system.NativeStart.main(Native Method)
04-20 00:04:16.831: I/Process(1257): Sending signal. PID: 1257 SIG: 9
tknell: logcat我得到第二个错误。
04-20 05:01:19.800: D/All Products:(1039): {"success":1,"products":[{"created_at":"2015-04-15 21:52:09"," pid":"1","updated_at":"0000-00-00 00:00:00","price":"1111.00","description":"good","name":"iphone "},{"created_at":"2015-04-18 02:41:49"," pid":"13","updated_at":"0000-00-00 00:00:00","price":"25.00","description":"cheap\n\n","name":"Samsung "},{"created_at":"2015-04-18 03:26:40","pid":"14","updated_at":"0000-00-00 00:00:00","price":"1000.00","description":"bad\n","name":"xiaomi"}]} 04-20 05:01:20.060: I/Choreographer(1039): Skipped 142 frames! The application may be doing too much work on its main thread. 04-20 05:01:20.560: I/Choreographer(1039): Skipped 48 frames! The application may be doing too much work on its main thread. 04-20 05:01:27.370: I/Choreographer(1039): Skipped 116 frames! The application may be doing too much work on its main thread. 04-20 05:01:29.990: D/dalvikvm(1039): GC_FOR_ALLOC freed 301K, 10% free 3623K/3992K, paused 351ms, total 360ms 04-20 05:01:30.760: I/Choreographer(1039): Skipped 65 frames! The application may be doing too much work on its main thread. 04-20 05:01:32.810: D/AndroidRuntime(1039): Shutting down VM 04-20 05:01:32.810: W/dalvikvm(1039): threadid=1: thread exiting with uncaught exception (group=0xb2a26ba8) 04-20 05:01:32.920: E/AndroidRuntime(1039): FATAL EXCEPTION: main 04-20 05:01:32.920: E/AndroidRuntime(1039): Process: mygp.gptrade, PID: 1039 04-20 05:01:32.920: E/AndroidRuntime(1039): android.os.NetworkOnMainThreadException 04-20 05:01:32.920: E/AndroidRuntime(1039): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 04-20 05:01:32.920: E/AndroidRuntime(1039): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 04-20 05:01:32.920: E/AndroidRuntime(1039): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 04-20 05:01:32.920: E/AndroidRuntime(1039): at java.net.InetAddress.getAllByName(InetAddress.java:214) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 04-20 05:01:32.920: E/AndroidRuntime(1039): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 04-20 05:01:32.920: E/AndroidRuntime(1039): at mygp.gptrade.JSONParser2.makeHttpRequest(JSONParser2.java:62) 04-20 05:01:32.920: E/AndroidRuntime(1039): at mygp.gptrade.EditProductActivity$GetProductDetails$1.run(EditProductActivity.java:131) 04-20 05:01:32.920: E/AndroidRuntime(1039): at android.os.Handler.handleCallback(Handler.java:733) 04-20 05:01:32.920: E/AndroidRuntime(1039): at android.os.Handler.dispatchMessage(Handler.java:95) 04-20 05:01:32.920: E/AndroidRuntime(1039): at android.os.Looper.loop(Looper.java:136) 04-20 05:01:32.920: E/AndroidRuntime(1039): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-20 05:01:32.920: E/AndroidRuntime(1039): at java.lang.reflect.Method.invokeNative(Native Method) 04-20 05:01:32.920: E/AndroidRuntime(1039): at java.lang.reflect.Method.invoke(Method.java:515) 04-20 05:01:32.920: E/AndroidRuntime(1039): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-20 05:01:32.920: E/AndroidRuntime(1039): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-20 05:01:32.920: E/AndroidRuntime(1039): at dalvik.system.NativeStart.main(Native Method)EditProductActivity.java
public class EditProductActivity extends Activity {
EditText txtName; EditText txtPrice; EditText txtDesc; EditText txtCreatedAt; Button btnSave; Button btnDelete; String pid; // Progress Dialog private ProgressDialog pDialog; // JSON parser class JSONParser2 jsonParser2 = new JSONParser2(); // single product url private static final String url_product_detials = "http://gemini888.tk/android_connect/get_product_details.php"; // url to update product private static final String url_update_product = "http://gemini888.tk/android_connect/update_product.php"; // url to delete product private static final String url_delete_product = "http://gemini888.tk/android_connect/delete_product.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCT = "product"; private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; private static final String TAG_PRICE = "price"; private static final String TAG_DESCRIPTION = "description"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_product); // save button btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); // getting product details from intent Intent i = getIntent(); // getting product id (pid) from intent pid = i.getStringExtra(TAG_PID); // Getting complete product details in background thread new GetProductDetails().execute(); // save button click event btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // starting background task to update product new SaveProductDetails().execute(); } }); // Delete button click event btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // deleting product in background thread new DeleteProduct().execute(); } }); } /** * Background Async Task to Get complete product details * */ class GetProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this); pDialog.setMessage("Loading product details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Getting product details in background thread * */ protected String doInBackground(String... params) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", pid)); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = jsonParser2.makeHttpRequest( url_product_detials, "GET", params); // check your log for json response Log.d("Single Product Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully received product details JSONArray productObj = json .getJSONArray(TAG_PRODUCT); // JSON Array // get first product object from JSON Array JSONObject product = productObj.getJSONObject(0); // product with this pid found // Edit Text txtName = (EditText) findViewById(R.id.inputName); txtPrice = (EditText) findViewById(R.id.inputPrice); txtDesc = (EditText) findViewById(R.id.inputDesc); // display product data in EditText txtName.setText(product.getString(TAG_NAME)); txtPrice.setText(product.getString(TAG_PRICE)); txtDesc.setText(product.getString(TAG_DESCRIPTION)); }else{ // product with pid not found } } catch (JSONException e) { e.printStackTrace(); } } }); return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once got all details pDialog.dismiss(); } } /** * Background Async Task to Save product Details * */ class SaveProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this); pDialog.setMessage("Saving product ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Saving product * */ protected String doInBackground(String... args) { // getting updated data from EditTexts String name = txtName.getText().toString(); String price = txtPrice.getText().toString(); String description = txtDesc.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_PID, pid)); params.add(new BasicNameValuePair(TAG_NAME, name)); params.add(new BasicNameValuePair(TAG_PRICE, price)); params.add(new BasicNameValuePair(TAG_DESCRIPTION, description)); // sending modified data through http request // Notice that update product url accepts POST method JSONObject json = jsonParser2.makeHttpRequest(url_update_product, "POST", params); // check json success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully updated Intent i = getIntent(); // send result code 100 to notify about product update setResult(100, i); finish(); } else { // failed to update product } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product uupdated pDialog.dismiss(); } } /***************************************************************** * Background Async Task to Delete Product * */ class DeleteProduct extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this); pDialog.setMessage("Deleting Product..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Deleting product * */ protected String doInBackground(String... args) { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", pid)); // getting product details by making HTTP request JSONObject json = jsonParser2.makeHttpRequest( url_delete_product, "POST", params); // check your log for json response Log.d("Delete Product", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // product successfully deleted // notify previous activity by sending code 100 Intent i = getIntent(); // send result code 100 to notify about product deletion setResult(100, i); finish(); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted pDialog.dismiss(); } }
}
第3次logcat (没有runOnUiThread) 04-21 04:34:25.747:E / WindowManager(1154):android.view.WindowLeaked:Activity mygp.gptrade.EditProductActivity泄露了窗口com.android.internal.policy.impl.PhoneWindow $ DecorView {b2e99188 VE ...最初添加的R ..... ID 0,0-320,96} 04-21 04:34:25.747:E / WindowManager(1154):在android.view.ViewRootImpl。(ViewRootImpl.java:348) 04-21 04:34:25.747:E / WindowManager(1154):在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248) 04-21 04:34:25.747:E / WindowManager(1154):在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.Dialog.show(Dialog.java:286) 04-21 04:34:25.747:E / WindowManager(1154):at mygp.gptrade.EditProductActivity $ GetProductDetails.onPreExecute(EditProductActivity.java:111) 04-21 04:34:25.747:E / WindowManager(1154):在android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) 04-21 04:34:25.747:E / WindowManager(1154):在android.os.AsyncTask.execute(AsyncTask.java:535) 04-21 04:34:25.747:E / WindowManager(1154):at mygp.gptrade.EditProductActivity.onCreate(EditProductActivity.java:72) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.Activity.performCreate(Activity.java:5231) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.ActivityThread.access $ 800(ActivityThread.java:135) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1196) 04-21 04:34:25.747:E / WindowManager(1154):在android.os.Handler.dispatchMessage(Handler.java:102) 04-21 04:34:25.747:E / WindowManager(1154):在android.os.Looper.loop(Looper.java:136) 04-21 04:34:25.747:E / WindowManager(1154):在android.app.ActivityThread.main(ActivityThread.java:5017) 04-21 04:34:25.747:E / WindowManager(1154):at java.lang.reflect.Method.invokeNative(Native Method) 04-21 04:34:25.747:E / WindowManager(1154):at java.lang.reflect.Method.invoke(Method.java:515) 04-21 04:34:25.747:E / WindowManager(1154):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779) 04-21 04:34:25.747:E / WindowManager(1154):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-21 04:34:25.747:E / WindowManager(1154):at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
将此代码添加到您的postExecute方法
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
答案 1 :(得分:0)
您声明成员pDialog
并使用它来解除onPostExecute
方法中的对话框,但在onPreExecute
方法中,您声明另一个保存已创建的pDialog
变量对话框而不是您的成员。因此,当您尝试关闭对话框时,成员变量pDialog
为空。
要解决此问题,请移除pDialog
中的其他onPreExecute
变量:
旧:
ProgressDialog pDialog;
pDialog = new ProgressDialog(getActivity());
新:
pDialog = new ProgressDialog(getActivity());