Java 在尝试使用异步任务发出GET请求时,如何阻止应用程序崩溃?
我真的很困惑为什么我会有这个问题。我对android开发非常陌生,所以我不确定在解决这个问题时从哪里开始。我在清单文件中拥有所有必需的权限。和 当按下一个按钮时,将调用myClickHandler并创建一个包含两个EditText的URL。然后调用DownloadWebPagetTask,启动一个异步任务。此AsyncTank获取URL,然后发送GET请求。这是我的密码Java 在尝试使用异步任务发出GET请求时,如何阻止应用程序崩溃?,java,android,get,Java,Android,Get,我真的很困惑为什么我会有这个问题。我对android开发非常陌生,所以我不确定在解决这个问题时从哪里开始。我在清单文件中拥有所有必需的权限。和 当按下一个按钮时,将调用myClickHandler并创建一个包含两个EditText的URL。然后调用DownloadWebPagetTask,启动一个异步任务。此AsyncTank获取URL,然后发送GET请求。这是我的密码 public void myClickHandler(View view) { SetText url = new S
public void myClickHandler(View view) {
SetText url = new SetText();
String stringUrl = url.createURL(artist_text.getText().toString(), release_text.getText().toString());
new DownloadWebpageTask().execute(stringUrl);
}
public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
//SendStuff send = new SendStuff("mrblahblahblacksheep");
//return send.sendGet(urls[0]);
String url = urls[0];
String final_response = "FAILED!";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(request);
final_response = response.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return final_response;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
result_text.setText(result);
}
}
每次我按下模拟器中的按钮,应用程序就会崩溃。所有碰撞数据均未保存在logcat中,因此我不确定是否需要磨损以找出碰撞原因。这可能是问题所在:
response = client.execute(request);
final_response = response.toString();
如果response为null,则response.toString将抛出NPE,您的应用程序将崩溃
使错误处理变得优雅
遇到异常时,请尝试从catch块返回null结果。此外,对于NPE,make if else阻塞并显式返回null
在onPostExecute中。。。检查结果是否为空,然后显示一些默认文本或显示预期结果。您是否尝试使用断点缩小问题范围?就是这样做的。应用程序尝试发送GET请求时崩溃。因此,当它发送response=client.executerequestIs result\u text时,result\u text被初始化。代码blockLogcat URL中没有显示它,最终响应plzDoesn似乎不是问题所在。设置response.toString之前应用程序崩溃。我尝试了新的下载WebPagetAsk.executehttp://www.thomas-bayer.com/sqlrest/CUSTOMER/3/; 它非常适合我。除非我们知道您使用的URL,否则很难找出问题所在。请尝试获取应用程序的日志。还有,您正在使用的设备和操作系统。