cannot able to fetch Boolean value from the shared Preference - android

I have a checkbox , I want it to be unchecked by default. i.e False.
On manually checking the checkbox, i.e if the checkbox is checked , it perform certain action in another class.
I tried to save the sate of the checkbox using SharedPreference, but when I tried to fetch the checkbox value in another class using GetBoolean , I am not getting the saved value.
my layout xml file
<?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 class
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();
}
}
My wallpaperService class
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++;
}
}
}
}
I have posted my code, any suggestion or advice will be of grate helpfull, as I am not able to understand where I am going wrong.

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();
}
Retrieving End
SharedPreferences getpreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
boolean isChecked=getpreferences.getBoolean("Box",false);

Related

How to update fragment/update fragment ui from activity?

Pageviewer.java code:
//hide status bar/action bar on single tap
package com.app.imageswiper;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Pageviwer extends AppCompatActivity {
private Integer[] mImageIds = {R.drawable.page001, R.drawable.page002,
R.drawable.page003};
private static final String DEBUG_TAG = "pageviwer ";
ImageView imageView;
float startXValue = 1;
public int num;
public int click;
protected static final String TAG = "Pageviwer";
private GestureDetector mGestureDetector;
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
setContentView(R.layout.pageviwer);
imageView = (ImageView) findViewById(R.id.image_place_holder);
imageView.setImageResource(mImageIds[0]);
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
setupGestureDetector();
hideActionBar(); // hide action bar after 1 second
}
private void setupGestureDetector() {
mGestureDetector = new GestureDetector(this,
new GestureDetector.SimpleOnGestureListener() {
//Detecting Swipe/Fling Direction
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
Log.i(TAG, "onFling");
if (e1.getX() < e2.getX()) {
Log.d(TAG, "Left to Right swipe performed");
if (num == 2) {
num = num;
} else {
imageView.setImageResource(mImageIds[num + 1]);
num = num + 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
if (e1.getX() > e2.getX()) {
Log.d(TAG, "Right to Left swipe performed");
if (num == 0) {
num = num;
} else {
imageView.setImageResource(mImageIds[num - 1]);
num = num - 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
return true;
}
//detecting single tap
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.i(TAG, "onSingleTapUp");
Toast.makeText(getApplicationContext(), "Single Tap ", Toast.LENGTH_LONG).show();
//Remove notification bar and action bar
if (click == 0) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
//Return notification bar and action bar
else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().show();
click = 0;
}
return true;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
public void hideActionBar() {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// DO DELAYED STUFF
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
}, 1000); // 1000 milliseconds (1 second)
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == com.app.imageswiper.R.id.action_settings) {
Bookmark=1;
prefs.edit().putInt("Bookmark", Bookmark).commit();
prefs.edit().putInt("Pageno", num).commit();
Toast.makeText(getApplicationContext(), "Bookmark value is "+Bookmark, Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter code:
package com.app.imageswiper;
/**
* Created by Jaffer on 14-Apr-16.
*/
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class Bookmarks extends Fragment {
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
Button sendButton = null;
View inflatedView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
this.inflatedView = inflater.inflate(R.layout.bookmarks, container, false);
sendButton = (Button) inflatedView.findViewById(R.id.bookmark);
if(Bookmark==1){sendButton.setText("Page "+Pageno);}
else {sendButton.setText("No Bookmark ");}
if(sendButton == null)
{
Log.d("debugCheck", "HeadFrag: sendButton is null");
return inflatedView;
}
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Pageviwer.class);
startActivity(intent);
}
});
return inflatedView;
}
}
bookmarks.xml code:
<?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"
android:id="#+id/bookmarks">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/bookmark"
android:layout_alignParentBottom="true" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
</LinearLayout>
I don't know how to update the button text from Pageviewer.java for the button with R.id.bookmark that shows up on the Bookmarks fragment on the click of menu item R.id.action_settings. I want to do this so that the button text corresponds to the page that is being bookmarked. I tried alot of things but to no avail. Can someone please help me with anything?
Thanks in advance
Create a method in your fragment to update the text of your button.
public void updateText(String newText){
//assuming button is globally declared in your fragment.
button.setText(newText);
}
Instead of Gesture Detector you could use a ViewPager which supports swiping to the left and right.You can find a sample implementation here.
Then in your Activty,implement PageChanegListener on ViewPager.
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.You have to implement viewpager's adapter with getItem(index) which returns a fragment at that index.
BookMarkFragment fragment (BookMarkFragment)mAdapter.getItem(position);
fragment.updateText(newText);
};
});
You should save the state of a button somewhere. Your field int Bookmark == 0, so expression sendButton.setText("Page "+Pageno); never execute. Save the state in SharedPreferences and get this state. Like this:
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int isBookmark = prefs.getInt("Bookmark", 0);
int mPageno = prefs.getInt("Pageno", 0);
...
if(isBookmark == 1){
sendButton.setText("Page " + mPageno);
} else {
sendButton.setText("No Bookmark");
}

Android: Settings "onResume"?

I'm working on a Android App and the layout and all the "android" specific stuff made a friend of my. I only was responsible for the "app" itself.
Nevertheless,
I would like to change some settings, e.g. change the server the stats produced by the app, should be transfered.
Here is the Settings.java:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class Settings extends Activity {
private Context mContext;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefEditor;
private EditText textName, textIP;
private RadioButton rdOnline, rdOffline;
private RadioGroup rdGroup;
private Button butSpeichern;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_settings);
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mPrefEditor = mPrefs.edit();
textName = (EditText) findViewById(R.id.txtBenutzer);
textIP = (EditText) findViewById(R.id.txtIP);
rdOffline = (RadioButton) findViewById(R.id.rdOffline);
rdOnline = (RadioButton) findViewById(R.id.rdOnline);
rdGroup = (RadioGroup) findViewById(R.id.radioDB);
butSpeichern = (Button) findViewById(R.id.btnSpeichern);
butSpeichern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSettings();
}
});
//Online default an
rdOnline.setChecked(true);
rdOffline.setChecked(false);
loadSettings();
//ggf. Lan
System.out.println("online");
if(automatischLAN()){
setLan();
}
}
private void saveSettings()
{
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.putString("benutzer", textName.getText().toString());
mPrefEditor.putString("ip", textIP.getText().toString());
mPrefEditor.apply();
finish();
}
private void loadSettings() {
textName.setText(mPrefs.getString("benutzer", ""));
textIP.setText(mPrefs.getString("ip", "192.168.0.50"));
rdOnline.setChecked(mPrefs.getBoolean("onlineDB", true));
rdOffline.setChecked(!mPrefs.getBoolean("onlineDB", true));
}
public boolean automatischLAN(){
Calendar cal = new GregorianCalendar();
Date currenttimen = new Date();
cal.setTime(currenttimen);
int freitag = cal.get(Calendar.DAY_OF_WEEK);
int STUNDE = 0;
STUNDE = cal.get(Calendar.HOUR_OF_DAY);
System.out.println(STUNDE);
if(freitag == Calendar.FRIDAY && STUNDE>11 && STUNDE< 14 ) {
System.out.println("lan");
return false;
}
else {
System.out.println("online");
return true;
}
}
public void onBackPressed()
{
saveSettings();
super.onBackPressed();
}
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
}
}
I'm afraid my setLan() method isn't working as the values are not stored in the prefs...
What is the easieast way to check prefs and chance them on each start of the app?
Thanks for your help
You have to commit the changes in the SharedPreference.Editor variable. Replace your function above with the given one
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.apply();
}

Unable to access views in android

I am using metaio sdk. I am trying to simply toggle the visibility of two imageviews when pressing a button but it is not working.
My layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ma_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00000000" >
-----
<ImageView
android:id="#+id/zoomIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="4dp"
android:layout_marginRight="4dp"
android:background="#drawable/zooming"
android:onClick="seeZoom" />
<ImageView
android:id="#+id/scrollerBg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#drawable/scrollerbg"
android:visibility="invisible"/>
<ImageView
android:id="#+id/scroller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#drawable/scroller"
android:visibility="invisible"/>
---
</RelativeLayout>
My code:
import android.view.MotionEvent;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKAndroid;
import com.metaio.sdk.jni.Vector3d;
import android.os.Environment;
import com.metaio.sdk.ARViewActivity;
import com.metaio.sdk.jni.EPLAYBACK_STATUS;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.MovieTextureStatus;
import com.metaio.sdk.jni.Rotation;
import com.metaio.sdk.MetaioDebug;
import com.company.abc.R;
public class MainActivity extends ARViewActivity
{
public RelativeLayout mGUIView;
//public ImageView imgView1;
//public ImageView imgView2;
Camera camera;
private IGeometry tdp1, tdp2, tdp3, tdp4, tdp5, tdp6, tdp7, sal1, sal2;
boolean isTorchOn=false;
Parameters camParams;
public ImageView basePng;
public ImageView zoomIcon;
ImageView scroller;
public LayoutParams scrollerParams;
ImageView scrollerBg;
public LayoutParams scrollerBgParams;
boolean afc;
int counter;
int displayWidthbyTwo;
int displayHeightbyTwo;
int scrollerW;
int scrollerH;
int scrollerBgW;
int scrollerBgH;
int ZoomValue=0;
int maxZoomLevel;
int maxZoombyfour;
boolean zoomSupported;
boolean isZoomBarVisible=false;
private MetaioSDKCallbackHandler mCallbackHandler;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MetaioDebug.enableLogging(true);
mCallbackHandler = new MetaioSDKCallbackHandler();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
displayWidthbyTwo=metrics.widthPixels/2;
displayHeightbyTwo=metrics.heightPixels/2;
PackageManager PM= this.getPackageManager();
afc = PM.hasSystemFeature(PackageManager.FEATURE_CAMERA_AUTOFOCUS);
setContentView(R.layout.mainactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mGUIView = (RelativeLayout) getLayoutInflater().inflate(R.layout.mainactivity, null);
zoomIcon = (ImageView) mGUIView.findViewById(R.id.zoomIcon);
scroller = (ImageView) mGUIView.findViewById(R.id.scroller);
scrollerBg = (ImageView) mGUIView.findViewById(R.id.scrollerBg);
scroller.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
scrollerW = scroller.getMeasuredWidth()/2;
scrollerH = scroller.getMeasuredHeight()/2;
scrollerParams = (LayoutParams) scroller.getLayoutParams();
scrollerParams.topMargin = displayHeightbyTwo-150-scrollerH;
scroller.setLayoutParams(scrollerParams);
scrollerBg.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
scrollerBgW = scrollerBg.getMeasuredWidth()/2;
scrollerBgH = scrollerBg.getMeasuredHeight()/2;
scrollerBgParams = (LayoutParams) scrollerBg.getLayoutParams();
scrollerBgParams.topMargin = displayHeightbyTwo-scrollerBgH;
scrollerBg.setLayoutParams(scrollerBgParams);
scroller.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) scroller.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
//Get y coord of the touch point relative to screen
int y_cord = (int) event.getRawY();
//Restrict scroller bewtween center of screen +- 150
if(y_cord>(displayHeightbyTwo+150))
y_cord = displayHeightbyTwo+150;
if(y_cord<(displayHeightbyTwo-150))
y_cord = displayHeightbyTwo-150;
//Set zoom levels at various steps
if(y_cord<=displayHeightbyTwo-90){
camParams.setZoom(0);
Log.i("Zooming:","0");
ZoomValue=0;}
if(y_cord<=displayHeightbyTwo-30 && y_cord>displayHeightbyTwo-90){
camParams.setZoom(maxZoombyfour);
Log.i("Zooming:","1");
ZoomValue=1;}
if(y_cord<=displayHeightbyTwo+30 && y_cord>displayHeightbyTwo-30){
camParams.setZoom(maxZoombyfour*2);
Log.i("Zooming:","2");
ZoomValue=2;}
if(y_cord<=displayHeightbyTwo+90 && y_cord>displayHeightbyTwo+30){
camParams.setZoom(maxZoombyfour*3);
Log.i("Zooming:","3");
ZoomValue=3;}
if(y_cord>displayHeightbyTwo+90){
camParams.setZoom(maxZoomLevel);
Log.i("Zooming:","4");
ZoomValue=4;}
camera.setParameters(camParams);
scrollerParams.topMargin = y_cord-scrollerH;
scroller.setLayoutParams(scrollerParams);
break;
default:
break;
}
return true;
}
});
}
#Override
protected int getGUILayout()
{
// TODO: return 0 in case of no GUI overlay
return R.layout.mainactivity;
}
#Override
protected void onStart()
{
super.onStart();
// hide GUI until SDK is ready
//if (!mRendererInitialized)
//mGUIView.setVisibility(View.GONE);
// add GUI layout
addContentView(mGUIView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
#Override
protected void loadContents()
{
// Load desired tracking data for planar marker tracking
String Path = "storage/sdcard1/AS/tdp/";
//final String trackingConfigFile = AssetsManager.getAssetPath("Tracking.xml");
boolean result = metaioSDK.setTrackingConfiguration(Path+"Tracking.xml");
String movie1Path = Path + "movie1.3gp";
tdp1 = metaioSDK.createGeometryFromMovie(movie1Path, false) ;
tdp1.setCoordinateSystemID(1);
tdp1.setScale(new Vector3d(4.0f,4.0f,4.0f));
tdp1.startMovieTexture(true); // loop = true;
}
#Override
protected void onGeometryTouched(IGeometry geometry) {
// TODO Auto-generated method stub
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onSurfaceChanged(int width, int height) {
//always call the super implementation first
super.onSurfaceChanged(width, height);
camera=IMetaioSDKAndroid.getCamera(this);
camParams = camera.getParameters();
if(afc){
List<String> focusModes = camParams.getSupportedFocusModes();
if(focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))
camParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
camParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
camera.setParameters(camParams);
}
if(camParams.isZoomSupported()){
this.runOnUiThread(new Runnable(){
public void run(){
zoomIcon.setVisibility(View.VISIBLE);
}
});
maxZoomLevel = camParams.getMaxZoom();
maxZoombyfour = Math.round(maxZoomLevel/4);
zoomSupported=true;
}
}
#Override
protected IMetaioSDKCallback getMetaioSDKCallbackHandler()
{
return mCallbackHandler;
}
final class MetaioSDKCallbackHandler extends IMetaioSDKCallback
{
}
public void showTorch(View v) {
if(isTorchOn){
IMetaioSDKAndroid.stopTorch(this);
isTorchOn=false;
}
else{
IMetaioSDKAndroid.startTorch(this);
isTorchOn=true;
}
}
public void seeZoom(View v) {
if(isZoomBarVisible){
scroller.setVisibility(0);
//scrollerBg.setVisibility(View.INVISIBLE);
isZoomBarVisible=false;
Log.i("ss","ss");
}
else{
scroller.setVisibility(1);
isZoomBarVisible=true;
Log.i("ss","ss");
}
}
public void seeSettings(View v) {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
//finish();
}
public void seeCatalog(View v) {
Intent intent = new Intent(this, CatalogueActivity.class);
startActivity(intent);
//finish();
}
}
I am trying in multiple ways since hours but none of them work . plesae tell me how to access the views from xml. This code used to work previously but it is not working now. Android programming really seems frustrating.
Thanks in advance
You must use setContent(R.layout.your_layout); inside onCreate
Like this
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//mGUIView = (RelativeLayout) getLayoutInflater().inflate(R.layout.scan, null);
setContent(R.layout.your_layout);
scroller = (ImageView) mGUIView.findViewById(R.id.scroller);
scrollerBg = (ImageView) mGUIView.findViewById(R.id.scrollerBg);
}
I guess the error is at 'R',
All you need to do is import your package.R
Example
...
import com.yourpackage.yourappname.R; //Import this
#Override
public void onCreate(Bundle savedInstanceState) {
MetaioCloudPlugin.startJunaio(null, getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
...
Then it should work fine :D
I encountered the same issue before. I managed to solve it by clearing the cache, data and uninstall the app from the device. It is working after I re-publish the app to the testing device. Maybe you could try it.

Sensor Reading keeps increasing even after closing app, Android

I have make this app which calculates Linear Acceleration of device of all dimension, combines it, and calculates net acceleration. Top five acceleration values are stored in Shared Preference key-value pairs.
The problem is when I close the app and reopen it, I find the values increased to a much higher level. I don't seem to catch the point in the code from where it is happening.
Please Help me out.
ShakoMeter.java (this is my main activity where all sensor data is collected and stored)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ShakeOMeter extends Activity implements SensorEventListener{
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SensorManager smngr;
Sensor sen;
TextView t,t3;
double max=-1;
double ax = 0,ay = 0,az = 0;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
ArrayList<Float> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shake_ometer);
t = (TextView)findViewById(R.id.TextView1);
// Showing initial message
TextView textview = new TextView(getApplicationContext());
textview.setText("Get ready to Shake It!!");
textview.setBackgroundColor(Color.BLACK);
textview.setTextColor(Color.WHITE);
textview.setTextSize(30);
textview.setPadding(10,10,10,10);
textview.setGravity(Gravity.CENTER_VERTICAL);
Toast toast = new Toast(getApplicationContext());
toast.setView(textview);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.FILL, 0, 0);
toast.show();
//Getting Sensor Control
smngr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sen = (Sensor) smngr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
//Obtaining SharedPreferance for storing key-value pairs of high scores.
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shake_ometer, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
list = new ArrayList<Float>();
ax = event.values[0];
ay = event.values[1];
az = event.values[2];
double temp=Math.sqrt(ro(ax)*ro(ax)+ro(ay)*ro(ay)+ro(az)*ro(az));
if(temp>=max){
max=temp;
t.setText(ro(max)+"");
list.add(sharedPref.getFloat("1", 0));
list.add(sharedPref.getFloat("2", 0));
list.add(sharedPref.getFloat("3", 0));
list.add(sharedPref.getFloat("4", 0));
list.add(sharedPref.getFloat("5", 0));
if(max>list.get(0)){
list.remove(0);
list.add((float) max);
Collections.sort(list);
editor.putFloat("1", list.get(0));
editor.putFloat("2", list.get(1));
editor.putFloat("3", list.get(2));
editor.putFloat("4", list.get(3));
editor.putFloat("5", list.get(4));
editor.commit();
System.out.println(sharedPref.getFloat("5", 0)+" "
+sharedPref.getFloat("4", 0)+" "
+sharedPref.getFloat("3", 0)+" "
+sharedPref.getFloat("2", 0)+" "
+sharedPref.getFloat("1", 0));
}
}
}
public void onClickReset(View view){
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void onClickTopFive(View view){
Intent intent = new Intent(getApplicationContext(),TopFive.class);
startActivity(intent);
}
#Override
protected void onResume(){
super.onResume();
final ShakeOMeter sh = this;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
smngr.registerListener(sh, sen, SensorManager.SENSOR_DELAY_NORMAL);
}
},3000);
}
#Override
protected void onPause() {
super.onPause();
smngr.unregisterListener(this);
}
protected void onStop(){
super.onStop();
smngr.unregisterListener(this);
}
public void onDestroy(){
super.onDestroy();
smngr.unregisterListener(this);
finish();
}
}
TopFive.java (This is a sub Activity where top five activities are displayed)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class TopFive extends Activity {
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SharedPreferences sharedPref;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_five);
// Show the Up button in the action bar.
setupActionBar();
TextView t1 = (TextView) findViewById(R.id.T1);
TextView t2 = (TextView) findViewById(R.id.T2);
TextView t3 = (TextView) findViewById(R.id.T3);
TextView t4 = (TextView) findViewById(R.id.T4);
TextView t5 = (TextView) findViewById(R.id.T5);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
edit = sharedPref.edit();
t1.setText(ro(sharedPref.getFloat("1", 0))+"");
t2.setText(ro(sharedPref.getFloat("2", 0))+"");
t3.setText(ro(sharedPref.getFloat("3", 0))+"");
t4.setText(ro(sharedPref.getFloat("4", 0))+"");
t5.setText(ro(sharedPref.getFloat("5", 0))+"");
}
public void onClickReset(View view){
edit.putFloat("1", 0);edit.commit();
edit.putFloat("2", 0);edit.commit();
edit.putFloat("3", 0);edit.commit();
edit.putFloat("4", 0);edit.commit();
edit.putFloat("5", 0);edit.commit();
Intent intent = getIntent();
finish();
startActivity(intent);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.top_five, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}

How do I get android preferences to work?

Sorry about this guys. This must be like the third question I've had to ask about this project alone. =(
What i want to be able to do is toggle the visibility of a radio button using a check box in a preferences activity.
There are no errors in my code and both activities run fine, but there is no change in visibility when the check box is checked or unchecked.
Here is my Activity with the radiobuttons
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import com.medialets.android.analytics.MMAnalyticsManager;
public class Temperature extends Activity {
MMAnalyticsManager mManager;
private EditText text;
public void onStart(Bundle savedInstanceState){
super.onStart();
getPrefs();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.temperature);
text = (EditText)findViewById(R.id.EditText01);
mManager = MMAnalyticsManager.sharedInstance(this);
mManager.start("codeHere", "1.0",
false);
}
#Override
public void onPause() {
super.onPause();
mManager.pause();
}
#Override
public void onResume() {
super.onResume();
mManager.resume();
}
#Override
public void onDestroy() {
super.onDestroy();
mManager.stop();
}
public void myClickHandler(View view){
switch (view.getId()) {
case R.id.Button01:
RadioButton celsiustokelvinButton = (RadioButton) findViewById (R.id.RadioButton05);
RadioButton celsiustofarenheitButton = (RadioButton) findViewById(R.id.RadioButton01);
RadioButton farenheittocelsiusButton = (RadioButton) findViewById(R.id.RadioButton02);
RadioButton farenheittokelvinButton = (RadioButton) findViewById(R.id.RadioButton06);
RadioButton kelvintocelsiusButton = (RadioButton) findViewById (R.id.RadioButton03);
RadioButton kelvintofarenheitButton=(RadioButton) findViewById (R.id.RadioButton04);
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiustofarenheitButton.isChecked()) {
text.setText(String
.valueOf(convertCelsiusToFarenheit(inputValue)));
} if (farenheittocelsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFarenheitToCelsius(inputValue)));
} if (celsiustokelvinButton.isChecked()) {
text.setText(String
.valueOf(convertCelsiusToKelvin(inputValue)));
} if (farenheittokelvinButton.isChecked()) {
text.setText(String
.valueOf(convertFarenheitToKelvin(inputValue)));
} if (kelvintocelsiusButton.isChecked()) {
text.setText(String
.valueOf(convertKelvinToCelsius(inputValue)));
} if (kelvintofarenheitButton.isChecked()) {
text.setText(String
.valueOf(convertKelvinToFarenheit(inputValue)));
}
break;
}}
private float convertFarenheitToCelsius(float fahrenheit){
return ((fahrenheit - 32) * 5 / 9);
}
private float convertCelsiusToFarenheit(float celsius){
return ((celsius * 9) / 5) + 32;
}
private double convertCelsiusToKelvin(float celsius){
return celsius + 273.15;
}
private double convertFarenheitToKelvin(float farenheit){
return ((farenheit-32)/(1.8));
}
private double convertKelvinToCelsius(float kelvin){
return kelvin-273.1;
}
private double convertKelvinToFarenheit(float kelvin){
return kelvin*1.8-459.67;
}
boolean CheckboxPreference;
private void getPrefs() {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
}
}
And here is my Preferences Activity
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class Preferences extends PreferenceActivity {
private RadioButton btn01;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
btn01 = (RadioButton)findViewById(R.id.RadioButton01);
Preference customPref = (Preference) findPreference("customPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),"The Custom Preference Has Been Clicked",Toast.LENGTH_LONG).show();
SharedPreferences customSharedPreference = getSharedPreferences("myCutomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("myCustomPref","The preference has been clicked");
editor.commit();
CheckBox();
return true;
}
private void CheckBox() {
final CheckBox ThisCheckBox = (CheckBox) findViewById (R.id.checkboxPref);
ThisCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoundButton,boolean test) {
if (ThisCheckBox.isChecked()){
btn01.setVisibility(View.VISIBLE);
} else {
btn01.setVisibility(View.GONE);
}
}
});
};
});
}}
Sorry there is other stuff in there as well such as an analytics plug in
Anyone have any idea as to why this just isn't working
(Just a side note. When looking at the logcat, clicking the checkbox returned no results)
EDIT: OK i've just ammended my code as suggested but i'm afraid that the preferences still do not affect anything. Anybody have any ideas?? =(
It's not working because for visiblity the values you should use are (reference):
0 = VISIBLE
4 = INVISIBLE
8 = GONE

Categories

Resources