2016-04-25 49 views
0

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

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

你正在做的是正确的。保存偏好并在需要时使用它。你面临的问题是什么? – drulabs

+0

使用单例可能会更有效,并且从SharedPreferences进行加载来填充。 – dharms

回答

1

您可以使用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, ""); 
    } 

} 

当你要设定的ID呼叫SaveId.setId(yourID);,当你想拨打电话SaveId.getId();

1

而不是读取和写入SharedPreferences我宁愿更有效的方式来存储一个简单的数据,如ID。

有两种方式:

  1. 如果您使用的是MVP的方法,你可以委托ID的setter和getter你的中央管理器,而不是去选择2

  2. 套装在您的自定义应用程序中的id并通过它。

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

public class MyApplication extends Application { 
    private Integer id; 

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

    public Integer getId() { 
     return id; 
    } 
} 

在你的活动,你可以得到它通过:

((MyApplication) getApplication()).getId(); 
+0

为什么你需要扩展应用程序? –

+0

@DavidSeroussi如何在不扩展的情况下向类添加方法? –

+0

我不扩展应用程序在我的getters和setters类,它的工作.. –

相关问题