首页 > 解决方案 > 使用 SharedPreference 保存后 onResume 上的变量值错误

问题描述

我正在尝试保存布尔计数并在using中onPause检索它。但是当我第一次启动应用程序时,我得到了count的值。我不知道为什么。我搜索了我的问题找不到匹配的答案。onResumeSharedPreferencefalse

以下是我的一项活动的代码:

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();
        }

    }
}

日志猫

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

标签: androidsharedpreferencesoncreateonresume

解决方案


这是因为当你第一次运行你的应用程序时,onResume()运行,参考Android的Activity生命周期,在这里看到Android Activity Lifecycle 这样你就可以处理它的第一次应用程序加载。


推荐阅读