SharedPreferences无法在活动中使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SharedPreferences无法在活动中使用相关的知识,希望对你有一定的参考价值。
我正在尝试在活动中获取SharedPreferences并将值设置为操作栏的标题,但我无法获取main_activity的值,但我可以在另一个中获取值,我不知道为什么以及如何。这是我保存SharedPreferences的代码:
public static final String Colloge_section="MyPrefsFile";
SharedPreferences.Editor
editor=getSharedPreferences(Colloge_section,MODE_PRIVATE).edit();
editor.putString("title_of_activity","student");
editor.apply();
这就是我获得SharedPreferences的方式:
SharedPreferences prfs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
String Astatus = prfs.getString("title_of_activity", "");
getSupportActionBar().setTitle(Astatus);
这是我的主要活动:
public class KworldActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView=null;
Toolbar toolbar=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kworld);
//set the fragment initialty
boolean net=isNetworkConnected();
if (net==true)
{
RssMainFragment fragment=new RssMainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
}else {
Toast.makeText(KworldActivity.this, "انت غير متصل بالانترنت الرجاء المحاوله لاحقا", Toast.LENGTH_LONG).show();
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SharedPreferences prfs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
String Astatus = prfs.getString("titleofactivity", "");
getSupportActionBar().setTitle(Astatus);
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kworld, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_about ) {
Intent homeIntent=new Intent(KworldActivity.this,AboutActivity.class);
startActivity(homeIntent);
finish();
//return true;
}else if(id == R.id.action_develop ) {
Intent homeIntent=new Intent(KworldActivity.this,DevelopActivity.class);
startActivity(homeIntent);
finish();
//return true;
}else if(id == R.id.action_share ) {
//Share Code is here
ApplicationInfo app = getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
Intent intent = new Intent(Intent.ACTION_SEND);
// MIME of .apk is "application/vnd.android.package-archive".
// but Bluetooth does not accept this. Let's use "*/*" instead.
intent.setType("*/*");
// Append file and send Intent
File originalApk = new File(filePath);
try {
//Make new directory in new location
File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
//If directory doesn't exists create new
if (!tempFile.isDirectory())
if (!tempFile.mkdirs())
return true;
//Get application's name and convert to lowercase
tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk");
//If file doesn't exists create new
if (!tempFile.exists()) {
if (!tempFile.createNewFile()) {
return true;
}
}
//Copy file to new location
InputStream in = new FileInputStream(originalApk);
OutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
//Open share dialog
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
startActivity(Intent.createChooser(intent, "Share app via"));
} catch (IOException e) {
e.printStackTrace();
}
//return true;
}else if(id == R.id.action_state ) {
buadd();
//return true;
}
return super.onOptionsItemSelected(item);
}
public void buadd(){
SharedPreferences prfs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
final String Std_id = prfs.getString("std_name", "");
Thread runt=new Thread(){
public void run(){
CallLibViewer cweb=new CallLibViewer();
cweb.OpenPhotoCopyViewer(Std_id);}
};
runt.start();
try{
runt.join();
Toast t1 =Toast.makeText(this, ContactResult.CopyViewerMessage,Toast.LENGTH_LONG);
View t2=t1.getView();
t2.setBackgroundColor(Color.BLACK);
t1.show();
}
catch(Exception ex){
}
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
SharedPreferences prfs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
String Astatus = prfs.getString("titleofactivity", "");
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_news:
fragment = new RssMainFragment();
getSupportActionBar().setTitle(Astatus);
break;
case R.id.nav_lib:
fragment = new LibraryFragment();
getSupportActionBar().setTitle("المكـتبة");
break;
case R.id.nav_notify:
fragment = new NotificationFragment();
getSupportActionBar().setTitle("لوحة الاشعارات");
break;
case R.id.nav_manage:
fragment = new OtherFragment();
getSupportActionBar().setTitle("خدمـات اخرى");
break;
case R.id.nav_contact:
fragment = new ContactFragment();
getSupportActionBar().setTitle("تواصل معنا");
break;
case R.id.nav_setting:
Intent homeIntent=new Intent(KworldActivity.this,SettingsActivity.class);
startActivity(homeIntent);
finish();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
}
答案
试试这段代码:
SharedPreferences sharedPreferencesObj=getApplicationContext().getSharedPreferences("MyPrefsFile", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferencesObj.edit();
editor.putString("title_of_activity","student");
editor.commit();
String title=sharedPreferencesObj.getString("title_of_activity", "")
另一答案
对SharedPreferences使用以下代码来保存数据
SharedPreferences prefs = context.getSharedPreferences("PrefName", context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Token", "tokenValue");
editor.apply();
用于获取数据
SharedPreferences preferences = context.getSharedPreferences("PrefName", context.MODE_PRIVATE);
String SavedToken= preferences.getString("Token", null);
以上是关于SharedPreferences无法在活动中使用的主要内容,如果未能解决你的问题,请参考以下文章