Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

my AsyncTask codes return null when try to login. I got confused, why on device it can throw the toast "return null..." but on emulator it force close, anyone please help me to fix this. thank you very much

login.java

public class Login extends Activity {
    public Koneksi linkurl;
    String SERVER_URL;
    private Button login, register, setting;
    private EditText username, password;
    public ProgressDialog progressDialog;


    /** Called when the activity is first created. */
    @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) {
                // TODO Auto-generated method stub
                Intent intentSet = new Intent(Login.this, UrlSetting.class);
                startActivity(intentSet);
            }
        });

        register.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intentReg = new Intent(Login.this, Register.class);
                startActivity(intentReg);
            }
        });

        login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                // TODO Auto-generated method stub

               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+"
"+"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 + "
");
                }
                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)
            {
                e.printStackTrace();
                Log.d("Error",e.getMessage());
                return null;
            }

            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();          
               return tryLogin(mUsername, mPassword);
        }
      protected void onPostExecute(String result){
          super.onPostExecute(result);
          if(result==null)
          {
              Toast.makeText(Login.this,"result is null- an error occured",Toast.LENGTH_SHORT).show();
            } 
          else{

              result = result.trim();
         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 - when I test in device

06-10 17:34:43.715: D/TextLayoutCache(13251): Using debug level: 0 - Debug Enabled: 0
06-10 17:34:43.786: D/libEGL(13251): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
06-10 17:34:43.793: D/libEGL(13251): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
06-10 17:34:43.801: D/libEGL(13251): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
06-10 17:34:43.918: D/OpenGLRenderer(13251): Enabling debug mode 0
06-10 17:34:45.090: D/TryLoginCheck(13251): Here
06-10 17:34:45.098: I/System.out(13251): UserName
06-10 17:34:45.098: I/System.out(13251): password
06-10 17:34:45.098: D/Parameters(13251): username=&password=

logcat- wen i test on emulator

06-10 17:37:34.375: I/Process(451): Sending signal. PID: 451 SIG: 9
06-10 17:43:06.032: W/KeyCharacterMap(488): No keyboard for id 0
06-10 17:43:06.032: W/KeyCharacterMap(488): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-10 17:43:19.961: D/TryLoginCheck(488): Here
06-10 17:43:19.963: I/System.out(488): UserNametes
06-10 17:43:19.963: I/System.out(488): passwordTes12345*
06-10 17:43:19.963: D/Parameters(488): username=tes&password=Tes12345*
06-10 17:43:20.343: D/Temp(488): Login Berhasil dengan userid='3'
06-10 17:43:20.343: D/Response(488): Login Berhasil dengan userid='3'
06-10 17:43:20.343: D/Sb Value(488): Login Berhasil dengan userid='3'
06-10 17:43:20.343: D/Check(488): Here
06-10 17:43:20.343: D/AndroidRuntime(488): Shutting down VM
06-10 17:43:20.343: W/dalvikvm(488): threadid=1: thread exiting with uncaught exception (group=0x40015560)
06-10 17:43:20.363: E/AndroidRuntime(488): FATAL EXCEPTION: main
06-10 17:43:20.363: E/AndroidRuntime(488): java.lang.NullPointerException: println needs a message
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.util.Log.println_native(Native Method)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.util.Log.d(Log.java:137)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.karismaelearning.Login$LoginTask.onPostExecute(Login.java:163)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.karismaelearning.Login$LoginTask.onPostExecute(Login.java:1)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.AsyncTask.finish(AsyncTask.java:417)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.Looper.loop(Looper.java:123)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.app.ActivityThread.main(ActivityThread.java:3683)
06-10 17:43:20.363: E/AndroidRuntime(488):  at java.lang.reflect.Method.invokeNative(Native Method)
06-10 17:43:20.363: E/AndroidRuntime(488):  at java.lang.reflect.Method.invoke(Method.java:507)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-10 17:43:20.363: E/AndroidRuntime(488):  at dalvik.system.NativeStart.main(Native Method)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're confusing 'response' with 'result'. In onPostExecute(String result) 'result' is the result from your asynchronous execution in doInBackground(). The response member variable of LoginTask is never used and I do not see why you'd want it at all. Remove it and use 'result'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...