2016-04-25 7 views
0

私はアンドロイドアプリケーションを構築しようとしています。アプリケーションにログインした後、そのuser_idに基づいて一意のデータを取得するために、すべてのアクティビティに対して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";} 
+0

。環境設定を保存し、必要に応じて使用します。あなたが直面している問題は何ですか? – drulabs

+0

シングルトンを使用するほうが効率的で、SharedPreferencesからロードした方が効率的です。 – dharms

答えて

1

を使用できSharedPreference:あなたがしたいときは、IDコールSaveId.setId(yourID);を設定したいと

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.getId();

1

SharedPreferencesに読み書きするのではなく、IDのような単純なデータを保存する方が効率的です。

2つの方法があります。

  1. あなたがMVPのアプローチを使用している場合は、オプション2

  2. セットのために行く代わりに、あなたの中央マネージャにIDのセッターとゲッターを委任することができあなたのカスタムアプリケーションの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

私はgetterクラスとsetterクラスでアプリケーションを拡張していません。それは動作します。 –

関連する問題