Я пытаюсь получить 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;
}
}