我知道有很多问题都是这样问的,但是我已经查看了所有问题,但没有一个答案对我有用。
这是我的java类
public class AllBugsActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> bugsList;
private static String url_all_bugs = "http://10.0.2.2/FinalYearProject/FYPFinal/android_connect/get_all_bugs.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_BUGS = "bugs";
private static final String TAG_BID = "bid";
private static final String TAG_NAME = "name";
JSONArray bugs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_bugs);
bugsList = new ArrayList<HashMap<String, String>>();
new LoadAllBugs().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bid = ((TextView) view.findViewById(R.id.bid)).getText()
.toString();
Intent in = new Intent(getApplicationContext(),
EditBugActivity.class);
in.putExtra(TAG_BID, bid);
startActivityForResult(in, 100);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllBugs extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllBugsActivity.this);
pDialog.setMessage("Loading bugs. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_bugs, "GET", params);
Log.d("All Bugs: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
bugs = json.getJSONArray(TAG_BUGS);
for (int i = 0; i < bugs.length(); i++) {
JSONObject c = bugs.getJSONObject(i);
String id = c.getString(TAG_BID);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_BID, id);
map.put(TAG_NAME, name);
bugsList.add(map);
}
} else {
Intent i = new Intent(getApplicationContext(),
NewBugActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
AllBugsActivity.this, bugsList,
R.layout.list_bug, new String[] { TAG_BID,
TAG_NAME},
new int[] { R.id.bid, R.id.name });
setListAdapter(adapter);
}
});
}
}
}
继承我的JSONParser类
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;
}
}
继续犯错误
03-21 17:06:15.158 1266-1280/com.example.neil.fypy4 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$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:98)
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.doInBackground(AllBugsActivity.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
03-21 17:06:15.511 1266-1266/com.example.neil.fypy4 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-21 17:06:16.008 1266-1266/com.example.neil.fypy4 E/WindowManager﹕ Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41cd1748 that was originally added here
android.view.WindowLeaked: Activity com.example.neil.fypy4.AllBugsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41cd1748 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at com.example.neil.fypy4.AllBugsActivity$LoadAllBugs.onPreExecute(AllBugsActivity.java:92)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.example.neil.fypy4.AllBugsActivity.onCreate(AllBugsActivity.java:50)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
我的php课程
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM bugs") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["bugs"] = array();
while ($row = mysql_fetch_array($result)) {
$bug = array();
$bug["bid"] = $row["bid"];
$bug["name"] = $row["name"];
$bug["severity"] = $row["severity"];
$bug["description"] = $row["description"];
$bug["created_at"] = $row["created_at"];
$bug["updated_at"] = $row["updated_at"];
array_push($response["bugs"], $bug);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No bugs found";
echo json_encode($response);
}
?>
非常感谢任何帮助。
答案 0 :(得分:1)
因此,在您的堆栈跟踪中,它会显示行号:从中您可以在您的NPE来源代码中进行三角测量。由于您未在此处提供行号,我将猜测int success = json.getInt(TAG_SUCCESS);
是否会导致NPE。原因是它是doInBackground(...)
中第一个可能为null的对象 - 如果查看JSONParser
类,则返回jObj
,这是一个初始化为null的字段成员,并且仅设置是否未发生错误。也就是说,您不会检查doInBackground(...)
JSONObject json
是否从= jParser.makeHttpRequest(url_all_bugs, "GET", params);
返回null,而是依赖TAG_SUCCESS
。但这是一个鸡和蛋的问题,因为如果它失败了它可以为null并且没有标签来检查是否成功!
无论如何,我的建议是在(json != null)
的try / catch之前添加doInBackground(...)
。您可能会发现您的JSONParser
类无法正确解析。您可以使用堆栈跟踪中的行号来查明问题的来源,或者只使用调试器并逐步执行代码。
另外,从变量开始,您可以使public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)
成为静态方法
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
不需要是类作用域(它们已经是静态的!)。只需使它们成为方法范围并有一个方便的静态方法调用来解析你的json。
最终评论:您无需从runOnUiThread(...)
调用onPostExecute(...)
因为onPostExecute(...)
在每个Async任务的UI线程上运行。这就是Async任务的工作原理。