在Android应用程序中发布请求失败

时间:2014-09-19 10:08:24

标签: android

我正在尝试为我的应用程序执行登录系统。问题是,当我添加一个Bundle来设置我的片段的信息时,请求响应显示该帐户不存在,另一方面,日志显示我正确的帐户信息,wath意味着请求它做得很好,但是我不知道为什么onPostExecute向我显示错误的回应。 以下是

的示例
@Override
    protected void onPostExecute(final Boolean success) {
        //LoginTask = null;
        //showProgress(false);
        if (success) {
            finish();
        } else {
            //password.setError(getString(R.string.error_incorrect_password));
            //password.requestFocus();
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Error !");
            builder.setMessage("The information entered is incorrect.\nPlease try again!")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();

        }

    }

我的DoInBackground功能:

protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

        ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("email", mEmail));
        nameValuePairs.add(new BasicNameValuePair("password", mPassword));

        //Prepare the Post query

        try {
            HttpClient clientHttp = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = clientHttp.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = reader.readLine();
            sb.append(line + "\n");
            is.close();

            String result = sb.toString();
            JSONObject jObj = new JSONObject(result);

            //Affichage de test
            System.out.println(jObj);

            if(jObj.isNull("false")){

                //Créer un Bundle pour déposer les infos
                infos = new Bundle();
                infos.putString("ID",jObj.getString("ID"));
                infos.putString("Name",jObj.getString("display_name"));
                infos.putString("ImgUrl","http://unchained-network.com/uploads/profilpics/53f5c570b6ac2.png");


                Fragment fg = getFragmentManager().findFragmentById(R.id.frgmnt);
                //Charger les infos dans l'activité
                fg.setArguments(infos);

                Intent myIntent = new Intent(getActivity(), HomesActivity.class);
                //Lançer l'activité
                startActivityForResult(myIntent, 0);

            }

        }catch (Exception e){

            return false;
        }

        return true;
    }

日志响应:

09-19 10:00:48.139    2326-2346/com.example.user.unchained I/System.out﹕  {"ID":"50","filename":"5379aae5ef60a.jpeg","display_name":"karim ennassiri"}

错误日志:

09-19 11:10:16.227    2452-2452/com.example.user.unchained E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.unchained, PID: 2452
java.lang.NullPointerException
        at com.example.user.unchained.EmailLoginActivity$LoginTask.onPostExecute(EmailLoginActivity.java:314)
        at com.example.user.unchained.EmailLoginActivity$LoginTask.onPostExecute(EmailLoginActivity.java:239)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

错误的编码。

整个下面的东西应该放在onPostExecute上。这是ui编码不应该在后台进行。试着移动这个

Fragment fg = getFragmentManager().findFragmentById(R.id.frgmnt);
            //Charger les infos dans l'activité
            fg.setArguments(infos);

            Intent myIntent = new Intent(getActivity(), HomesActivity.class);
            //Lançer l'activité
            startActivityForResult(myIntent, 0);

答案 1 :(得分:0)

我认为问题出在finish()调用onPostExecute();好像你想完成AsyncTask的活动。

更好的方法是管理Handler onPostExecute AsyncTask Activity,由UIThread或您要完成的{{1}}管理,在这种情况下触发你可以自己关闭活动

答案 2 :(得分:0)

在主要活动中你应该:

/*
* Declared in the Activity
*/    

private AsyncHandler mAsyncHandler;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    ...
    ...
    mAsyncHandler = new AsyncHandler();
}

并声明如下所示的处理程序:

    public class AsyncHandler extends Handler {
    public static final int BUILD_RESPONSE = 10;
    public static final int FALSE_RESPONSE = 100;
    public static final int TRUE_RESPONSE = 1000;

    @Override
    public void handleMessage(Message msg) {
        stopWaitingProgress();

        switch (msg.what) {
            case BUILD_RESPONSE:
                //Créer un Bundle pour déposer les infos
                infos = new Bundle();
                infos.putString("ID",jObj.getString("ID"));
                infos.putString("Name",jObj.getString("display_name"));
                infos.putString("ImgUrl","http://unchained-network.com/uploads/profilpics/53f5c570b6ac2.png");


                Fragment fg = getFragmentManager().findFragmentById(R.id.frgmnt);
                //Charger les infos dans l'activité
                fg.setArguments(infos);

                Intent myIntent = new Intent(getActivity(), HomesActivity.class);
                //Lançer l'activité
                startActivityForResult(myIntent, 0);

                break;

            case FALSE_RESPONSE:

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Error !");
                builder.setMessage("The information entered is incorrect.\nPlease try again!")
                  .setCancelable(false)
                  .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
                break;


            case TRUE_RESPONSE:
                finish();      <<---  Supposing you have the context for this one
                break;
        }
    }
}

对于班级管理AsyncTask你应该:

    /*
* Declaring a field as AsyncHandler in the class implementing AsyncTask (see below))
*/    
private AsyncHandler mAsyncConnectionHandler;

/*
* ... and whern from the Activity instantiate the AsyncTask, pass the Acitvity
* mAsyncHandler to the AsyncTask mAsyncConnectionHandler field    
*/   


protected Boolean doInBackground(Void... params) {
    // TODO: attempt authentication against a network service.

    try {
        // Simulate network access.
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        return false;
    }

    ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("email", mEmail));
    nameValuePairs.add(new BasicNameValuePair("password", mPassword));

    //Prepare the Post query

    try {
        HttpClient clientHttp = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = clientHttp.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = reader.readLine();
        sb.append(line + "\n");
        is.close();

        String result = sb.toString();
        JSONObject jObj = new JSONObject(result);

        //Affichage de test
        System.out.println(jObj);

        if(jObj.isNull("false")){
            Message msg = Message.obtain(mAsyncConnectionHandler, AsyncHandler.BUILD_RESPONSE);
            mAsyncConnectionHandler.sendMessage(msg);
        }

    }catch (Exception e){

        return false;
    }

    return true;
}


@Override
protected void onPostExecute(final Boolean success) {

    if (success) {

        Message msg = Message.obtain(mAsyncConnectionHandler, AsyncHandler.TRUE_RESPONSE);
        mAsyncConnectionHandler.sendMessage(msg);
    } else {
        Message msg = Message.obtain(mAsyncConnectionHandler, AsyncHandler.FALSE_RESPONSE);
        mAsyncConnectionHandler.sendMessage(msg);
    }

}