在Android登录活动中使用AsyncTask时出错

时间:2014-10-31 00:45:17

标签: java android android-asynctask android-studio

我正在尝试使用AsyncTask和PHP / MySQL编写Android登录活动。

我得到了这个logcat:

10-30 17:27:28.708  17111-17111/com.android.fer.prototipo I/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file.
10-30 17:27:28.708  17111-17111/com.android.fer.prototipo I/SELinux﹕ Function: selinux_android_load_priority , loading version is VE=SEPF_SGH-I337M_4.4.2_0017
10-30 17:27:28.708  17111-17111/com.android.fer.prototipo I/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /data/security/spota/seapp_contexts
10-30 17:27:28.718  17111-17111/com.android.fer.prototipo D/dalvikvm﹕ Late-enabling CheckJNI
10-30 17:27:29.178  17111-17111/com.android.fer.prototipo W/ApplicationPackageManager﹕ getCSCPackageItemText()
10-30 17:27:29.278  17111-17111/com.android.fer.prototipo I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build:  (CL3869936)
    OpenGL ES Shader Compiler Version: 17.01.11.SPL
    Build Date: 01/17/14 Fri
    Local Branch:
    Remote Branch:
    Local Patches:
    Reconstruct Branch:
10-30 17:27:29.338  17111-17111/com.android.fer.prototipo D/OpenGLRenderer﹕ Enabling debug mode 0
10-30 17:27:45.104  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: left = 0
10-30 17:27:45.104  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: top = 0
10-30 17:27:45.104  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: right = 144
10-30 17:27:45.104  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: bottom = 144
10-30 17:27:45.864  17111-17444/com.android.fer.prototipo W/dalvikvm﹕ threadid=14: thread exiting with uncaught exception (group=0x4192eda0)
10-30 17:27:45.884  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: left = 0
10-30 17:27:45.884  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: top = 0
10-30 17:27:45.884  17111-17444/com.android.fer.prototipo E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.android.fer.prototipo, PID: 17111
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:518)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
            at com.android.fer.prototipo.library.JSONParser.getJSONFromUrl(JSONParser.java:38)
            at com.android.fer.prototipo.library.UserFunctions.loginUser(UserFunctions.java:28)
            at com.android.fer.prototipo.Login$ProcessLogin.doInBackground(Login.java:152)
            at com.android.fer.prototipo.Login$ProcessLogin.doInBackground(Login.java:132)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
10-30 17:27:45.894  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: right = 144
10-30 17:27:45.894  17111-17111/com.android.fer.prototipo D/ProgressBar﹕ updateDrawableBounds: bottom = 144
10-30 17:27:45.894  17111-17111/com.android.fer.prototipo E/ViewRootImpl﹕ sendUserActionEvent() mView == null
10-30 17:27:46.825  17111-17111/com.android.fer.prototipo E/WindowManager﹕ android.view.WindowLeaked: Activity com.android.fer.prototipo.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42d48840 V.E..... R......D 0,0-1026,486} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:457)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:288)
            at com.android.fer.prototipo.Login$ProcessLogin.onPreExecute(Login.java:147)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.android.fer.prototipo.Login$NetCheck.onPostExecute(Login.java:120)
            at com.android.fer.prototipo.Login$NetCheck.onPostExecute(Login.java:78)
            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:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            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:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
10-30 17:27:47.786  17111-17444/com.android.fer.prototipo I/Process﹕ Sending signal. PID: 17111 SIG: 9

我自己修复了很多错误,但这个错误让我陷入困境,继承了我认为是问题的一些代码:

public class Login extends Activity {
    Button btnLogin;
    EditText inputUsername;
    EditText inputPassword;
    private TextView loginErrorMsg;

private static String KEY_SUCCESS = "success";
private static String KEY_ID = "id";
private static String KEY_USERNAME = "username";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_LASTNAME2 = "lname2";
private static String KEY_EMAIL = "email";
private static String KEY_STATUS = "status";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    inputUsername = (EditText) findViewById(R.id.username);
    inputPassword = (EditText) findViewById(R.id.password);
    btnLogin = (Button) findViewById(R.id.btn_login);
    loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
    /*
    * Evento para boton Login.
    * Se utiliza Toast para alertas cuando hay campos vacios
    **/
    btnLogin.setOnClickListener(new View.OnClickListener(){
       public  void onClick(View view){
           if( (!inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) ){
               NetAsync(view);
           }
           else if( ( !inputUsername.getText().toString().equals("")) ){
               Toast.makeText(getApplicationContext(),"Campo de contraseña vacío", Toast.LENGTH_SHORT).show();
           }
           else if( ( !inputPassword.getText().toString().equals("")) ){
               Toast.makeText(getApplicationContext(),"Campo de matrícula vacío", Toast.LENGTH_SHORT).show();
           }
           else {
               Toast.makeText(getApplicationContext(), "Campos de matrícula y contraseña vacíos", Toast.LENGTH_SHORT).show();
           }
       }
    });
}

/*Verificar conexion a internet
* */

private class NetCheck extends AsyncTask<String, Void, Boolean>{

    private ProgressDialog nDialog;

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        nDialog = new ProgressDialog(Login.this);
        nDialog.setTitle("Verificando Conexión");
        nDialog.setMessage("Verificando..");
        nDialog.setIndeterminate(false);
        nDialog.setCancelable(true);
        nDialog.show();
    }
    @Override
    protected Boolean doInBackground(String... args){
        /*Establecemos conexion con google para verificar que tengamos internet*/
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if(netInfo != null && netInfo.isConnected()){
            try{
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(3000);
                urlc.connect();
                if(urlc.getResponseCode() == 200){
                    return true;
                }
            }catch (MalformedURLException e1){
                //TODO Auto-generated catch block
                e1.printStackTrace();
            }catch (IOException e){
                //TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }
    @Override
    protected void onPostExecute(Boolean th){
        if(th == true){
            nDialog.dismiss();
            new ProcessLogin().execute();
        }
        else{
            nDialog.dismiss();
            loginErrorMsg.setText("Error en conexión a internet");
        }
    }
}

/*
Async Task para conectarse con BD MySQL a traves de JSON
 */
private class ProcessLogin extends AsyncTask<String, Void, JSONObject>{
    private ProgressDialog pDialog;
    String username , password;
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        inputUsername = (EditText) findViewById(R.id.username);
        inputPassword = (EditText) findViewById(R.id.password);
        username = inputUsername.getText().toString();
        password = inputPassword.getText().toString();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setTitle("Conectando a servidores");
        pDialog.setMessage("Iniciando sesión..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected JSONObject doInBackground(String... args){
        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(username,password);
        return json;
    }
    @Override
    protected void onPostExecute(JSONObject json){
        try {
            if (json.getString(KEY_SUCCESS) != null){
                String res = json.getString(KEY_SUCCESS);
                if (Integer.parseInt(res) == 1){
                    pDialog.setMessage("Cargando perfil de usuario");
                    pDialog.setTitle("Obteniendo información");
                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    JSONObject json_user = json.getJSONObject("user");
                    /*Limpiar datos en SQlite*/
                    UserFunctions logout = new UserFunctions();
                    logout.logoutUser(getApplicationContext());
                    db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_LASTNAME2), json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_ID),json_user.getString(KEY_STATUS));
                    /*
                    Si arreglo JSON esta almacenado en SQlite lanza el panel de usuario
                     */
                    pDialog.dismiss();
                    Intent upanel = new Intent(getApplicationContext(),Main.class);
                    upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    pDialog.dismiss();
                    startActivity(upanel);
                    finish();
                }else{
                    pDialog.dismiss();
                    loginErrorMsg.setText("Datos incorrectos");
                }
            }

        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}
public void NetAsync(View view){
    new NetCheck().execute();
}

2 个答案:

答案 0 :(得分:1)

看看这个,

http://loopj.com/android-async-http/

它是一个非常有用的库,它消除了使用内部类的所有复杂性。我还认为你应该将你的api客户端代码隔离到一个完全不同的包。

答案 1 :(得分:0)

你的代码很长。我建议你使用Volley Library和Loop4j Library。

排球图书馆示例:

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Loop4J Library示例:

http://loopj.com/android-async-http/