我正在开发一个项目,其中来自mysql数据库的数据从我的服务器加载并以ListView的形式显示。但是,当我打开ContentActivity
时,应用程序最终强制关闭时,我遇到了一些障碍。从我的logcat,我得到两组错误:
首先我在第196行(class LoadAllContent extends AsyncTask<String, String, String> {
)和第221行(Log.d("All Posts: ", json.toString());
)上遇到错误。此细分的完整错误是:
10-13 13:42:58.978 20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
10-13 13:42:58.978 20090-20315/? W/System.err? at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
10-13 13:42:58.980 20090-20315/? E/AndroidRuntime? FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:221)
at com.app.appname.ContentActivity$LoadAllContent.doInBackground(ContentActivity.java:196)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
10-13 13:42:59.007 553-3073/? W/ActivityManager? Force finishing activity com.app.appname/.ContentActivity
第二组错误位于第85行(new LoadAllContent().execute();
)和第208行(pDialog.show();
)
10-13 13:42:59.856 20090-20090/? E/WindowManager? Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
android.view.WindowLeaked: Activity com.app.appname.ContentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41ec1f80 V.E..... R......D 0,0-480,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.app.appname.ContentActivity$LoadAllContent.onPreExecute(ContentActivity.java:208)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.app.appname.ContentActivity.onCreate(ContentActivity.java:85)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
我不确定这两个错误是否相关。我的 ContentActivity.java 和 index.php 文件如下所示。
ContentActivity.java
public class ContentActivity extends ListActivity implements ISideNavigationCallback {
Utils util;
final Context context = this;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> contentList;
// url to get all content
private static String getContent = "http://192.168.43.87/app/index.php?act=getContent";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_PID = "id";
private static final String TAG_TITLE = "title";
// products JSONArray
JSONArray posts = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
util = new Utils(this);
TextView appTit = (TextView) findViewById(R.id.appTitle);
String pageTitle = "MySql Database Content";
appTit.setText((CharSequence)pageTitle);
// Hashmap for ListView
contentList = new ArrayList<HashMap<String, String>>();
new LoadAllContent().execute();
// Get listview
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String postId = ((TextView) view.findViewById(R.id.postId)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), ContentViewActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, postId);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all content by making HTTP Request
* */
class LoadAllContent extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContentActivity.this);
pDialog.setMessage("Loading blog. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All content from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(getContent, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Posts: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
posts = json.getJSONArray(TAG_POSTS);
// looping through All Products
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String title = c.getString(TAG_TITLE);
// 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_TITLE, title);
// adding HashList to ArrayList
contentList.add(map);
}
} else {
// no content found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NoPostActivity.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(
ContentActivity.this, contentList,
R.layout.list_item, new String[] { TAG_PID,
TAG_TITLE},
new int[] { R.id.postId, R.id.title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
的index.php
<?php
$action = $_GET['act'];
if ($action == 'getallposts') {
$posts = get_posts('numberposts=10&order=DESC&orderby=post_desc_gmt');
$numPosts = count($posts);
if ($numPosts > 0) {
$response["posts"] = array();
foreach ($posts as $postr) : setup_postdata( $post );
// temp user array
$post = array();
$post['id'] = $postr->ID;
$post["title"] = $postr->post_title;
$post["desc"] = substr($postr->post_content,0,50).'...';
$post['comments'] = $postr->comment_count;
$post["created"] = $postr->post_date_gmt;
array_push($response["posts"], $post);
endforeach;
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
echo json_encode($response);
}
}
?>
我真的很感激任何解决这个问题的方法,因为我所做的所有研究都没有结果。
答案 0 :(得分:0)
只有几条评论:
将Log.d("All Posts: ", json.toString());
移至try .. catch
阻止并抓住NullPointerException
。
您无需在runOnUiThread
上使用postExecute
postExecute
始终在UI线程(主线程)上运行
不要从doInBackground
开始活动(可能是
可能,但不要这样做);从postExecute
执行此操作,而不是这样:
if(success!= 1){
Intent i = new
Intent(getApplicationContext(),NoPostActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}