Search code examples
javaandroidbackground-task

Android remembering previous login (backgroundtask)


Im attempting to have a login that checks to see if user exists on a mysql database, but when running the app it remembers previous login details. I think the problem is in the background task as if I comment it out I can toast the login details fine.

public class Tab1Activity extends Activity 
{   
    String task,username,password;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab1);

        final Button buta = (Button) findViewById(R.id.button1);
        final Button butb = (Button) findViewById(R.id.button2);
        final TextView usernameTV = (TextView) findViewById(R.id.editText1);
        final TextView passwordTV = (TextView) findViewById(R.id.editText2);

        buta.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                 SharedPreferences  preferences = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
                 //editor = preferences.edit();

                 username=usernameTV.getText().toString(); 
                 password=passwordTV.getText().toString();
                 task="login";
                 Toast.makeText(getApplicationContext(), username+" "+password, Toast.LENGTH_SHORT).show();

                 // create and call background activity                                

                 BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);                
                 backgroundTaskLogin.execute(task,username,password);

                 //get data back from sharedpreference
                 String driver_exist = preferences.getString("myDatalogin","ERROR getting name");

                 //display datas
                 String[] loginSeparated = driver_exist.split(",");
                 Toast.makeText(getApplicationContext(), loginSeparated[0], Toast.LENGTH_SHORT).show();


               if (loginSeparated[0].equals("true"))
               {

                int finalId = Integer.parseInt(loginSeparated[1]);   
                //Toast.makeText(getApplicationContext(), loginSeparated[1], Toast.LENGTH_SHORT).show();

                SharedPreferences.Editor editor = getSharedPreferences("MYPREFS",  Context.MODE_PRIVATE).edit();
                editor.putInt("TaxiDriverId", finalId);
                editor.apply();

                //once clicked - jump to tab2
                TabActivity tabs = (TabActivity) getParent();
                tabs.getTabHost().setCurrentTab(1);
               }
               else
               {
                   Toast.makeText(getApplicationContext(), "Wrong password", Toast.LENGTH_SHORT).show();
               }
            }
        });
    }

    //////////////////////////////////////////////////////
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tab1, menu);
        return true;
        }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

This is the background talk which I believe where the problem lie.

public class BackgroundTask extends AsyncTask<String,Void,String>
    {

        SharedPreferences preferences;
        SharedPreferences.Editor editor;
        SharedPreferences.Editor pig;

        Context context;

        BackgroundTask(Context ctx)
        {
            this.context = ctx;
        }

        @Override
        protected String doInBackground(String... params)
        {
            String urlLogin  = "";
            preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
            editor = preferences.edit();
            editor.putString("flag","0");
            editor.commit();

            String task = params[0];
            String loginusername;
             String loginpassword;


            if (task.equals("login"))
            {          
              urlLogin  = "http://super.com/LoginAndRegister-login.php";
              loginusername = params[1];
              loginpassword = params[2];



                try 
                {
                    URL url = new URL(urlLogin);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);


                    //send the driver number to the database
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
                    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

                    String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
                    +"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
                    bufferedWriter.write(myDatalogin);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();

                    //get response from the database
                    InputStream inputStream = httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String dataResponse = "";
                    String inputLine = "";
                     while((inputLine = bufferedReader.readLine()) != null)
                     {
                        dataResponse += inputLine;
                     }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();

                    editor.putString("flag","login");
                    editor.commit();                                      
                    pig = preferences.edit();
                    pig.putString("myDatalogin",dataResponse);
                    pig.commit();               
                    return  dataResponse;
                } 
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                } 

            }//end if statement

Solution

  • When you're done with the Activity call finish() this will ensure that the next time the activity is started it will start fresh. Also look over the launchMode attribute in the Activity tag in AndroidManifest.xml to make sure you're starting your activity correctly. https://developer.android.com/guide/topics/manifest/activity-element.html