您好,我正在尝试使用sharedpreferences检索用户名ID并进行一项活动,因此无法调用它,但是在另一项活动中,它被正确调用了
这是我的LoginActivity代码
public class Login extends AppCompatActivity {
ProgressDialog pDialog;
Button btn_login;
EditText txt_username, txt_password;
int success;
ConnectivityManager conMgr;
private String url = Server.URL_LOGIN;
private static final String TAG = Login.class.getSimpleName();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public final static String TAG_USERNAME = "username";
public final static String TAG_ID = "id_mentor";
public final static String TAG_ADMIN = "iwanwahyudi";
String tag_json_obj = "json_obj_req";
String user_type = "iwanwahyudi";
SharedPreferences sharedpreferences;
Boolean session = false;
String id_mentor, username, iwanwahyudi;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection",
Toast.LENGTH_LONG).show();
}
}
btn_login = (Button) findViewById(R.id.btn_login);
txt_username = (EditText) findViewById(R.id.txt_username);
txt_password = (EditText) findViewById(R.id.txt_password);
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id_mentor = sharedpreferences.getString(TAG_ID, null);
username = sharedpreferences.getString(TAG_USERNAME, null);
iwanwahyudi = sharedpreferences.getString(TAG_ADMIN, null);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String username = txt_username.getText().toString();
String password = txt_password.getText().toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
checkLogin(username, password);
} else {
Toast.makeText(getApplicationContext() ,"No Internet Connection", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext() ,"Kolom tidak boleh kosong", Toast.LENGTH_LONG).show();
}
}
});
}
private void checkLogin(final String username, final String password) {
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String id_mentor = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id_mentor);
editor.putString(TAG_USERNAME, username);
editor.commit();
if(txt_username.getText().toString().equals("iwanwahyudi")){
Intent intent1 = new Intent(Login.this, AdminActivity.class);
intent1.putExtra(TAG_ID, id_mentor);
intent1.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent1);
}
else {
Intent intent1 = new Intent(Login.this, MainActivity.class);
intent1.putExtra(TAG_ID, id_mentor);
intent1.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent1);
}
}else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
这是我要在其中输入用户名ID的AbsenAcvitivity
public class Absen extends AppCompatActivity implements View.OnClickListener {
SharedPreferences sharedpreferences;
String id_mentor, username;
public static final String TAG_ID = "id_mentor";
public static final String TAG_USERNAME = "username";
EditText keterangan1, tilawah1, ujian1, pekan1, materi1;
TextView nama1, nim2, id_mentor1;
private Button buttonSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_absen);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
id_mentor = getIntent().getStringExtra(TAG_ID);
username = getIntent().getStringExtra(TAG_USERNAME);
String nama = getIntent().getExtras().getString("nama");
String nim = getIntent().getExtras().getString("nim");
nama1 = (TextView) findViewById(R.id.nama);
nim2 = (TextView) findViewById(R.id.nim2);
id_mentor1 = (TextView) findViewById(R.id.text_view);
keterangan1 = (EditText) findViewById(R.id.keterangan);
tilawah1 = (EditText) findViewById(R.id.tilawah);
ujian1 = (EditText) findViewById(R.id.ujian);
pekan1 = (EditText) findViewById(R.id.pekan);
materi1 = (EditText) findViewById(R.id.materi);
buttonSave = (Button) findViewById(R.id.buttonSave);
nama1.setText(nama);
nim2.setText(nim);
id_mentor1.setText(id_mentor);
buttonSave.setOnClickListener(this);
}
private void addEmployee(){
final String nama = nama1.getText().toString().trim();
final String nim = nim2.getText().toString().trim();
final String pekan = pekan1.getText().toString().trim();
final String keterangan = keterangan1.getText().toString().trim();
final String materi = materi1.getText().toString().trim();
final String tilawah = tilawah1.getText().toString().trim();
final String ujian = ujian1.getText().toString().trim();
final String idmentor = id_mentor1.getText().toString().trim();
class AddEmployee extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Absen.this,"Menambahkan...","Tunggu...",false,false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(Absen.this,s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put(Server.KEY_EMP_PEKAN,pekan);
params.put(Server.KEY_EMP_NAMA,nama);
params.put(Server.KEY_EMP_NIM2,nim);
params.put(Server.KEY_EMP_KETERANGAN,keterangan);
params.put(Server.KEY_EMP_MATERI,materi);
params.put(Server.KEY_EMP_TILAWAH,tilawah);
params.put(Server.KEY_EMP_UJIAN,ujian);
params.put(Server.KEY_EMP_ID_MENTOR,idmentor);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Server.URL_ADD, params);
return res;
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
}
@Override
public void onClick(View v) {
if(v == buttonSave){
addEmployee();
}
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
以及正确调用用户名ID的MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences sharedpreferences;
String id_mentor, username;
public static final String TAG_ID = "id_mentor";
public static final String TAG_USERNAME = "username";
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
id_mentor = getIntent().getStringExtra(TAG_ID);
username = getIntent().getStringExtra(TAG_USERNAME);
Log.d("CEK mentor",id_mentor);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View hearedView = navigationView.getHeaderView(0);
textView = (TextView) hearedView.findViewById(R.id.textView);
textView.setText(id_mentor);
对不起我的语法不好,谢谢指教
根据我的了解,您永远不会使用Sharedpreference
中的值。您的MainActivity可以获取username ID
的原因是,当您从LoginActivity
成功登录时,您会将这些值与Intent
一起出现。当您使用Absen(Activity)
时,您可能无法通过意图放置这些值,因此它将为null并且不会显示。 [我仍然不知道你怎么称呼Absen(Activity)
,所以我想你不是通过Absen(Activity)
的意图发送数据的。
PS。您可以从sharedPreference
获取数据,因此没有理由通过Intent发送有关在共享首选项中也收集了哪些数据的数据。
您的问题是“您想使用sharePreference
获取用户ID”,但您没有使用它来获取用户ID。您正在使用intent
获取Absen Activity
中的用户ID。但是您也没有通过意图将数据传递到Absen Activity
。如果要使用sharePreferences
,则只需使用
id_mentor = sharedpreferences.getString(TAG_ID,"");
username = sharedpreferences.getString(TAG_USERNAME, "");
在Absen Activity
中。希望对您有帮助。 :)
通过这种方式,我们可以在sharedPreferences中保存并获取数据:
保存数据:
SharedPreferences pref = getApplicationContext().getSharedPreferences("my_shared_preferences", 0); // 0 - for private mode
Editor editor = pref.edit();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id_mentor);
editor.putString(TAG_USERNAME, username);
editor.commit();
要获取数据:
pref.getString(TAG_USERNAME, null); // getting String
pref.getString(TAG_ID, null); // getting String
您应该使用上面的代码通过sharedPreference获取数据