1

我按照本教程http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/

我尝试制作用于登录的应用程序。当我按照本教程进行操作时,它有错误。我认为它从onProgressDialogat错误,int success = jResponse.getInt("user");但我不知道如何解决它。

登录网址

http://192.168.10.111/user/auth/?login_id=kongkea&password=kongkea&app_id=103574020240693

(在浏览器中)登录成功,返回json

`{
    "user": {
        "user_id": "15",
        "firstname": "kea",
        "lastname": "kong",
        "gender": null,
        "email": null,
        "picture": null,
        "total_friends": 0,
        "total_cards": 0,
        "friend_status": "SELF"
    },
    "token": "NCTak4hOqzLUMCOYkTOG1wFCqjsxI0yKM4YGGw9pa2oz8QNCNiXeWEAOBhvTOHJKAWOvXo9zy2y5Jp9MK1PuSpiT2OALXq94acWsQ1fq0axi2UCD1DENd5Kzf54JL"
}`

仪表板活动

public class DashboardActivity extends BaseActivity {

private EditText etUsername;
private EditText etPassword;
private static String appId = "103574020240693";
private ProgressDialog progressDialog;
private static final int PROGESSDIALOG_ID = 0;
private static final int SERVER_ERROR = 1;
private static final int NETWORK_ERROR = 2;
private static final int CANCELED = 3;
private static final int SUCCESS = 4; 
private String ServerResponse;
private LoginTask loginTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    etUsername = (EditText) findViewById(R.id.loginEmail);
    etPassword = (EditText) findViewById(R.id.loginPassword);

    Button login_button = (Button) findViewById(R.id.btnLogin);
    login_button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if(etUsername.getText().toString().length() == 0
                    || etPassword.getText().toString().length() == 0
                    || appId.length() == 0){
                Toast.makeText(getApplicationContext(), "Please enter username and password", Toast.LENGTH_SHORT).show();
            } else {
                showDialog(PROGESSDIALOG_ID);
            }
        }
    });

    isNetworkAvailable();
}

protected Dialog onCreateDialog(int id) {
    switch(id){
    case PROGESSDIALOG_ID:
        removeDialog(PROGESSDIALOG_ID);
        progressDialog = ProgressDialog.show(DashboardActivity.this, "Authenticating", "Please wait...",true,true, new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if(loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
                    loginTask.cancel(true);
            }
        });
        break;
        default: progressDialog = null;
    }
    return progressDialog;
}



@Override
protected void onPrepareDialog(int id, Dialog dialog){
    switch(id){
    case PROGESSDIALOG_ID:
        if(loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
            loginTask.cancel(true);
        loginTask = new LoginTask();
        loginTask.execute();
    }
}

class LoginTask extends AsyncTask<Void, Integer, Void>{

    @Override
    protected Void doInBackground(Void... unused) {
         try {
            ServerResponse = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet(getString(R.string.webserverurl)
                    +URLEncoder.encode(etUsername.getText().toString(),"UTF-8")
                    +"&password="+ URLEncoder.encode(etPassword.getText().toString(),"UTF-8")+"&app_id="+appId);
            httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Some user agent string");

            if(isCancelled()){
                publishProgress(CANCELED);
                return (null);
            }

            HttpResponse httpResponse = httpClient.execute(httpGet,localContext);
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
            ServerResponse = reader.readLine();
            publishProgress(SUCCESS);
        } catch (UnknownHostException e) {
            removeDialog(PROGESSDIALOG_ID);
            e.printStackTrace();
            publishProgress(NETWORK_ERROR);
        } catch (Exception e){
            removeDialog(PROGESSDIALOG_ID);
            e.printStackTrace();
            publishProgress(SERVER_ERROR);
        }
        return null;
    }


    @Override
    protected void onProgressUpdate(Integer...errorCode){
        switch(errorCode[0]){
        case CANCELED:
            removeDialog(PROGESSDIALOG_ID);
            Toast.makeText(getApplicationContext(), "Cancel by user", Toast.LENGTH_LONG).show();
            break;
        case NETWORK_ERROR:
            removeDialog(PROGESSDIALOG_ID);
            Toast.makeText(getApplicationContext(), "Network connection error", Toast.LENGTH_LONG).show();
            break;
        case SERVER_ERROR:
            removeDialog(PROGESSDIALOG_ID);
            Toast.makeText(getApplicationContext(), "Server Error", Toast.LENGTH_LONG).show();
            break;
        case SUCCESS:
            removeDialog(PROGESSDIALOG_ID);
            try {
                if (ServerResponse != null) {
                    JSONObject jResponse = new JSONObject(ServerResponse);
                    String sMessage = jResponse.getString("user");
                    int success = jResponse.getInt("user");
                    if(success == 1){
                        DashboardActivity.this.finish();
                    } else {
                        Toast.makeText(getApplicationContext(), sMessage, Toast.LENGTH_LONG).show();
                    }
                }

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Server Error", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
            break;
        }
    }

    @Override
    protected void onPostExecute(Void unused){

    }
}

 @Override
 protected void onDestroy(){
     //you may call the cancel() method but if it is not handled in doInBackground() method
     if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
         loginTask.cancel(true);
     super.onDestroy();
 }

}

错误

12-04 14:43:35.258: W/System.err(1039): org.json.JSONException: Value {"picture":null,"total_cards":0,"friend_status":"SELF","email":null,"gender":null,"lastname":"kong","user_id":"15","firstname":"kea","total_friends":0} at user of type org.json.JSONObject cannot be converted to int
12-04 14:43:35.258: W/System.err(1039):     at org.json.JSON.typeMismatch(JSON.java:100)
12-04 14:43:35.258: W/System.err(1039):     at org.json.JSONObject.getInt(JSONObject.java:446)
12-04 14:43:35.268: W/System.err(1039):     at com.example.androidlogin.DashboardActivity$LoginTask.onProgressUpdate(DashboardActivity.java:157)
12-04 14:43:35.268: W/System.err(1039):     at com.example.androidlogin.DashboardActivity$LoginTask.onProgressUpdate(DashboardActivity.java:1)
12-04 14:43:35.268: W/System.err(1039):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)
12-04 14:43:35.268: W/System.err(1039):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 14:43:35.268: W/System.err(1039):     at android.os.Looper.loop(Looper.java:137)
12-04 14:43:35.268: W/System.err(1039):     at android.app.ActivityThread.main(ActivityThread.java:4424)
12-04 14:43:35.268: W/System.err(1039):     at java.lang.reflect.Method.invokeNative(Native Method)
12-04 14:43:35.268: W/System.err(1039):     at java.lang.reflect.Method.invoke(Method.java:511)
12-04 14:43:35.268: W/System.err(1039):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-04 14:43:35.268: W/System.err(1039):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-04 14:43:35.280: W/System.err(1039):     at dalvik.system.NativeStart.main(Native Method)
4

3 回答 3

3

我认为你有问题:

String sMessage = jResponse.getString("user");
int success = jResponse.getInt("user");

假设它应该是:int success = jResponse.getInt("user_id");

于 2012-12-04T08:45:33.467 回答
2

user不是JSONObjectint,因此您应该检索内部JSONObject. 替换

int success = jResponse.getInt("user");

JSONObject userJsonObj  = jResponse.getJSONObject("user")
int success = userJsonObj.getInt("user_id");

您必须使用该userJsonObj对象来检索您需要的内容

于 2012-12-04T09:27:53.343 回答
0

你误用了 AyncTasks :首先你应该在 doInBackground 中进行解析。仅将进度用于进度条或 ui 进度通知。onPostExecute 应该是在成功或失败的情况下更新 ui 的地方。

但在全球范围内,使用 AsyncTask 进行联网并不是一个好主意。javadoc 声明它们是为短期运行的任务而设计的。网络不是一项短期任务。

您应该考虑为您的网络请求使用 android 服务。有一个库可以帮助您:RoboSpice。如果您使用 spring android 模块或 google http java 客户端模块,它将帮助您创建服务并提供开箱即用的 REST 支持。


如果您真的想继续使用 AsyncTask,那么 @Maxim Shoustin 的答案就是您要寻找的。

于 2012-12-04T08:48:47.523 回答