1

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

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

日志猫

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
4

5 回答 5

5

在 tryLogin 中,当发生异常时,您执行以下操作:

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

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

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);
}
于 2013-06-10T09:14:09.980 回答
1

要找出例程 tryLogin 不起作用的原因,我建议遵循 @BlackBelt 的建议,除了 tryLogin() 使用:

tryLogin() {

  try {

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

}

并查看产生的错误消息。

于 2013-06-10T10:30:41.453 回答
0

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

于 2013-06-10T09:13:30.973 回答
0

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

所以我会定义一个新类来保存 AsyncTask 的结果,并设置它,以便该类可以表示成功或错误消息。然后onPostExecute根据是否发生错误,让 执行相应的操作。

于 2013-06-10T09:21:04.623 回答
0

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

试着打电话

极好的()
在你的构造函数中
登录任务
(据我了解,当您扩展 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(...)
}

ps 如果您通过扩展Thread但不准备Looper并使用 UI 元素的上下文来创建自定义线程(例如,To toast 消息)Android 将抛出 Looper not Prepared 异常!

于 2013-06-10T09:42:50.100 回答