简体   繁体   中英

How to pass User_Id to every activity in android?

I am trying to build an android application. After logged in to the application I want to use User_Id for all activities for getting unique data based on that user_id. How it is possible? And what changes i want to make in this code to get user_id in all activities?

LoginActivity.java

       public class LoginActivityMerchant extends AppCompatActivity implements View.OnClickListener {

//Defining views
private AutoCompleteTextView ACTUser;
private EditText etPassword;
private Button buttonLogin;
private TextView linkToRegister;
private ProgressDialog loading;
public static final String KEY_firstName = "First_Name";
public static final String KEY_LastName = "Last_Name";
public static final String KEY_Mob = "Mobile";
public static final String KEY_ShopName = "Shop_Name";

public static final String KEY_Location = "Location";
public static final String KEY_Radius = "UserId";
public static final String JSON_ARRAY = "result";
public static final String KEY_UserName = "User_Name";
public static final String KEY_Password = "Password";
public TextView test;

//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;

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

    //Initializing views
    ACTUser = (AutoCompleteTextView) findViewById(R.id.email);
    etPassword = (EditText) findViewById(R.id.password);
    buttonLogin =  (Button) findViewById(R.id.email_sign_in_button);
    linkToRegister = (TextView) findViewById(R.id.Reg_TextView);
    test=(TextView)findViewById(R.id.test);
    //Adding click listener
    buttonLogin.setOnClickListener(this);
    linkToRegister.setOnClickListener(this);
}

@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    SharedPreferences sharedPreferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

    //Fetching the boolean value form sharedpreferences
    loggedIn = sharedPreferences.getBoolean(config.LOGGEDIN_SHARED_PREF, false);

    //If we will get true
    if(loggedIn){
        //We will start the Profile Activity
        //Config.KEY_USERNAME=Config.USERNAME_SHARED_PREF;
        SharedPreferences sharedPreferences1 = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String username = sharedPreferences1.getString(config.SHARED_PREF_NAME,"Not Available");
        setInfos(username);
        Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
        startActivity(intent);
    }
}

private void login(){


    //Getting values from edit texts
    final String user = ACTUser.getText().toString().trim();
    final String password = etPassword.getText().toString().trim();
    if(user.isEmpty()||password.isEmpty())
    {
        Toast.makeText(LoginActivityMerchant.this, "Please fill all the fields", Toast.LENGTH_LONG).show();
    }

    //Creating a string request
    else{
        StringRequest stringRequest = new StringRequest(Request.Method.POST, config.LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //test.setText(response);
                        //If we are getting success from server
                        if(response.contains("success")){
                            //Creating a shared preference
                           // Toast.makeText(LoginActivityMerchant.this, "Success", Toast.LENGTH_LONG).show();

                            SharedPreferences sharedPreferences = LoginActivityMerchant.this.getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                            //Creating editor to store values to shared preferences
                            SharedPreferences.Editor editor = sharedPreferences.edit();

                            //Adding values to editor
                            editor.putBoolean(config.LOGGEDIN_SHARED_PREF, true);
                            editor.putString(config.SHARED_PREF_NAME, user);
                            config.KEY_USERNAME = user;

                            //Saving values to editor
                            editor.commit();

                            //Starting profile activity
                            //Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                            setInfos(user);
                            Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
                            startActivity(intent);
                        }else{
                            //If the server response is not success
                            //Displaying an error message on toast
                            Toast.makeText(LoginActivityMerchant.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                            ACTUser.setText(user);
                            etPassword.setText(password);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //You can handle error here if you want
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                //Adding parameters to request
                params.put(KEY_UserName, user);
                params.put(KEY_Password, password);
                //test.setText(password);
                //returning parameter
                return params;
            }
        };

        //Adding the string request to the queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }}

@Override
public void onClick(View v) {
    //Calling the login function
    if(v==buttonLogin){
        login();
    }
    if(v==linkToRegister){
        Intent intent = new Intent(LoginActivityMerchant.this, Registration.class);
        startActivity(intent);
    }
}

public void setInfos(String username){
    String url = config.LOGIN_URL+username;
    loading = ProgressDialog.show(this, " Please wait...", "Fetching...", false, false);
    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(LoginActivityMerchant.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String response) {
    String FirstName="";
    String LastName="";
    String UserName="";
    String Mobile="";
    String Location="";
    String Radius="";

    // String stringid="";
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
        JSONObject userData = result.getJSONObject(0);
        FirstName = userData.getString(KEY_firstName);
        UserName = userData.getString(KEY_UserName);
        LastName = userData.getString(KEY_LastName);
        Mobile = userData.getString(KEY_Mob);
        Location = userData.getString(KEY_Location);

        //stringid=userData.getString(KEY_USERID);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    config.KEY_NAME=FirstName + " "+LastName;

    config.KEY_USERNAME=UserName;
}

 }

loginold.php

<?php 

if($_SERVER['REQUEST_METHOD']=='POST'){
    //Getting values 
    $username = $_POST['User_Name'];
    $password = $_POST['Password'];

    //Creating sql query
    $sql = "SELECT * FROM User_Profile WHERE User_Name='$username' AND Password='$password'";

    //importing dbConnect.php script 
    require_once('include/dbConnect.php');

    //executing query
    $result = mysqli_query($con,$sql);

    //fetching result
    $check = mysqli_fetch_array($result);

    //if we got some result 
    if(isset($check)){
        //displaying success 
        echo "success";
    }else{
        //displaying failure
        echo "failure";
    }
    mysqli_close($con);
}
  else 
   {echo "error";}

You can use SharedPreference :

public class SaveId {

  static final String ID = "ID";

  static SharedPreferences getSharedPreferences(Context ctx) {
      return PreferenceManager.getDefaultSharedPreferences(ctx);
  }

  public static void setId(Context ctx, int value) {
      SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
      editor.putInt(ID, value);
      editor.commit();
  }

  public static String getId(Context ctx) {
      return getSharedPreferences(ctx).getString(ID, "");
  }

}

When you want to set the id call SaveId.setId(yourID); and when you want to get the id call SaveId.getId();

Instead of read and write to SharedPreferences I would prefer a more efficient way to store a simple data like an ID.

There are two ways:

  1. If you are using an MVP approach, you could delegate the setter and getter of the ID to your central manager, instead go for option 2

  2. Set the id in your custom application and get it through it.

You have to override default application and set it in the manifest.

public class MyApplication extends Application {
    private Integer id;

    public void setId(int id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }
}

In your activities you can get it through:

((MyApplication) getApplication()).getId();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM