WebHU - Programozási kérdések és válaszok

nem tud lekérni logikai értéket a megosztott beállításokból

Van egy jelölőnégyzetem, szeretném, ha alapértelmezés szerint ne legyen bejelölve. azaz hamis. A jelölőnégyzet manuális bejelölése esetén, azaz ha a jelölőnégyzet be van jelölve, akkor bizonyos műveleteket hajt végre egy másik osztályban.

Megpróbáltam menteni a jelölőnégyzet állapotát a SharedPreference segítségével, de amikor megpróbáltam lekérni a jelölőnégyzet értékét egy másik osztályban a GetBoolean segítségével, nem kapom meg a mentett értéket.

elrendezésű xml fájlom

<?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 osztály

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

}

  }

Saját háttérkép szolgáltatás osztály

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++;
            }
        }




    }




}

Elküldtem a kódomat, minden javaslat vagy tanács nagyon hasznos lesz, mivel nem tudom megérteni, hol hibázok.


  • Adja meg a "kulcs" attribútumot a jelölőnégyzet beállításához, és használja ezt a kulcsot a prefs.getBoolean() fájlban olvasás és írás közben. 15.09.2015

Válaszok:


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

Visszakeresés vége

SharedPreferences getpreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);   
boolean isChecked=getpreferences.getBoolean("Box",false);
15.09.2015
  • köszönöm rajan.az általad megadott kód működött nekem. Köszönöm minden idejét és segítségét. 17.09.2015
  • Megpróbáltam, de azt az üzenetet adja, hogy 15 hírnévre van szükségem, akkor csak ez fog számítani 18.09.2015
  • Új anyagok

    A rádiógomb ellenőrzött eseményének használata a jQueryben
    Ebben a cikkben látni fogjuk, hogyan kell dolgozni a jquery választógombbal ellenőrzött eseményeivel. A választógombok HTML gombok, amelyek segítenek kiválasztani egyetlen értéket egy csoportból...

    Körkörös függőségek megoldása terraformban adatforrásokkal – lépésről lépésre
    Mi az a körkörös függőségek Dolgozzunk egy egyszerű eseten, amikor az SQS-sor és az S3-vödör közötti körkörös függőség problémája van egy egymástól függő címkeérték miatt. provider..

    Miért érdemes elkezdeni a kódolást 2023-ban?
    01100011 01101111 01100100 01100101 — beep boop beep boop Világunk folyamatosan fejlődik a technológia körül, és naponta fejlesztenek új technológiákat a valós problémák megoldására. Amint..

    🎙 Random Noise #2  – Örökbefogadás és hit
    az analitika íratlan világának gondozása Szeretné, hogy ezek a frissítések a postaládájába kerüljenek? Iratkozzon fel itt . "Ha önvezető autókat gyártanak, akkor mi miért ne..

    A legrosszabb politika és prediktív modellek májátültetésre jelöltek számára az Egyesült Államokban
    A máj (vagy óangolul lifer) az emberi test legnehezebb belső szervére utal, amely csendesen működik a nap 24 órájában. Mit csinál a máj? 500 feladatot hajt végre a szervezet egészségének..

    5 webhely, amely 2022-ben fejleszti front-end fejlesztői készségeit
    Frontendmentor.io A tényleges projektek létrehozásával a Frontendmentor.io segítséget nyújt a front-end kódolási képességeinek fejlesztésében. A kódolást azután kezdheti meg, hogy..

    Mikor kell használni a Type-t az interfészhez képest a TypeScriptben?
    A TypeScript a JavaScript gépelt szuperkészlete, amely statikus gépelést ad a nyelvhez. Ez megkönnyíti a robusztus és karbantartható kód írását azáltal, hogy a hibákat a fordítási időben..