有误差的AsyncTask [英] got error with AsyncTask

查看:129
本文介绍了有误差的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用AsyncTask的,但我不明白为什么我仍然有错误,当我的设备(OS 4.0)上测试。我的APK建设2.3.3。我想我做到了codeS错了,但我不知道哪里是我的错误。任何人都请帮助我,非常感谢你。

login.java

 包com.karismaelearning;    公共类扩展登录活动{
        公共Koneksi linkurl;
        串SERVER_URL;
        私人按钮登录,注册,设置;
        私人的EditText用户名,密码;
        公共ProgressDialog progressDialog;
        @覆盖
        公共无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.login);            设置=(按钮)findViewById(R.id.bsetting);
            登录=(按钮)findViewById(R.id.login);
            注册=(按钮)findViewById(R.id.reg);
            用户名=(的EditText)findViewById(R.id.uname);
            密码=(EditText上)findViewById(R.id.pass);            setting.setOnClickListener(新OnClickListener(){                @覆盖
                公共无效的onClick(视图v){
                    意图int​​entSet =新意图(Login.this,UrlSetting.class);
                    startActivity(intentSet);
                }
            });            register.setOnClickListener(新OnClickListener(){                公共无效的onClick(视图v){
                    意图int​​entReg =新意图(Login.this,Register.class);
                    startActivity(intentReg);
                }
            });            login.setOnClickListener(新OnClickListener(){                公共无效的onClick(视图v){
                    新LoginTask()执行();
                }
            });        }
        保护字符串tryLogin(字符串mUsername,字符串mPassword){
          Log.d(TryLoginCheck,在这里);
            HttpURLConnection的连接;
           OutputStreamWriter请求= NULL;                网址URL = NULL;
                串响应=无效;
                字符串TEMP = NULL;
                字符串参数=用户名=+ mUsername +&放大器;密码=+ mPassword;
                的System.out.println(用户名+ mUsername +\\ n+密码+ mPassword);
                Log.d(参数,参数);
                尝试{
                    linkurl =新Koneksi(本);
                    SERVER_URL = linkurl.getUrl();
                    SERVER_URL + =/mobile/Login.php;
                    URL =新的URL(SERVER_URL);
                    连接=(HttpURLConnection类)url.openConnection();
                    connection.setDoOutput(真);
                    connection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
                    connection.setRequestMethod(POST);                    请求=新OutputStreamWriter(connection.getOutputStream());
                    request.write(参数);
                    request.flush();
                    request.close();
                    串线=;
                    InputStreamReader的ISR =新的InputStreamReader(connection.getInputStream());
                    读者的BufferedReader =新的BufferedReader(ISR);
                    StringBuilder的SB =新的StringBuilder();
                    而((行= reader.readLine())!= NULL){
                        sb.append(行+\\ n);
                    }
                    TEMP = sb.toString();
                    Log.d(温度,温度);                    响应= sb.toString();
                    Log.d(响应,响应);
                   Log.d(保安局值,sb.toString());
                    isr.close();
                    reader.close();
                }
                赶上(IOException异常五){
                    Toast.makeText(这一点,e.toString(),Toast.LENGTH_SHORT).show();
                }                返回响应;
        }        公共类LoginTask扩展的AsyncTask<字符串,字符串,字符串> {    串响应=无效;    @覆盖
    在preExecute保护无效()
    {    }
    @覆盖
    保护字符串doInBackground(字符串...为arg0)
    {
     。字符串mUsername = username.getText()的toString();
            。字符串mPassword = password.getText()的toString();            响应= tryLogin(mUsername,mPassword).trim();
       返回响应;
    }
  保护无效onPostExecute(字符串结果){      如果(结果== NULL)
      {
          Toast.makeText(Login.this,结果是空值时出错,Toast.LENGTH_SHORT).show();
        }
      其他{     Log.d(检查,在这里);
        Log.d(响应,响应);
     如果(response.toLowerCase()。包含(berhasil))
            {
                字符串NAMA = username.getText()的toString()。
                意图newIntent =新意图(Login.this,MainPage.class);                束束=新包();                bundle.putString(非农产品市场准入,NAMA);                newIntent.putExtras(包);
                startActivityForResult(newIntent,0);
            }
            其他
            {
                //可选
                // Kalau BISA dibuat不断untuk menghindari萨拉赫penulisan
                字符串RoleError =角色SALAH
                字符串UserError =USER SALAH                createDialog(MAAF,response.equals(RoleError)角色安达bukan学生!?!用户名密码Atau萨拉赫);
            }
      }
  }
        }
        私人无效createDialog(标题字符串,字符串文本){
            AlertDialog广告=新AlertDialog.Builder(本)
            .setPositiveButton(OK,NULL)
            .setTitle(职称)
            .setMessage(文本)
            。创建();
            ad.show();
        }
    }

LogCat中

  06-10 16:50:00.082:D / TryLoginCheck(4534):在这里
06-10 16:50:00.090:我/的System.out(4534):用户名
06-10 16:50:00.090:我/的System.out(4534):密码
06-10 16:50:00.090:D /参数(4534):用户名=放大器;密码=
06-10 16:50:00.122:W / dalvikvm(4534):主题ID = 11:螺纹未捕获的异常(组= 0x40bd31f8)退出
06-10 16:50:00.129:E / AndroidRuntime(4534):致命异常:AsyncTask的#1
06-10 16:50:00.129:E / AndroidRuntime(4534):了java.lang.RuntimeException:执行doInBackground发生错误()
06-10 16:50:00.129:E / AndroidRuntime(4534):在android.os.AsyncTask $ 3.done(AsyncTask.java:278)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.FutureTask中$ Sync.innerSetException(FutureTask.java:273)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:307)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-10 16:50:00.129:E / AndroidRuntime(4534):在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:208)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:569)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.lang.Thread.run(Thread.java:856)
06-10 16:50:00.129:E / AndroidRuntime(4534):因:显示java.lang.NullPointerException
06-10 16:50:00.129:E / AndroidRuntime(4534):在com.karismaelearning.Login $ LoginTask.doInBackground(Login.java:151)
06-10 16:50:00.129:E / AndroidRuntime(4534):在com.karismaelearning.Login $ LoginTask.doInBackground(Login.java:1)
06-10 16:50:00.129:E / AndroidRuntime(4534):在android.os.AsyncTask $ 2.call(AsyncTask.java:264)
06-10 16:50:00.129:E / AndroidRuntime(4534):在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:305)
06-10 16:50:00.129:E / AndroidRuntime(4534):... 5个
06-10 16:50:05.192:D / OpenGLRenderer(4534):刷新缓存(模式0)
06-10 16:50:06.309:D / OpenGLRenderer(4534):冲洗缓存(模式1)
06-10 16:50:07.536:I /流程(4534):发送信号。 PID:4534 SIG:9


解决方案
在tryLogin,

在发生异常时你做的:

  Toast.makeText(这一点,e.toString(),Toast.LENGTH_SHORT).show();

这是错误的。在 Toast.show()已对UI线程运行。

  tryLogin(){  尝试{  }赶上(IOException异常五){
       返回null;
  }}

 保护无效onPostExecute(字符串结果){    如果(结果== NULL){
     Toast.makeText(Login.this,结果是一个空值出现错误),Toast.LENGTH_SHORT).show();
    }其他{
       结果= result.trim();
       //其他的东西
    } }@覆盖
保护字符串doInBackground(字符串...为arg0)
{
   。字符串mUsername = username.getText()的toString();
   。字符串mPassword = password.getText()的toString();
   返回tryLogin(mUsername,mPassword);
}

I already use AsyncTask, but I don't understand why I still got error when i tested on my device (OS 4.0) . my apk build in 2.3.3 . I think i made the codes wrong, but i don't know where is my mistake. Anyone please help me, thank you very much

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

解决方案

in tryLogin, when an Exception occurs you do:

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

that's wrong. The Toast.show() has to run on the UI Thread.

in

tryLogin() {

  try {

  }  catch(IOException e)  {
       return null;
  }

}

and in

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);
}

这篇关于有误差的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆