AsyncTask出错了

时间:2013-06-10 09:10:52

标签: android android-asynctask

我已经使用了AsyncTask,但我不明白为什么我在设备上测试时仍会出现错误(OS 4.0)。我的apk版本在2.3.3中。我想我的代码错了,但我不知道我的错误在哪里。有人请帮助我,非常感谢

login.java

package com.karismaelearning;

    public class Login extends Activity {
        public Koneksi linkurl;
        String SERVER_URL;
        private Button login, register, setting;
        private EditText username, password;
        public ProgressDialog progressDialog;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);

            setting = (Button)findViewById(R.id.bsetting);
            login = (Button) findViewById(R.id.login);
            register = (Button) findViewById(R.id.reg);
            username = (EditText) findViewById(R.id.uname);
            password = (EditText) findViewById(R.id.pass);

            setting.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intentSet = new Intent(Login.this, UrlSetting.class);
                    startActivity(intentSet);
                }
            });

            register.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    Intent intentReg = new Intent(Login.this, Register.class);
                    startActivity(intentReg);
                }
            });

            login.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    new LoginTask().execute();
                }
            });

        }
        protected String tryLogin(String mUsername, String mPassword){           
          Log.d(" TryLoginCheck ","Here");
            HttpURLConnection connection;
           OutputStreamWriter request = null;

                URL url = null;
                String response = null;   
                String temp=null;
                String parameters = "username="+mUsername+"&password="+mPassword;   
                System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
                Log.d("Parameters",parameters);
                try{
                    linkurl = new Koneksi(this);
                    SERVER_URL = linkurl.getUrl();
                    SERVER_URL += "/mobile/Login.php";
                    url = new URL(SERVER_URL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setRequestMethod("POST");    

                    request = new OutputStreamWriter(connection.getOutputStream());
                    request.write(parameters);
                    request.flush();
                    request.close();            
                    String line = "";               
                    InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                    BufferedReader reader = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    temp=sb.toString();
                    Log.d("Temp",temp);

                    response = sb.toString();
                    Log.d("Response",response);
                   Log.d("Sb Value",sb.toString());
                    isr.close();
                    reader.close();
                }
                catch(IOException e)    {
                    Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
                }

                return response;
        }

        public class LoginTask extends AsyncTask<String, String, String> {

    String response = null;

    @Override
    protected void onPreExecute()
    {

    }
    @Override
    protected String doInBackground(String... arg0)
    {
     String mUsername = username.getText().toString();
            String mPassword = password.getText().toString();

            response = tryLogin(mUsername, mPassword).trim();
       return response;
    }
  protected void onPostExecute(String result){

      if(result==null)
      {
          Toast.makeText(Login.this,"result is null- an error occured",Toast.LENGTH_SHORT).show();
        } 
      else{

     Log.d("Check","Here");
        Log.d("Response",response);
     if(response.toLowerCase().contains("berhasil"))
            {
                String nama = username.getText().toString();
                Intent newIntent = new Intent(Login.this, MainPage.class);

                Bundle bundle = new Bundle();

                bundle.putString("nama", nama);

                newIntent.putExtras(bundle);
                startActivityForResult(newIntent, 0);
            }
            else
            {
                //Optional
                //Kalau bisa dibuat constant untuk menghindari salah penulisan
                String RoleError = "ROLE SALAH";
                String UserError = "USER SALAH";

                createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
            }
      }
  }
        }
        private void createDialog(String title, String text) {
            AlertDialog ad = new AlertDialog.Builder(this)
            .setPositiveButton("Ok", null)
            .setTitle(title)
            .setMessage(text)
            .create();
            ad.show();
        }
    }

logcat的

06-10 16:50:00.082: D/TryLoginCheck(4534): Here
06-10 16:50:00.090: I/System.out(4534): UserName
06-10 16:50:00.090: I/System.out(4534): password
06-10 16:50:00.090: D/Parameters(4534): username=&password=
06-10 16:50:00.122: W/dalvikvm(4534): threadid=11: thread exiting with uncaught exception (group=0x40bd31f8)
06-10 16:50:00.129: E/AndroidRuntime(4534): FATAL EXCEPTION: AsyncTask #1
06-10 16:50:00.129: E/AndroidRuntime(4534): java.lang.RuntimeException: An error occured while executing doInBackground()
06-10 16:50:00.129: E/AndroidRuntime(4534):     at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.lang.Thread.run(Thread.java:856)
06-10 16:50:00.129: E/AndroidRuntime(4534): Caused by: java.lang.NullPointerException
06-10 16:50:00.129: E/AndroidRuntime(4534):     at com.karismaelearning.Login$LoginTask.doInBackground(Login.java:151)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at com.karismaelearning.Login$LoginTask.doInBackground(Login.java:1)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-10 16:50:00.129: E/AndroidRuntime(4534):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-10 16:50:00.129: E/AndroidRuntime(4534):     ... 5 more
06-10 16:50:05.192: D/OpenGLRenderer(4534): Flushing caches (mode 0)
06-10 16:50:06.309: D/OpenGLRenderer(4534): Flushing caches (mode 1)
06-10 16:50:07.536: I/Process(4534): Sending signal. PID: 4534 SIG: 9

5 个答案:

答案 0 :(得分:5)

在tryLogin中,当发生异常时,你会这样做:

 Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();

那是错的。 Toast.show()必须在UI线程上运行。

in

tryLogin() {

  try {

  }  catch(IOException e)  {
       return null;
  }

}

并在

protected void onPostExecute(String result){

    if (result == null) {
     Toast.makeText(Login.this,"result is null- an error occured"),Toast.LENGTH_SHORT).show();
    } else {
       result = result.trim();
       // the other stuff
    }

 }

@Override
protected String doInBackground(String... arg0)
{
   String mUsername = username.getText().toString();
   String mPassword = password.getText().toString();          
   return tryLogin(mUsername, mPassword);
}

答案 1 :(得分:1)

要弄清楚为什么例程tryLogin不起作用,我建议遵循@ BlackBelt的建议,除了tryLogin()使用:

tryLogin() {

  try {

  }  catch(Throwable e)  {
       e.printStackTrace();
       Log.d("Error",e.getMessage());
       return null;
  }

}

并查看生成的错误消息。

答案 2 :(得分:0)

登录请求放在doInBackground()方法中。并处理AsyncTask的onPostExecute()方法中的响应

答案 3 :(得分:0)

Toast无法在catch中运行,因为后台线程无法访问用户界面。但是,onPostExecute确实在主线程上运行,因此它可以访问用户界面,toast可以在那里工作。

所以我定义了一个新类来保存AsyncTask的结果,并设置它以便该类可以表示成功或错误消息。然后让onPostExecute相应地运行,具体取决于是否发生错误。

答案 4 :(得分:0)

如果我理解正确,错误是由于 Looper.prepare()未被手动调用或自动从框架调用。

尝试在

super() 
的构造函数中调用

LoginTask
(根据我的理解,当您扩展AsyncTask并从UI线程执行/启动它时,您将不会得到此异常,因为Looper将由超类自动准备。)

或。快速修复(不推荐):在doInBackground中调用Looper.prepare()

@Override
protected String doInBackground(String... arg0) {

    try {
        Looper.prepare();
    } catch (Exception e){
        // ignore. There can be only one Looper associated with thread
        // This happens when the current thread already has Looper associated with it
    }

    //TODO: Your original content of doInBackground(...)
}

P.S。如果您通过扩展线程而不是准备 Looper 并使用UI元素的上下文来创建自定义线程(例如,To to Toast消息),Android将抛出Looper未准备好的异常! / p>