无法从共享首选项

时间:2015-09-15 11:54:20

标签: android checkbox sharedpreferences

我有一个复选框,我希望默认情况下取消选中它。即假。 在手动选中复选框时,即如果选中该复选框,它将在另一个类中执行某些操作。

我尝试使用SharedPreference保存复选框的状态,但是当我尝试使用GetBoolean获取另一个类中的复选框值时,我没有得到保存的值。

我的布局xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Number of Circle" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

    </EditText>

     <CheckBox
        android:id="@+id/chkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/enable_touch_checkBox"
        />


    <Button
        android:id="@+id/buttonAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="131dp"
        android:text="save" 
        />
</LinearLayout>

MyPreferenceActivity类

package de.vogella.android.wallpaper;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class MyPreferencesActivity extends Activity {
    private PrefManager pref;
    private TextView txtGoogleUsername, txtNoOfCircles, txtGalleryName;
    private CheckBox checkBox ;
    private Button btnSave;
    private Boolean checkBoxValue;
    private static final String PREF_NAME = "wallpaper";


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    txtNoOfCircles = (TextView) findViewById(R.id.editText1);
    checkBox = (CheckBox) findViewById(R.id.chkBox1);
    btnSave = (Button) findViewById(R.id.buttonAlert);

    pref = new PrefManager(getApplicationContext());
    txtNoOfCircles.setText(String.valueOf(pref.getNoOfGridCircles()));
    //checkBox.setChecked(pref.getCheckBox());

    /********************************/
    SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);
    checkBoxValue = sharedPreferences.getBoolean("Box", false);
    if(checkBoxValue){
        checkBox.setChecked(true);
    }
    else
    {
        checkBox.setChecked(false);
    }



    /********************************/

    /*saveLogin = pref.getCheckBox();
    if(saveLogin == true){
        checkBox.setChecked(true);
    }*/


    btnSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //savePreferences("Box", checkBox.isChecked());
            if(checkBox.isChecked())
            {
                //pref.setCheckBox(true);
                savePreferences("Box", checkBox.isChecked());
                Toast.makeText(getApplicationContext(),
                        "hii",
                        Toast.LENGTH_LONG).show();

            }
            else
            {
                savePreferences("Box", checkBox.isChecked());
                //pref.setCheckBox(false);
            }
            boolean vals = pref.getCheckBox();
            //checkBox = (CheckBox) findViewById(R.id.chkBox1);

            String no_of_columns = txtNoOfCircles.getText().toString()
                    .trim();
            //checkBox.get
            if (no_of_columns.length() == 0 || !isInteger(no_of_columns)) {
                Toast.makeText(getApplicationContext(),
                        getString(R.string.toast_enter_valid_number),
                        Toast.LENGTH_LONG).show();
                return;
            }

            if(no_of_columns != null || no_of_columns.equals(" ") )
            {

                if (!no_of_columns.equalsIgnoreCase(String.valueOf(pref
                                .getNoOfGridCircles()))) {
                    // User changed the settings
                    // save the changes and launch SplashScreen to initialize
                    // the app again
                   // pref.setGoogleUsername(googleUsername);
                    pref.setNoOfGridCircles(Integer.parseInt(no_of_columns));
                  //  pref.setCheckBox(val);

                 //   pref.setGalleryName(galleryName);

                    // start the app from SplashScreen
                    Intent i = new Intent(MyPreferencesActivity.this,
                            SetWallpaperActivity2.class);
                    // Clear all the previous activities
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);


                    startActivity(i);
                } else {
                    // user not modified any values in the form
                    // skip saving to shared preferences
                    // just go back to previous activity
                    onBackPressed();
                }

            }

        }

    });

}

public boolean isInteger(String input) {
    try {
        Integer.parseInt(input);
        return true;
    } catch (Exception e) {
        return false;
    }
}


private void savePreferences(String key, boolean value){
    //SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME,0);
    Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);
    editor.commit();

}

  }

我的wallpaperService类

package de.vogella.android.wallpaper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.animation.AnimatorSet.Builder;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.service.wallpaper.WallpaperService;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyWallpaperService extends WallpaperService {

    private final String TAG = getClass().getSimpleName();
    private static final String PREF_NAME = "wallpaper";
    //private PrefManager pref = new PrefManager(getApplicationContext());



    @Override
    public Engine onCreateEngine() {
        Log.i( TAG, "onCreateEngine" );
        return new MyWallpaperEngine();
    }

    private class MyWallpaperEngine<YourActivity> extends Engine {
        private final Handler handler = new Handler();
        private final Runnable drawRunner = new Runnable() {
            @Override
            public void run() {
                draw();
            }

        };
        private List<MyPoint> circles;
        private Paint paint = new Paint();
        Bitmap image = null;
        private int width;
        int height;
        private boolean visible = true;
        private int maxNumber;
        private int maxNumber2;
        private boolean touchEnabled;
        private boolean touchEnabled2;
        SharedPreferences prefs = null;


        int fatchDataSize = 10;
        ProdAdDetails []prodobj = new ProdAdDetails[fatchDataSize]; 
        HashMap<Integer,String> map = new HashMap<Integer,String>();
        Canvas canvas = null;
        public MyWallpaperEngine() 
{
            pref= new PrefManager(getApplicationContext());
            //prefs=PreferenceManager.getDefaultSharedPreferences(MyWallpaperService.this);
                    prefs = getSharedPreferences(PREF_NAME,0);

            touchEnabled = prefs.getBoolean("Box",false);




                    }

        @Override
        public void onVisibilityChanged(boolean visible) {
            this.visible = visible;
            if (visible) {
                handler.post(drawRunner);
            } else {
                handler.removeCallbacks(drawRunner);
            }
        }

        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            this.visible = true;
            handler.removeCallbacks(drawRunner);
        }
        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            this.width = width;
            this.height = height;
            super.onSurfaceChanged(holder, format, width, height);
        }

        @Override
        public void onTouchEvent(MotionEvent event) {
            if (touchEnabled) {
                if (event.getAction() == MotionEvent.ACTION_MOVE ) 
                 {                        
                    Toast.makeText(getApplicationContext(), "Move", Toast.LENGTH_SHORT).show();             
                 }
                 else
                 if (event.getAction() == MotionEvent.ACTION_DOWN) 
                 {                         
                    Toast.makeText(getApplicationContext(), "Down", Toast.LENGTH_SHORT).show();


                 }      

                super.onTouchEvent(event);
            } // if block end
        }


        private void draw() {
            SurfaceHolder holder = getSurfaceHolder();
            //Canvas canvas = null;
            try {
                canvas = holder.lockCanvas();
                if (canvas != null) {
                    if (circles.size() >= maxNumber2) {
                        circles.clear();
                        map = new HashMap<Integer,String>();
                    }
                    int x = (int) (width * Math.random());
                    int y = (int) (height * Math.random());

                    circles.add(new MyPoint(null, String.valueOf(circles.size() + 1), x, y));
                    drawCircles(canvas, circles);
                }
            } finally {
                if (canvas != null)
                    holder.unlockCanvasAndPost(canvas);
            }
            handler.removeCallbacks(drawRunner);
            if (visible) {
                handler.postDelayed(drawRunner, 10000);
            }
        }

        // Surface view requires that all elements are drawn completely
        private void drawCircles(Canvas canvas, List<MyPoint> circles) {
            canvas.drawColor(Color.LTGRAY);
            int i=0;
            for (MyPoint point : circles) {
                //-------------------------------
                paint.setTextSize(20);
                paint.setStrikeThruText(true);

                image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
                canvas.drawBitmap(image, point.x, point.y, null);
                //touchEnabled = ((SharedPreferences) paint).getBoolean("touch", true);
                //=====================================
                ProdAdDetails pad = prodobj[i];//(ProdAdDetails)point.prodobj;

                String prodName      = pad.getProd_name();
                String prodDtl       = pad.getProd_details();
                String prodCompName  = pad.getProd_comp_name();
                String prodPrice     = pad.getProd_price();

                final String prodDtls = prodDtl+"\nCompany :"+prodCompName+"\nRate :"+prodPrice+"%";
                canvas.drawText(prodName, point.x+1, point.y+1, paint);
                canvas.drawBitmap(image, point.x, point.y, null);
                int key = point.x;
                System.out.println("put:::"+key);
                map.put(key, prodDtls);
            //-------------------------------
                //canvas.drawPaint(paint);
                //Circle(point.x, point.y, 40.0f, paint);
                //Toast.makeText(getApplicationContext(), prodDtls, Toast.LENGTH_SHORT).show();
                i++;
            }
        }




    }




}

我已经发布了我的代码,任何建议或建议都会有所帮助,因为我无法理解我哪里出错了。

1 个答案:

答案 0 :(得分:0)

public static String KEY="Box";
    private void savePreferences(boolean value){
        SharedPreferences sharedpreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);    
        Editor editor = sharedpreferences.edit();
        editor.putBoolean(KEY,value);
        editor.commit();
        }

检索结束

SharedPreferences getpreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);   
boolean isChecked=getpreferences.getBoolean("Box",false);