【问题标题】:Android AsyncTask nullAndroid AsyncTask 空
【发布时间】:2014-07-21 03:19:55
【问题描述】:

我正在尝试基于 qr 扫描仪进行“登录”。任务代码的作用是返回一个文本,即用户名,但我收到此错误。有人可以帮帮我吗?

public class LoginActivity extends Activity {
JSONObject usuario;
static String resultadoqr;
public String texto;
private ProgressBar pb;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    //Modifica el layaout para q sea de pantalla completa
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //Se Inicia la view del layout
    setContentView(R.layout.login);
    //Activa la progres bar
    pb=(ProgressBar)findViewById(R.id.progressBar1);
    pb.setVisibility(View.GONE);


}
public String devuelveusuario(){
    return texto;
}
//DETECTAR PULSACION DE BACK

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

  if (keyCode == KeyEvent.KEYCODE_BACK) {

    new AlertDialog.Builder(this)
      .setIcon(android.R.drawable.ic_dialog_alert)
      .setTitle("Salir")
      .setMessage("Estás seguro?")
      .setNegativeButton(android.R.string.cancel, null)//sin listener
      .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {//un listener que al pulsar, cierre la aplicacion
        @Override
        public void onClick(DialogInterface dialog, int which){
          //Salir
            System.exit(0);
        }
      })
      .show();

    // Si el listener devuelve true, significa que el evento esta procesado, y nadie debe hacer nada mas
    return true;
  }
//para las demas cosas, se reenvia el evento al listener habitual
  return super.onKeyDown(keyCode, event);
} 

public void login(View view){
    try{
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }catch(Exception e){
        //AL COMPROBAR Q EL SCANNER NO ESTA INSTALADO, LO INSTALA
        //Toast toast = Toast.makeText(getApplicationContext(),"No se encuentra ZScanner, se procede a instalar la app", Toast.LENGTH_SHORT);
        Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
        Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
        startActivity(marketIntent);
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


//RESULTADO DEL SCANNER FUERA DE LA ASYNC
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

     if (requestCode == 0) {
         if (resultCode == RESULT_OK) {
             resultadoqr= intent.getStringExtra("SCAN_RESULT");
             //String formato = intent.getStringExtra("SCAN_RESULT_FORMAT");
             // Hacer algo con los datos obtenidos.
             //resultado.setText(contenido);
             if (resultadoqr != null) {
                // Quiere decir que se obtuvo resultado por lo tanto:       
                 pb.setVisibility(View.VISIBLE);
                 Log.e("==>","Comenzando peticion: "+resultadoqr);
                 new MyAsyncTask().execute(resultadoqr);
            } else {
                    Toast.makeText(getApplicationContext(),"Usuario no encontrado", Toast.LENGTH_SHORT).show();     
            }

         } else if (resultCode == RESULT_CANCELED) {
             // Si se cancelo la captura.
             Toast toast = Toast.makeText(this, "El escaneo ha sido cancelado", Toast.LENGTH_SHORT);
             toast.show();
         }
     }
}


// CLASE ASYNC DE LOG ON

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();



         @Override
          protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(resultadoqr);
            return null;

          }

         protected void onPostExecute(Double result){
             pb.setVisibility(View.GONE);
             Toast.makeText(getApplicationContext(), "Peticion enviada", Toast.LENGTH_SHORT).show();
             //TextView t = (TextView)findViewById(R.id.nombre);
             //t.setText(texto);
             if(texto.length()<1){
                    // out of range
                 Toast.makeText(getApplicationContext(), "Usuario Erróneo", Toast.LENGTH_LONG).show();
             }else if (texto==null){
                 Toast.makeText(getApplicationContext(), "Error desconocido, contacte con el soporte", Toast.LENGTH_LONG).show();
             }else{
                    Toast.makeText(getApplicationContext(), "Bienvenido usuario "+texto, Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), "¿Qué desea?", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent ("com.oceanapps.bagu.PanelProductosActivity");
                    startActivity(i);
                    finish();
                }


         }
         protected void onProgressUpdate(Integer...progress){
             pb.setProgress(progress[0]);
         }

        public void postData(String valorAEnviar) {

            Log.e("==>","Accediendo a php");
            try {
                String postReceiverUrl = "http://miqueas.segeon.es/posts/post_usuario.php";
                // HttpClient
                HttpClient httpClient = new DefaultHttpClient();

                // post header
                HttpPost httpPost = new HttpPost(postReceiverUrl);

                // add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("usuario", valorAEnviar));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // execute HTTP post request
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity resEntity = response.getEntity();

                if (resEntity != null) {

                    String responseStr = EntityUtils.toString(resEntity).trim();
                    texto = responseStr; 
                    // you can add an if statement here and do other actions based on the response
                }


            } catch (ClientProtocolException e) {

            } catch (IOException e) {
                // process execption
            }catch(Exception ex) { 
                Log.e("ERROR", ex.toString());
            }

        }
    }

}

这是错误。

05-31 13:38:42.117: E/AndroidRuntime(8273): FATAL EXCEPTION: main
05-31 13:38:42.117: E/AndroidRuntime(8273): java.lang.NullPointerException
05-31 13:38:42.117: E/AndroidRuntime(8273):     at com.oceanapps.bagu.LoginActivity$MyAsyncTask.onPostExecute(LoginActivity.java:176)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at com.oceanapps.bagu.LoginActivity$MyAsyncTask.onPostExecute(LoginActivity.java:1)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at android.os.AsyncTask.finish(AsyncTask.java:631)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at android.os.Looper.loop(Looper.java:137)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at android.app.ActivityThread.main(ActivityThread.java:4949)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at java.lang.reflect.Method.invokeNative(Native Method)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at java.lang.reflect.Method.invoke(Method.java:511)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
05-31 13:38:42.117: E/AndroidRuntime(8273):     at dalvik.system.NativeStart.main(Native Method)

PHP 文档没问题,经过测试并且可以运行。

有人可以帮助我吗?谢谢。

【问题讨论】:

  • 请找出哪一行是LoginActivity.java:176
  • 什么是pb?你在哪里initialized呢?
  • LoginActivity.java 的第 176 行发生异常
  • 它的 pb(ProgressBar) 没有被初始化。
  • 对不起,我要编辑我的帖子以显示所有代码。 PB 是一个进度条。

标签: java android android-asynctask nullpointerexception


【解决方案1】:

由于错误是 Nullpointer 并且它在 OnPostExecute 中,很明显它可能是由于pb progressBar 对象或textto 字符串,但它不能是 pb 因为在你调用 AsyncTask 之前你调用了 pb 因此应该没问题,所以我猜唯一的原因是textto 所以我会一步一步解决这个问题......

方法1.用public String texto;替换这个public String texto="Error"; 方法 2. 使用此类 ConnectionClass.java 代替 http 连接(我已针对您的特定情况更改了一些代码,否则此类用于一般用途)。

现在像这样调整异步类代码:-

    private class MyAsyncTask extends AsyncTask<String, Integer, String>{



         @Override
          protected Double doInBackground(String... params) {
   ConnectionClass cc=new ConnectionClass(LoginActivity.this);
   return cc.connectToServer("http://miqueas.segeon.es/posts/post_usuario.php",resultadoqr);


          }

         protected void onPostExecute(String result){
             Toast.makeText(getApplicationContext(), "Peticion enviada", Toast.LENGTH_SHORT).show();
             //t.setText(texto);
             if(result!=""){
                    Toast.makeText(getApplicationContext(), "Bienvenido usuario "+result, Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), "¿Qué desea?", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent ("com.oceanapps.bagu.PanelProductosActivity");
                    startActivity(i);
                    finish();
             }

else{
                 Toast.makeText(getApplicationContext(), "Error desconocido, contacte con el soporte", Toast.LENGTH_LONG).show();
             }

         }

还要检查清单中是否提供了 INTERNET 权限,并检查您在使用应用程序时是否可以连接到网络...

我还执行了另一件事 miqueas.segeon.es/posts/post_usuario.php?usuario=tester 但响应是空白的,所以也要检查一下...

如果有帮助,请尝试以上我尝试调试问题的方法,并希望它有助于让我们知道... :)

谢谢

【讨论】:

    【解决方案2】:

    Texto(您创建的字符串,但没有启动)是崩溃的原因。

    在检查 Texto 的长度之前,您应该在逻辑的第一个部分检查是否为 null。

    例子

     if (text == null) {
    
    } else if (text.length < 1) { 
    
    } else ..
    

    【讨论】:

      【解决方案3】:

      您使用以下代码定义了一个 String 对象:

      public String texto;
      

      但您从未使用值初始化变量。 String 类是可为空的,这意味着它可以为 NULL。在下一行中,您使用该变量,但它尚未在代码中的任何位置初始化。

      if(texto.length()<1){
      

      这是 java 抛出 NULLPointerException 的地方。

      【讨论】:

        【解决方案4】:

        在下面的代码中,您应该检查texto变量是否为空作为第一个条件语句,以便只有在texto不为空时才调用texto.length()。

        改变这个:

                 if(texto.length()<1){
                        // out of range
                     Toast.makeText(getApplicationContext(), "Usuario Erróneo", Toast.LENGTH_LONG).show();
                 }else if (texto==null){
                     Toast.makeText(getApplicationContext(), "Error desconocido, contacte con el soporte", Toast.LENGTH_LONG).show();
                 }else{
                        Toast.makeText(getApplicationContext(), "Bienvenido usuario "+texto, Toast.LENGTH_SHORT).show();
                        Toast.makeText(getApplicationContext(), "¿Qué desea?", Toast.LENGTH_SHORT).show();
                        Intent i = new Intent ("com.oceanapps.bagu.PanelProductosActivity");
                        startActivity(i);
                        finish();
                    }
        

        到这里:

                 if (texto==null){
                     Toast.makeText(getApplicationContext(), "Error desconocido, contacte con el soporte", Toast.LENGTH_LONG).show();
                 }
                 else if(texto.length()<1){
                        // out of range
                     Toast.makeText(getApplicationContext(), "Usuario Erróneo", Toast.LENGTH_LONG).show();
                 }
                 else{
                     Toast.makeText(getApplicationContext(), "Bienvenido usuario "+texto, Toast.LENGTH_SHORT).show();
                     Toast.makeText(getApplicationContext(), "¿Qué desea?", Toast.LENGTH_SHORT).show();
                     Intent i = new Intent ("com.oceanapps.bagu.PanelProductosActivity");
                     startActivity(i);
                     finish();
                    }
        

        【讨论】:

        • 我会得到 texto= null 因为代码: // 执行 HTTP 发布请求 HttpResponse response = httpClient.execute(httpPost);不起作用,我不知道为什么
        【解决方案5】:

        如果不知道哪一行引发了异常,很难判断,但很可能pbtexto 变量是null。请在运行 AsyncTask 之前仔细检查您是否将它们设置为适当的值。

        【讨论】:

          猜你喜欢
          • 2018-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-09
          • 2012-11-16
          • 2015-01-01
          相关资源
          最近更新 更多