preferences.getBoolean()返回默认值

时间:2018-05-15 09:47:09

标签: java android sharedpreferences

我正在使用sharedPreferences重用相同的活动。在Tab1中,我使用键设置了首选项中的布尔值,按下按钮时,“requestFromTab1”为true。使用密钥“requestFromTab2”的Tab2也是如此。但是在GalleryFragment中,我想要重用的活动总是在访问这些键时返回默认值。因此,我无法关闭Galleryfragment。提前谢谢。

Tab1.java

package com.example.android.tabswithswipes;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.tabswithswipes.Utils.CircleProgressBarDrawable;
import com.example.android.tabswithswipes.Utils.UniversalImageLoader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;

/**
 * Created by Chaitanya Shiva on 08-05-2018.
 */

public class Tab1 extends Fragment{
    SimpleDraweeView draweeView;
    Button uploadButton;
    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab1, container, false);
        draweeView = (SimpleDraweeView)v.findViewById(R.id.tab1DraweeView);
        uploadButton = (Button)v.findViewById(R.id.uploadBtn);
        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkWriteExternalPermission()){
            startActivity(new Intent(getActivity(), GalleryFragment.class));}
            else{       if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001);
                }
                        if(checkWriteExternalPermission()){
                            Intent intent = new Intent(getActivity(), GalleryFragment.class);
                            SharedPreferences preferences = getActivity().getSharedPreferences("MyPref",0);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putBoolean("requestFromTab1", true);
                            editor.commit();
                            startActivity(intent);
                        }
                }
            }
        });
        return v;
    }
    private boolean checkWriteExternalPermission(){
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
        int res = getContext().checkCallingOrSelfPermission(permission);
        return (res== PackageManager.PERMISSION_GRANTED);}
        else return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        final SharedPreferences preferences = getActivity().getSharedPreferences("MyPref",0);
        String data;
        if(preferences.contains("imgUriTab1")){
            data = preferences.getString("imgUriTab1",null);
            Uri imageUri = Uri.fromFile(new File(data));
            draweeView.getHierarchy().setProgressBarImage(new CircleProgressBarDrawable());
            draweeView.setImageURI(imageUri);
            uploadButton.setText("Change");
        }
    }
}

Tab2.java

package com.example.android.tabswithswipes;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.example.android.tabswithswipes.Utils.CircleProgressBarDrawable;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.File;

/**
 * Created by Chaitanya Shiva on 08-05-2018.
 */

public class Tab2 extends Fragment{
    SimpleDraweeView draweeView;
    Button uploadBtnTab2;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab2, container, false);
        draweeView = (SimpleDraweeView)v.findViewById(R.id.tab2DraweeView);
        uploadBtnTab2 = (Button)v.findViewById(R.id.uploadBtnTab2);
        uploadBtnTab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkWriteExternalPermission()){
                    startActivity(new Intent(getActivity(), GalleryFragment.class));}
                else{       if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001);
                }
                    if(checkWriteExternalPermission()){
                        Intent intent = new Intent(getActivity(), GalleryFragment.class);
                        SharedPreferences preferences = getActivity().getSharedPreferences("MyPref",0);
                        startActivity(intent);
                    }
                }
            }
        });

        return v;
    }

    private boolean checkWriteExternalPermission(){
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            int res = getContext().checkCallingOrSelfPermission(permission);
            return (res== PackageManager.PERMISSION_GRANTED);}
        else return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        final SharedPreferences preferences = getActivity().getSharedPreferences("MyPref",0);
        String data;
        if(preferences.contains("imgUriTab2")){
            data = preferences.getString("imgUriTab2", null);
            Uri imageUri = Uri.fromFile(new File(data));
            draweeView.getHierarchy().setProgressBarImage(new CircleProgressBarDrawable());
            draweeView.setImageURI(imageUri);
            uploadBtnTab2.setText("Change");
        }
    }
}

GalleryFragment.java

package com.example.android.tabswithswipes;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.tabswithswipes.Utils.CircleProgressBarDrawable;
import com.example.android.tabswithswipes.Utils.FilePaths;
import com.example.android.tabswithswipes.Utils.FileSearch;
import com.example.android.tabswithswipes.Utils.GridImageAdapter;
import com.example.android.tabswithswipes.Utils.Permissions;
import com.example.android.tabswithswipes.Utils.UniversalImageLoader;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by Chaitanya Shiva on 08-05-2018.
 */

public class GalleryFragment extends android.support.v4.app.FragmentActivity {
    private static final String TAG = "GalleryFrgment";
    private GridView gridView;
    private SimpleDraweeView galleryImage;
    private Spinner directorySpinner;
    private Context mContext = GalleryFragment.this;
    private String mSelectedImage;
    private ArrayList<String> directories;
    private String mAppend = "file:/";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_gallery);
        galleryImage = (SimpleDraweeView)findViewById(R.id.galleryImageView);
        galleryImage.getHierarchy().setProgressBarImage(new CircleProgressBarDrawable());
        gridView = (GridView)findViewById(R.id.gridView);
        directorySpinner = (Spinner)findViewById(R.id.spinnerDirectory);
        ImageView closeGallery = (ImageView)findViewById(R.id.closeGallery);
        closeGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        init();
        TextView nextScreen = (TextView) findViewById(R.id.tvNext);
        nextScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    SharedPreferences preferences = getSharedPreferences("MyPref",0);
                    if(preferences.getBoolean("requestFromTab1",false)){
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean("requestFromTab1", false);
                    editor.putString("imgUriTab1",mSelectedImage);
                    editor.commit();
                    finish();}
                    if(preferences.getBoolean("requestFromTab2",false)){
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("requestFromTab2", false);
                editor.putString("imgUriTab2",mSelectedImage);
                editor.commit();
                finish();}

            }
        });
    }

    private void init(){
        FilePaths filePaths = new FilePaths();
        if(FileSearch.getDirectoryPaths(filePaths.PICTURES)!=null){
            directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
        }
        directories.add(filePaths.CAMERA);
        ArrayList<String> directoryNames = new ArrayList<>();
        for(int i=0;i<directories.size();i++){
            int index = directories.get(i).lastIndexOf("/");
            String string = directories.get(i).substring(index).replace("/","");
            directoryNames.add(string);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, directoryNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        directorySpinner.setAdapter(adapter);

        directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setUpGridView(directories.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    private void setUpGridView(String selectedDirectory) {
        final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
        Collections.reverse(imgURLs);
        GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview, mAppend, imgURLs);
        gridView.setAdapter(adapter);
        if (imgURLs != null && imgURLs.size() > 0) {
            try {
                galleryImage.setImageURI(Uri.fromFile(new File(imgURLs.get(0))));
                mSelectedImage = imgURLs.get(0);
            } catch (ArrayIndexOutOfBoundsException e) {
                Log.e(TAG, "setUpGridView:ArrayIndexOutOfBounds: " + e.getMessage());
            }
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    galleryImage.setImageURI(Uri.fromFile(new File(imgURLs.get(position))));
                    mSelectedImage = imgURLs.get(position);
                }
            });
        }
    }



}

1 个答案:

答案 0 :(得分:0)

@Chaitanya Reddy问题是你正在使用Tabs Fragment,两个片段onCreateView方法会同时调用,因为如果你只有两个标签,tab会立即启动标签。

最好将共享偏好值放在标签活动之前。