如何将User_Id传递给android中的每个活动?

时间:2016-04-25 20:52:53

标签: java php android mysql

我正在尝试构建一个Android应用程序。登录到应用程序后,我想使用User_Id进行所有活动,以获取基于该user_id的唯一数据。怎么可能?我想在此代码中进行哪些更改以在所有活动中获取user_id?

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";}

2 个答案:

答案 0 :(得分:1)

您可以使用SharedPreference:

$(document).ready(function () {
alert(“works”);
    });

如果您要设置ID调用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, ""); } } 以及何时想要获取ID SaveId.setId(yourID);

答案 1 :(得分:1)

不是对SharedPreferences进行读写,而是希望以更有效的方式存储像ID这样的简单数据。

有两种方法:

  1. 如果您使用的是MVP方法,您可以将ID的setter和getter委派给中央经理,而不是选择2

  2. 在自定义应用程序中设置ID并通过它。

  3. 您必须覆盖默认应用程序并将其设置在清单中。

    public class MyApplication extends Application {
        private Integer id;
    
        public void setId(int id) {
            this.id = id;
        }
    
        public Integer getId() {
            return id;
        }
    }
    

    在您的活动中,您可以通过:

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