2

I have login activity and saved data into sharedpreferences data storage .

when I open app then first time login activity load and fill user credentials and stored in sharedpreferences, open Main Activity but when I press back button on Main Activity sharedpreferences data lost.

And next time when I opened app it shown login activity instead should be open Main Activity because I matched data this time from sharedpreferences.

My Complete code of Login Activity

public class Login extends AppCompatActivity implements     View.OnClickListener {

private String output;
private Toolbar toolbar;
private Button button;
EditText Username,Password;
String myURL,userValue,passValue;
public static final String DEFAULT="N/A";
List<DataModel> loginList;

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

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    Username = (EditText) findViewById(R.id.etUsername);
    Password = (EditText) findViewById(R.id.etPassword);

    button = (Button) findViewById(R.id.btn_login);
    button.setOnClickListener(this);

    SharedPreferences sharedPreferences = getSharedPreferences("loginData",this.MODE_PRIVATE);
    String user = sharedPreferences.getString("username",DEFAULT);
    String pass = sharedPreferences.getString("password",DEFAULT);

    if(user.equals(DEFAULT) || pass.equals(DEFAULT) && user==null && pass ==null)
    {
        Toast.makeText(this,"No Data was found",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this,"Data was found",Toast.LENGTH_LONG).show();
        Toast.makeText(this,user+pass,Toast.LENGTH_LONG).show();
        CheckOnline();
    }

}
private void CheckOnline() {
    if(inOnline())
    {
        String user,pass="";
        SharedPreferences sharedPreferences = getSharedPreferences("loginData", this.MODE_PRIVATE);
        user = sharedPreferences.getString("username", DEFAULT);
        pass = sharedPreferences.getString("password", DEFAULT);
        String getStatus = sharedPreferences.getString("LoggedIn", DEFAULT);
        if (getStatus.equals("true")) {
            Toast.makeText(this, user + pass, Toast.LENGTH_LONG).show();
            myURL = "http://www.example.com/extra/login.php?user=" + user + "&pass=" + pass;
            requestData(myURL);
        }
    }
    else
    {
        Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
    }
}
protected boolean inOnline()
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if(netInfo!=null && netInfo.isConnectedOrConnecting())
    {
        return true;
    }
    else{
        return false;
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void requestData(String uri) {
    LoginCheck check=new LoginCheck();
    check.execute(uri);
}



@Override
public void onClick(View v) {

   // startActivity(new Intent(this, MainActivity.class));
    if(v.getId()==R.id.btn_login)
    {
        if(inOnline())
        {
            userValue = Username.getText().toString();
            passValue = Password.getText().toString();
            myURL = "http://www.example.com/extra/login.php?user="+userValue+"&pass="+passValue;
            requestData(myURL);
        }
        else
        {
            Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
        }
        //  LoginCheck loginCheck = new LoginCheck();
      //  loginCheck.execute(new String[]{"http://www.dialerphilippines.com/predictivedialervoip/extra/login.php"});
    }
}



protected String updateDisplay()
{
    if(loginList != null) {
        for(DataModel login : loginList) {
            output = (login.getLoginResult() + "\n");
        }
    }
    else{
        output = "null hai";
    }
    return output;
}

@Override
public void onBackPressed() {
    Login.this.finish();
}

private class LoginCheck extends AsyncTask<String,String,String>{
    ProgressDialog dialog = new ProgressDialog(Login.this);
    @Override
    protected void onPreExecute() {
        dialog.setMessage("Login....");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String content = null;
        try {
            content = HttpManager.getData(params[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return content;
    }

    @Override
    protected void onPostExecute(String result) {
     //   loginList = JSONParser.parseLogin(result);
      //  String my = StringUtils.deleteWhitespace
      //  startActivity(new Intent(this, MainActivity.class));
       String strWithoutWhiteSpace = result.trim();
      //  Integer res = Integer.parseInt(strWithoutWhiteSpace);

        if(strWithoutWhiteSpace.equals("success")) {
            SharedPreferences sharedPreferences = getSharedPreferences("loginData",MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("username",userValue);
            editor.putString("password", passValue);
            editor.putString("LoggedIn", "true");
            editor.commit();

            startActivity(new Intent(Login.this, MainActivity.class));
            finish();
        }
        else{
            Toast.makeText(Login.this, "Either Username or Password is not correct", Toast.LENGTH_SHORT).show();
        }
        dialog.dismiss();
    }
}
}
Manish Tiwari
  • 1,806
  • 10
  • 42
  • 65

2 Answers2

1

Inserting data in shared Prefrences

SharedPreferences.Editor editor = getSharedPreferences(FILE_NAME, MODE_PRIVATE).edit();
editor.putString("name", "John");
editor.putInt("fName", "ALEX");
editor.commit();

Getting data back from Stored Shared Prefrences

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", "default_value"); 
String fName= prefs.getInt("fName", "default_value");
asad.qazi
  • 2,449
  • 3
  • 23
  • 35
0

You can create another shared preference value that holds whether the condition of Isloggedin is true and use this to redirect your activity.

String getStatus = pref.getString("LoggedIn", "nil");
if (getStatus.equals("true")) {
    // go to main or wherever your want.
    startActivity(new Intent(this, MYActivity.class));
} else {
    // TO DO - go to login page
}

When Login validated and you are updating your shared preferences or "putting" your values in for login; update your isloggedin preference.

editor.putString("LoggedIn", "true");
editor.commit();

Also take control of your backpressed events, by overriding the onbackpressed.

@Override
public void onBackPressed() {
    // TO DO

}

Providing Proper Back Navigation

edit
After your additional information: 1. I am not sure how finishing your activity in the onbackpressed event is helpful. It would be better to redirect your activity elsewhere, rather than finish the activity. This is not making sense to me. eg

@Override
public void onBackPressed() {
    // TO DO
    startActivity(new Intent(this, SomeActivityIWantTheUserToGoto.class));
}

Also, I cannot see where you are getting the string result from.

Apart from this. I suggest you implement what I have suggested. Completely, with a review of your string result. This question is growing and there comes a point in time where I cannot keep attending it.
Thanks.

edit2

I suggest you log what result is in your on postexecute. Actually check what result is.