Ваш вызов onCreate не выводит значение общей настройки, а значение переменной count, которое по умолчанию имеет значение true. Мы не знаем, какова фактическая ценность в то время, но, учитывая, что ваш onResume выводит его, вероятно, false.
Я пытаюсь сохранить Boolean count in onPause
и получить это при onResume
использовании SharedPreference
. Но когда я впервые запускаю приложение, я получаю false
значение count . Я не знаю почему. Я искал свой вопрос, не смог найти подходящий ответ.
Ниже приведен код одного из моих действий:
public class ListView extends AppCompatActivity {
private DatabaseReference mDatabase;
private ArrayList<String> url= new ArrayList<>();
private ArrayList<String> listitems = new ArrayList<>();
private ArrayAdapter mAdapter;
private android.widget.ListView listView;
private AlertDialog.Builder builder;
private int posi;
private boolean count =true;
BroadcastReceiver onComplete;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
Log.d("count onCreate",String.valueOf(count));
sharedPreferences = getSharedPreferences("Count",0);
builder = new AlertDialog.Builder(ListView.this);
final View coordinatorLayout = findViewById(android.R.id.content);
Intent intent = getIntent();
final String uri=intent.getStringExtra("uri");
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
mAdapter = new CustomAdapter(this,listitems);
listView = (android.widget.ListView)findViewById(R.id.listview);
mDatabase = FirebaseDatabase.getInstance().getReference().child(uri);
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
String key = dataSnapshot.getKey();
String value= dataSnapshot.getValue(String.class);
listitems.add(0,key);
url.add(0,value);
listView.smoothScrollToPosition(0);
mAdapter.notifyDataSetChanged();
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
if ((cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED) ||
(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
builder.setMessage("Do You Want To Download "+listitems.get(position)+" "+uri+ " ?");
builder.setTitle(R.string.confirm);
builder.setIcon(R.drawable.pdf);
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
posi = position;
Intent intent1 = new Intent(ListView.this, downloadService.class);
intent1.putExtra("uri", url.get(position));
startService(intent1);
Snackbar sb = Snackbar.make(coordinatorLayout, "Downloading in Background, See Notification", Snackbar.LENGTH_SHORT);
View sbView = sb.getView();
sbView.setBackgroundColor(getResources().getColor(R.color.material_orange));
sb.show(); }
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert1 = builder.create();
alert1.show();
}
else {
final View coordinatorLayout = findViewById(android.R.id.content);
Snackbar sb = Snackbar.make(coordinatorLayout, "No Internet Connection..!", Snackbar.LENGTH_SHORT);
View sbView = sb.getView();
sbView.setBackgroundColor(getResources().getColor(R.color.material_orange));
sb.show();
}
}
});
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),"Something Went Wrong :(" ,Toast.LENGTH_SHORT).show();
}
});
onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder builder = new AlertDialog.Builder(ListView.this);
builder.setTitle("Download Completed");
builder.setMessage("Do You Want To Open "+listitems.get(posi)+" "+uri+ " ?");
builder.setIcon(R.drawable.pdf);
builder.setNegativeButton("Later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("Open", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent inten = new Intent(ListView.this,onDownload.class);
inten.putExtra("uri",url.get(posi));
startService(inten);
}
});
AlertDialog alert = builder.create();
alert.show();
}
};
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(onComplete);
Log.d("count onPause",String.valueOf(count));
sharedPreferences.edit().putBoolean("count",count).apply();
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
count =sharedPreferences.getBoolean("count",true);
Log.d("count onResume",String.valueOf(count));
if (count){
count=false;
Toast.makeText(getApplicationContext(),"Loading...",Toast.LENGTH_SHORT).show();
}
}
}
Logcats
07-24 19: 15: 25.478 19784-19784 / com.example.mmstq.myapp D / count onCreate: true
07-24 19: 15: 25.489 19784-19784 / com.example.mmstq.myapp D / count onResume: false
android,sharedpreferences,oncreate,onresume,