1

I tested the application and on the device with usb debug, but i get different result. in emulator it works fine, but on device i can't login and just throw the toast

Toast.makeText(Login.this,"result is null- an error occured",Toast.LENGTH_SHORT).show();. 

why is it happen? my emulator run on OS 2.3.3 and my device on 4.0.

when I tested on my device the logcat didn't appear, the logcat only show the process when i run it on emulator O.o.

anyone please help me, 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+"\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)
            {

                return null;
            }

            return response;
    }

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

        String result = 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",result);
         if(result.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", result.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();
    }
}
Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96
blackneko
  • 91
  • 1
  • 12
  • Is your mobile device connected to internet ? – Alexis C. Jun 10 '13 at 11:50
  • It is because internet policy is different on 4.0. Take a look at: http://stackoverflow.com/questions/13342638/httpclient-phpmyadmin-not-working-on-android-4-0 – Bigflow Jun 10 '13 at 11:52
  • @ZouZou, not yet I only try usb debug fisrt.. do you have any idea why this is happen? O.o Thank you – blackneko Jun 10 '13 at 12:00
  • @Bigflow, I already use AsyncTask like the other suggest but i don't know why the result always null so always throw the toast.. do you have any idea why this happened? Thank you – blackneko Jun 10 '13 at 12:02
  • @blackneko Made an answer, but read it good. – Bigflow Jun 10 '13 at 12:07

3 Answers3

1

see here your are doing UI related operations in doInBacground(). we can't do like that just make that code in preExecute() and then use those values where you want. Like this

String result = null;
String mUsername = null;
String mPassword = null;

@Override
protected void onPreExecute()
{
    mUsername = username.getText().toString();
    mPassword = password.getText().toString();  
}

@Override
protected String doInBackground(String... arg0)
{       
    return tryLogin(mUsername, mPassword);
}
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • sorry i'm new in android, can you explain more clear because i don't understand what you mean. thank you very much – blackneko Jun 10 '13 at 12:05
  • Now i was edited my answer with new code check it will help u. – RajaReddy PolamReddy Jun 10 '13 at 12:07
  • I tried your code but still only throw the toast and on the logcat not appear anything wrong when i debug it on my device? why is that? thank you – blackneko Jun 10 '13 at 12:15
  • not yet, i tried login but still it only throw the toast when result = null. this only happen when i debug on device. do you have any other idea why it is happen? thank you – blackneko Jun 10 '13 at 12:19
  • when i tested on device it always go to this ` if(result==null) { Toast.makeText(Login.this,"result is null- an error occured",Toast.LENGTH_SHORT).show(); } ` – blackneko Jun 10 '13 at 12:32
  • that line ` if(result==null) { Toast.makeText(Login.this,"result is null- an error occured",Toast.LENGTH_SHORT).show(); } ` thank you – blackneko Jun 10 '13 at 12:58
  • 1
    thank you for your help. i must shut down my device and turn it on and my apps works fine :D – blackneko Jun 11 '13 at 09:29
0

I think that this question will solved your problem, I had the same time ago: HttpURLConnection fails on Android 4.0 All is related with httpurlconnection and internet policy.

Community
  • 1
  • 1
ƒernando Valle
  • 3,634
  • 6
  • 36
  • 58
  • I already use AsyncTask like that on my code above, is it wrong? O.o before I use that , the apps force close, but after I type AsyncTask apps not force close but the result always null?? O.o – blackneko Jun 10 '13 at 11:57
0

You can use this code (place it on top in the code somewhere):

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

But Strictly to check/test if your AsyncTask is good.
If your code works after this, then the AsyncTask is not good.
If it still doesn't work, something else is wrong.

But only use this code to check it, do not use it in your final program.

Bigflow
  • 3,616
  • 5
  • 29
  • 52
  • the result still the same.. only throw toast.. do you have any other idea why tis only happen on device, but when emulator it's fine? Thank you – blackneko Jun 10 '13 at 12:25
  • @blackneko No idea yet, but you could try to make a new emulator with also Android 4.0, and test it again on emulator. Then you can check if the problem is within the device or Android version. – Bigflow Jun 10 '13 at 12:30
  • I tried in new emulator use 4.0.3 and it works fine.. O.o so what's happen in here? O.o – blackneko Jun 10 '13 at 12:45
  • @blackneko I got no idea to be honest, only thing I can think of (not fastest way maybe) but to use `System.out.println("variable"+some kind of variable here);` And see till where everything goes good, and where it goes wrong. For example: Try to check if it actually got internet (the app, not the phone). If that is ok, see if the Connection/Request goes good, and so on and on. Till it goes wrong somewhere :p – Bigflow Jun 10 '13 at 12:52
  • it's really weird,right.. on the device always failed but when it tested on emulator same OS it works ==".. thank you very much for your help :) – blackneko Jun 10 '13 at 12:55
  • @blackneko Let me know if you found anything while debugging. Curious what the problem is :) – Bigflow Jun 10 '13 at 13:15
  • the solution is.... i only shut it down and Turn it on and try with wifi tethering an VOILA the program works XD LOL just simple like that, don't have any error – blackneko Jun 11 '13 at 09:28
  • May I ask again another question in here [link]http://stackoverflow.com/questions/17161188/confused-to-put-code-in-asynctask ,i need help to get the solution. i already read the documentation about AsyncTask but still confuse where i must put bundle thing . if you have time to look at it, please help me. thank you – blackneko Jun 18 '13 at 10:24
  • Hi @Bigflow, i need help once again to make pop up window.. someone tell me how to do it but he didn't explain it clear so i still didn't understand. if you have time can you please look to this question [link]http://stackoverflow.com/questions/17183916/confused-when-try-to-make-pop-up-window thank you very much.. – blackneko Jun 19 '13 at 09:20