AllProductsActivity.java 中的 Logcat 错误
Posted
技术标签:
【中文标题】AllProductsActivity.java 中的 Logcat 错误【英文标题】:Logcat Error at AllProductsActivity.java 【发布时间】:2014-10-21 03:57:07 【问题描述】:运行时出现空指针异常。我在这些行收到异常
下面我发布了 Logcat 和与之相关的代码。
堆栈跟踪:
10-20 07:13:32.092: E/Buffer Error(2936): Error converting result java.lang.NullPointerException: lock == null
10-20 07:13:32.092: E/JSON Parser(2936): Error parsing data org.json.JSONException: End of input at character 0 of
10-20 07:13:32.152: W/dalvikvm(2936): threadid=11: thread exiting with uncaught exception (group=0xb3a7eba8)
10-20 07:13:32.162: E/androidRuntime(2936): FATAL EXCEPTION: AsyncTask #1
10-20 07:13:32.162: E/AndroidRuntime(2936): Process: com.example.androidhive, PID: 2936
10-20 07:13:32.162: E/AndroidRuntime(2936): java.lang.RuntimeException: An error occured while executing doInBackground()
10-20 07:13:32.162: E/AndroidRuntime(2936): at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-20 07:13:32.162: E/AndroidRuntime(2936): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-20 07:13:32.162: E/AndroidRuntime(2936): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-20 07:13:32.162: E/AndroidRuntime(2936): at java.lang.Thread.run(Thread.java:841)
10-20 07:13:32.162: E/AndroidRuntime(2936): Caused by: java.lang.NullPointerException
10-20 07:13:32.162: E/AndroidRuntime(2936): at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
10-20 07:13:32.162: E/AndroidRuntime(2936): at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
10-20 07:13:32.162: E/AndroidRuntime(2936): at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-20 07:13:32.162: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-20 07:13:32.162: E/AndroidRuntime(2936): ... 3 more
10-20 07:13:32.752: I/Choreographer(2936): Skipped 120 frames! The application may be doing too much work on its main thread.
10-20 07:13:33.462: I/Choreographer(2936): Skipped 63 frames! The application may be doing too much work on its main thread.
10-20 07:13:34.722: E/WindowManager(2936): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorViewb3d35370 V.E..... R.....ID 0,0-461,175 that was originally added here
10-20 07:13:34.722: E/WindowManager(2936): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
10-20 07:13:34.722: E/WindowManager(2936): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
10-20 07:13:34.722: E/WindowManager(2936): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.Dialog.show(Dialog.java:286)
10-20 07:13:34.722: E/WindowManager(2936): at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
10-20 07:13:34.722: E/WindowManager(2936): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
10-20 07:13:34.722: E/WindowManager(2936): at android.os.AsyncTask.execute(AsyncTask.java:535)
10-20 07:13:34.722: E/WindowManager(2936): at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.Activity.performCreate(Activity.java:5231)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-20 07:13:34.722: E/WindowManager(2936): at android.os.Handler.dispatchMessage(Handler.java:102)
10-20 07:13:34.722: E/WindowManager(2936): at android.os.Looper.loop(Looper.java:136)
10-20 07:13:34.722: E/WindowManager(2936): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-20 07:13:34.722: E/WindowManager(2936): at java.lang.reflect.Method.invokeNative(Native Method)
10-20 07:13:34.722: E/WindowManager(2936): at java.lang.reflect.Method.invoke(Method.java:515)
10-20 07:13:34.722: E/WindowManager(2936): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-20 07:13:34.722: E/WindowManager(2936): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-20 07:13:34.722: E/WindowManager(2936): at dalvik.system.NativeStart.main(Native Method)
AllProductsActivity.java:
package com.example.androidhive;
public class AllProductsActivity extends ListActivity
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://localhost/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;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute(); ---->57th line
// 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(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
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
* */
@Override
protected void onPreExecute()
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show(); ---->117th line
/**
* 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()); ---->130th line
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(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
runOnUiThread(new Runnable()
public void run()
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] TAG_PID,
TAG_NAME,
new int[] R.id.pid, R.id.name );
// updating listview
setListAdapter(adapter);
);
JsonParser.java:
package com.example.androidhive;
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 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;
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidhive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:configChanges="keyboardHidden|orientation"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainScreenActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- All Product Activity -->
<activity
android:name="com.example.androidhive.AllProductsActivity"
android:label="All Products" >
</activity>
<!-- Add Product Activity -->
<activity
android:name=".NewProductActivity"
android:label="Add New Product" >
</activity>
<!-- Edit Product Activity -->
<activity
android:name=".EditProductActivity"
android:label="Edit Product" >
</activity>
</application>
</manifest>
任何人都可以帮助我。在此先感谢。
【问题讨论】:
在startActivity()
方法之后调用finish()
以及为什么在doInBackground()
中调用return null
?
字符串类型所以我需要返回null。 @Rustam
如果您不想返回任何更好的东西,请将返回类型更改为void
。
@Rustam 然后我得到像这样的编译错误The return type is incompatible with AsyncTask<String,String,String>.doInBackground(String[])
试试这个可能会有所帮助 Log.d("All Products ", "> " + json);
【参考方案1】:
使用您的ip address
而不是本地主机。我通过使用我的 ip 地址而不是使用 loc 解决了这个错误
【讨论】:
【参考方案2】:也许看看这个答案: Json object integrate with android
还要确保在您的 android 代码中,将 AllProductsActivity.java、EditProductActivity.java 和 NewProductActivity.java 中的私有静态 URL 变量更改为您的 IP 地址。例如,对于 AllProductsActivity.java,它应该是:
【讨论】:
以上是关于AllProductsActivity.java 中的 Logcat 错误的主要内容,如果未能解决你的问题,请参考以下文章