在android中使用asynctask时,如何处理异常?
说明: 我正在为我的应用程序使用web服务。其中,每个请求都>使用GET方法。因此,创建一个类,在其中我还创建了一个方法来设置>url并从服务器获取响应 这里是我的类,它从服务器获取响应在android中使用asynctask时,如何处理异常?,android,android-asynctask,Android,Android Asynctask,说明: 我正在为我的应用程序使用web服务。其中,每个请求都>使用GET方法。因此,创建一个类,在其中我还创建了一个方法来设置>url并从服务器获取响应 这里是我的类,它从服务器获取响应 package adapter; import android.content.Context; import android.util.Log; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOExc
package adapter;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
public class CallAPI {
private Context context;
public String GetResponseGetMethod(String url) {
URL obj;
String Response="";
String getMethodResponse = "";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.e("GET Response Code :: " , ""+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\n");
}
in.close();
// print result
getMethodResponse=response.toString();
Log.e("Response",response.toString());
} else {
Log.e("GET request not worked","");
}
}
catch (MalformedURLException e) {
Toast.makeText(context, "YEs got it", Toast.LENGTH_LONG).show();
}
catch (IOException e){
Toast.makeText(context, "YEs Inside IO it", Toast.LENGTH_LONG).show();
}
return getMethodResponse;
}
}
以上班级得到回应
这是我使用Asynktask的班级
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
@Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
@Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public类TabJson扩展异步任务{
字符串jsonStr=“”;
@凌驾
受保护的void onPreExecute(){
Utils.Pdialog(getContext());
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
jsonStr=newcallapi().GetResponseGetMethod(url);
if(jsonStr!=null){
试一试{
JSONObject obj=新的JSONObject(jsonStr);
}捕获(JSONException e){
e、 printStackTrace();
}
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
}
}
有时需要时间才能得到回应
我的问题是:
当获取响应的时间太长时,我如何处理这种情况。它还引发了一个类似unknowhostapi的异常
如何克服这个问题。请帮助我解决这个问题。@Milan我在您的代码中没有看到任何异步任务。如果要实现AsyncTask,请执行以下步骤- 1.扩展异步任务 2.重写doInBackground()和postExecute方法
package adapter;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
public class CallAPI {
private Context context;
public String GetResponseGetMethod(String url) {
URL obj;
String Response="";
String getMethodResponse = "";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.e("GET Response Code :: " , ""+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\n");
}
in.close();
// print result
getMethodResponse=response.toString();
Log.e("Response",response.toString());
} else {
Log.e("GET request not worked","");
}
}
catch (MalformedURLException e) {
Toast.makeText(context, "YEs got it", Toast.LENGTH_LONG).show();
}
catch (IOException e){
Toast.makeText(context, "YEs Inside IO it", Toast.LENGTH_LONG).show();
}
return getMethodResponse;
}
}
<uses-permission android:name="android.permission.INTERNET" />
您必须使处理服务器的函数返回一些可以包含所有可能结果的对象,而不仅仅是成功案例。例如:
class Results {
public String result;
public Err error;
public enum Err {
OK, ERR1, ERR2, ERR3
}
}
因此,如果一切正常,则将结果字符串设置为响应,将错误枚举设置为OK。或者,如果存在其他错误,请使用定义的另一个枚举。在接收结果的代码中,您可以检查错误类型以确定如何处理它。您的代码存在一些问题:
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
您正在返回null
。而是返回字符串
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
return jsonStr;
}
现在,在post execute中,将其格式化为jsonObject,如下所示:
@Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject obj = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
现在,您有了
JSONobject
obj。用它做点什么。@millan在您的callAPI类中为catch块中的getMehodResponse分配一些值,如下所示-
public class CallAPI {
private Context context;
public String GetResponseGetMethod(String url) {
URL obj;
String Response="";
String getMethodResponse = "";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.e("GET Response Code :: " , ""+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\n");
}
in.close();
// print result
getMethodResponse=response.toString();
Log.e("Response",response.toString());
} else {
Log.e("GET request not worked","");
}
}
catch (MalformedURLException e) {
getMethodResponse="Malformed";
Toast.makeText(context, "YEs got it", Toast.LENGTH_LONG).show();
}
catch (IOException e){
getMethodResponse="IO";
Toast.makeText(context, "YEs Inside IO it", Toast.LENGTH_LONG).show();
}
return getMethodResponse;
}
}
In-TabJson类返回以下In-doInBackground方法-
@Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
return jsonStr;
}
在TabJson类中,在onPostExecute方法中使用以下代码-
@Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
//Show pop up or alert msg here.
}
}
switch(s){
case "IO":
//Do what you want to show your user.
break;
case "Malformed":
//Do what you want to show your user.
break;
}
super.onPostExecute(s);
}
也可以发布您如何使用此方法的代码?与
asynctask
一样,您需要使用asynctask。我编辑了我的帖子,我想这取决于你的网络连接。记录您从服务器获得的所有结果。我无法理解它返回了什么?这是回复吗?在你编辑之后,我的回答没有任何意义。您已经在代码中使用了asynctask。我可以设置asynctask在停止执行10秒后仅执行10秒吗?有可能吗?现在告诉我根据这种情况我会怎么做?我创建了一个方法,因为每次我都没有在每个活动和片段中放入相同的代码。