1

I think I can bypass login activity after I logged in but how to retrieve and pass username to next activity. I got username's value is NULL

Here is login Activity

public class LoginActivity extends AppCompatActivity {
    /*
     * Database helper field
     */
    private DatabaseHelper databaseHelper;
    /*
    Edittext username and password
     */
    private EditText uName, pwd;
    /*
    Button login and signup
     */
    private Button loginButton, signupButton;
    private String username, password;

    /**
     * Create activity when register button and log in button clicked
     * @param savedInstanceState saved instance state
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar)findViewById(R.id.login_toolbar);
        toolbar.setTitle("LOGIN");

        databaseHelper = new DatabaseHelper(this);

        uName = (EditText)findViewById(R.id.uNameToLogin_editText);
        pwd = (EditText)findViewById(R.id.pwdToLogin_editText);

        SharedPreferences sharedPreferences = getSharedPreferences
                (getString(R.string.SHARED_PREFS), MODE_PRIVATE);
        boolean isLoggedIn = sharedPreferences.getBoolean(getString(R.string.LOGGEDIN), false);
        if (isLoggedIn){
            Intent newIntent = new Intent(LoginActivity.this, FinderActivity.class);
            newIntent.putExtra("Username", username);
            startActivity(newIntent);
            finish();
        }
        /*
        * Sign up button clicked takes user to registration form
         */
        signupButton = (Button)findViewById(R.id.signupButton);
        signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        /*
        *Log in activity
         */
        loginButton = (Button)findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = uName.getText().toString();
                password = pwd.getText().toString();
                //log in successfull using correct username and password
                String pass = databaseHelper.searchPassword(username);
                if (pass.equals(password)){

                    SharedPreferences sharedPreferences = getSharedPreferences
                            (getString(R.string.SHARED_PREFS), MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean(getString(R.string.LOGGEDIN), true);
                    editor.commit();

                    Toast.makeText(LoginActivity.this, "Welcome! " + username,
                            Toast.LENGTH_LONG).show();
                    //change to new search intent
                    Intent newIntent = new Intent(LoginActivity.this, FinderActivity.class);
                    newIntent.putExtra("Username", username);
                    startActivity(newIntent);
                    finish();
                } else {
                    //error shows if inccorrect password or username
                    Toast.makeText(LoginActivity.this, "Username or Password Incorrect!, Try Again",
                            Toast.LENGTH_LONG).show();
                }

            }
        });

    }

}

here is my NextActivity which contains logout actions in menu bar

public class FinderActivity extends AppCompatActivity {

    private static final String TAG = "FinderActivity";
    private String address = "";
    public List<LocationInfo> locationList;
    public ListView mListView;
    public ArrayAdapter<LocationInfo> locationAdapter;
    private int numberOfLocation;
    public LocationAddress locationAddress;
    public String api_url, uName;
    public double lat, lng;

    SharedPreferences mSharePreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finder);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Intent intent = getIntent();
        uName = intent.getStringExtra("Username");
        String welcomeString = "Welcome, " + uName;
        getSupportActionBar().setTitle(welcomeString);

        Log.i(TAG, "On create called");

        View b = findViewById(R.id.customButton);
        b.setVisibility(View.GONE);

        /*
        retrieve search button actions
         */
        Button searchButton = (Button) findViewById(R.id.search_button);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //pass address to location class
                EditText search = (EditText) findViewById(R.id.search_EditText);
                address = search.getText().toString();
                LocationAddress.setAddress(address);
                if (locationList != null) {
                    locationList.clear();
                }
                if (address.equals("")) {
                    Toast.makeText(FinderActivity.this, "PLease enter your address!",
                            Toast.LENGTH_LONG).show();
                } else {
                /*
                * manging connection from the application to networking service
                * before attempting to fetch url, make sure there is a network connection
                */
                    ConnectivityManager connectivityManager = (ConnectivityManager)
                            getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networtInfo = connectivityManager.getActiveNetworkInfo();
                    if (networtInfo != null && networtInfo.isConnected()) {
                        GetAddressTask task = new GetAddressTask();
                        task.execute();
                        View b = findViewById(R.id.customButton);
                        b.setVisibility(View.GONE);
                        Log.i(TAG, "connected");
                    } else {
                        Log.i(TAG, "not connected");
                    }

                /*
                Retrieve data to listview
                 */
                    showListView();
                    /*
                    itemClick listener for each item in the list view
                     */
                    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(FinderActivity.this, ParkingLocation.class);
                            api_url = locationList.get(position).getUrl_api();
                            intent.putExtra("key_api_url", api_url);
                            intent.putExtra("username", uName);
                            startActivity(intent);
                        }
                    });

                }
            }
        });

        /*
        Custom search button actions if and only if search button gives null results
         */
        Button customSearch = (Button) findViewById(R.id.customButton);
        customSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (address.equals("")) {
                    Toast.makeText(FinderActivity.this, "PLease enter your address!",
                            Toast.LENGTH_LONG).show();

                } else if (LocationAddress.getNumOfLocations() > 0) {
                    Toast.makeText(FinderActivity.this, "This action is only available if no parking locations found!!",
                            Toast.LENGTH_LONG).show();
                } else { //open custom search activity
                    Intent newIntent = new Intent(FinderActivity.this, CustomSearchActivity.class);
                    Bundle b = new Bundle();
                    b.putDouble("key_lat", lat);
                    b.putDouble("key_lng", lng);
                    b.putString("username", uName);
                    newIntent.putExtras(b);
                    startActivity(newIntent);
                }
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        switch (id) {
            //log out action
            case R.id.action_logout:
                mSharePreferences = getSharedPreferences(getString
                        (R.string.SHARED_PREFS), MODE_PRIVATE);
                SharedPreferences.Editor editor = mSharePreferences.edit();
                editor.putBoolean(getString(R.string.LOGGEDIN), false);
                editor.commit();
                Intent backIntent = new Intent(FinderActivity.this, LoginActivity.class);
                startActivity(backIntent);
                return true;
            //show my saved places view
            case R.id.action_show:
                Intent intent = new Intent(FinderActivity.this, MyDestination.class);
                intent.putExtra("username", uName);
                startActivity(intent);
                return true;
        }
        //show list of destination once this button clicked
        return super.onOptionsItemSelected(item);
    }
codeMagic
  • 44,549
  • 13
  • 77
  • 93
Tuan
  • 51
  • 5
  • I edited your post to try and make it more clear. If I have changed the meaning at all, feel free to edit. It is still unclear what you are asking and a whole lot of code to sift through. You might want to consider making it more precise. You are asking about `SharedPreferences` but you are sending the username through an `Intent`. What exactly do you want to do and what have you done to try and narrow down the problem? Have you debugged to see where/when certain values are set? – codeMagic Dec 03 '15 at 17:48
  • If `isLoggedIn ` is true, then the username probably won't have a value because you haven't set it. You might want to store that value in `SharedPrefs` and retrieve it if the user is logged in. – codeMagic Dec 03 '15 at 17:56
  • you mean in the login button action listener I have to store the value of username and pass it to login activity? so I can bypass and retrieve for next login ? – Tuan Dec 03 '15 at 19:50
  • Honestly, I'm very confused on what you have and are trying to do. But, at that point, `username` isn't going to have a value so you need it stored somewhere if you want to use it – codeMagic Dec 03 '15 at 19:52
  • Thanks again. I solved my problem – Tuan Dec 03 '15 at 20:09
  • ah sorry, what im just trying to do is after I log in, i want to store the username in sharedPrefs so I can fetch it back for next login. at this point I don't have to login again and it takes me directly to second activity. By the way, I solved my problem. Thanks again – Tuan Dec 03 '15 at 20:16

1 Answers1

1

If you want to pass the data withing a intent you shoud set this on onCreate in FinderActivity.java

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

    if (getIntent() != null) {
        final Bundle extras = getIntent().getExtras();
        if (extras != null) {
            userName = extras.getString("Username");
        }
    }

}

If you want to save on SharedPreferences you have to save on LoginActivity and get on FinderActivity.java A link explaining how -> How to use SharedPreferences in Android to store, fetch and edit values

Community
  • 1
  • 1
josealfonsomora
  • 154
  • 1
  • 11
  • You saved my time, Thank you. I already solved it, just store and fetch username needed. – Tuan Dec 03 '15 at 20:10