[英]Fatal Exception:Async Task #1
I am trying to get data from mysql database and load it into listview ,but not able to do it because the app crashes after the progress dialog appears.The logcat shows error as An error occured while executing doInBackground().Please help me,this is my java file 我正在尝试从mysql数据库中获取数据并将其加载到listview中,但由于在进度对话框出现后应用程序崩溃而无法执行。logcat显示错误为执行doInBackground()时发生错误。请帮助我,这是我的java文件
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CompScience 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://10.0.2.2/books/get_all_books.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "computerscience";
private static final String TAG_PID = "bid";
private static final String TAG_NAME = "title";
private static final String TAG_DESCRIPTION = "author";
// products JSONArray
JSONArray computerscience = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comp_science);
// 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 Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String description = ((TextView) view).getText().toString();
Intent i = new Intent(CompScience.this,List1.class);
// i.putExtra("description", description);
startActivity(i);
}
});
}
class LoadAllProducts extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CompScience.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
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
computerscience = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < computerscience.length(); i++) {
JSONObject c = computerscience.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
// 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);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
Log.e(TAG_PRODUCTS, "No products 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 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(
CompScience.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME,TAG_DESCRIPTION},
new int[] { R.id.bid, R.id.title,R.id.author });
// updating listview
setListAdapter(adapter);
}
});
}
}
This is the logcat 这是logcat
04-08 02:59:40.928: E/AndroidRuntime(2224): FATAL EXCEPTION: AsyncTask #1
04-08 02:59:40.928: E/AndroidRuntime(2224): java.lang.RuntimeException: An error occured while executing doInBackground()
04-08 02:59:40.928: E/AndroidRuntime(2224): at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.lang.Thread.run(Thread.java:841)
04-08 02:59:40.928: E/AndroidRuntime(2224): Caused by: java.lang.NullPointerException
04-08 02:59:40.928: E/AndroidRuntime(2224): at com.example.dashboard.CompScience$LoadAllProducts.doInBackground(CompScience.java:94)
04-08 02:59:40.928: E/AndroidRuntime(2224): at com.example.dashboard.CompScience$LoadAllProducts.doInBackground(CompScience.java:1)
04-08 02:59:40.928: E/AndroidRuntime(2224): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-08 02:59:40.928: E/AndroidRuntime(2224): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
04-08 02:59:40.928: E/AndroidRuntime(2224): ... 3 more
Browser response: 浏览器响应:
{
"computerscience": [
{
"bid": "1",
"title": "Electronic Principles",
"author": "Albert Malvino & David J Bates"
},
{
"bid": "2",
"title": "Electronic Circuits",
"author": "RD Sudhakar"
},
{
"bid": "3",
"title": "Digital Principles & Applications",
"author": "Leach, Malvino, Saha"
}
],
"success": 1
}
You have a NullpointerException at line 94: 您在第94行有NullpointerException:
Log.d("All Products: ", json.toString());
This means that the object json is equal to null (nothing) and trying to call a method from an object that is nothing will throw an error. 这意味着对象json等于null(无),尝试从无内容的对象调用方法将引发错误。 Check why
jParser.makeHttpRequest(url_all_products, "GET", params);
检查为什么
jParser.makeHttpRequest(url_all_products, "GET", params);
returns null, maybe a parameter is wrong? 返回null,也许参数错误? When it returns a valid result the AsyncTask won't fail again :)
当它返回有效结果时,AsyncTask不会再次失败:)
Try That: 试试看:
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
params.add(new BasicNameValuePair(TAG_APPID, appID));
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
There pas your required parametrs: 有需要的参数:
params.add(new BasicNameValuePair(TAG_APPID, appID));
From: How to connect Android with PHP, MySQL 来自: 如何将Android与PHP,MySQL连接
Please look at your doinbackground method, you are writing
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",params);
Where params are only declared , No params is defined. 仅声明params的地方,未定义params。 It all depends on how you are sending params with request in jParser.makeHttpRequest method.
这完全取决于您如何使用jParser.makeHttpRequest方法中的请求发送参数。 I think if this request need params then define some params, or send empty string if no params required.
我认为如果此请求需要参数,则定义一些参数,如果不需要参数,则发送空字符串。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.