Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android异步任务空_Java_Android_Android Asynctask_Nullpointerexception - Fatal编程技术网

Java Android异步任务空

Java Android异步任务空,java,android,android-asynctask,nullpointerexception,Java,Android,Android Asynctask,Nullpointerexception,我正试图做一个基于qr扫描仪的“记录”。任务代码所做的是返回一个文本,其中包含用户的名称,但是我得到了这个错误。有人能帮我吗 public class LoginActivity extends Activity { JSONObject usuario; static String resultadoqr; public String texto; private ProgressBar pb; @Override protected void onCreate(Bundle savedIn

我正试图做一个基于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());
            }

        }
    }
PHP文档已经过测试,运行正常


有人能帮我吗?谢谢。

如果不知道哪一行抛出异常,很难判断,但是
pb
texto
变量可能是
null
。请在运行
AsyncTask

之前仔细检查是否将它们设置为适当的值。在下面的代码位中,您应该检查
texto
变量作为第一个条件语句是否为null,以便仅当texto不为null时才调用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();
            }

如果(texto.length()使用以下代码定义了字符串对象:

public String texto;
但是您从未使用值初始化过变量。字符串类是可空的,这意味着它可以为空。在下面的一行中,您使用这个变量,而它在代码中的任何地方都没有初始化

if(texto.length()<1){
if(texto.length()texto(您创建的字符串,但没有启动)是崩溃的原因

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

范例

 if (text == null) {

} else if (text.length < 1) { 

} else ..
if(text==null){
}如果(text.length<1){
}否则。。

由于错误为Nullpointer,且其在OnPostExecute中,显然它可能是由于progressBar对象或字符串的原因,但它不能是pb,因为就在调用AsyncTask之前,您调用了pb,因此应该没有问题,因此我猜唯一的原因是由于
textto
方法1.将其替换为
公共字符串texto;
替换为
公共字符串texto=“Error”
方法2.使用这个类代替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();
             }

         }
私有类MyAsyncTask扩展了AsyncTask{
@凌驾
受保护的双doInBackground(字符串…参数){
ConnectionClass cc=新的ConnectionClass(LoginActivity.this);
返回cc.connectToServer(“http://miqueas.segeon.es/posts/post_usuario.php“,resultadoqr);
}
受保护的void onPostExecute(字符串结果){
Toast.makeText(getApplicationContext(),“Peticion enviada”,Toast.LENGTH_SHORT.show();
//t、 setText(texto);
如果(结果!=“”){
Toast.makeText(getApplicationContext(),“Bienvenido usuario”+结果,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),“Quédesea?”,Toast.LENGTH_SHORT.show();
意向i=新意向(“com.oceanapps.bagu.PanelProductosActivity”);
星触觉(i);
完成();
}
否则{
Toast.makeText(getApplicationContext(),“Error desconocido,contact-con el-soport”,Toast.LENGTH_LONG).show();
}
}
还要检查清单中是否提供了INTERNET权限,以及在使用应用程序时是否可以连接到网络

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

尝试上面的事情我已经尝试过调试这个问题,如果它有帮助的话,希望它确实有帮助让我们知道…:)


thx

请指出哪一行是
LoginActivity.java:176
什么是
pb
?以及您
初始化的
it?异常发生在
LoginActivity.java
其pb(ProgressBar)中的第176行这还没有初始化。对不起,伙计们,我要编辑我的帖子来显示所有代码。PB是一个进度条。我会得到texto=null,因为代码:://execute HTTP post request HttpResponse response=httpClient.execute(httpPost);不工作,我不知道为什么
 if (text == null) {

} else if (text.length < 1) { 

} else ..
    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();
             }

         }