I need to fix one problem.
In the Android Studio I am trying to use SharedPreferences and store the font type but there is something wrong with my code. Please help me out.
// Load Text Font start
SharedPreferences myTextFont = this.getSharedPreferences("MyTextFont", MODE_PRIVATE);
textFont = myTextFont.getInt("font", textExample.getTypeface().getStyle());
textExample.setTypeface(textExample.getTypeface());
textView3.setTypeface(textExample.getTypeface(), textExample.getTypeface().getStyle());
// Load Text Font end
//Font Buttons start
final Typeface typeface1 = ResourcesCompat.getFont(this,R.font.mkhatvruli);
type_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textExample.setTypeface(typeface1);
SharedPreferences myTextFont = getSharedPreferences("MyTextFont", MODE_PRIVATE);
SharedPreferences.Editor editor = myTextFont.edit();
editor.putInt("font", textExample.getTypeface().getStyle());
editor.commit();
}
});
When I click, the button font type changes in the text view but does not store.
I think that something is wrong here:
editor.putInt("font", textExample.getTypeface().getStyle());
Related
I have an ImageView ImageView1, whose background can be set by the user. How can I save the state of that background, so that when the user closes the app and reopens it, the background of ImageView1 is still the same?
Is it possible with onSaveInstanceState or do I have to write something different, and if so: How can I do this?
Right now I have:
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("ImageView1", imageView1);
but imageView1 gets red underline, even though declared before to id of ImageView
You can use shared preferences:
Save to shared preferences on change.
Get from shared preferences on app reopen.
Check documentation for more:
https://developer.android.com/training/data-storage/shared-preferences
You can use SharedPreferences as follows:
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("data", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("image", //put image path here);
editor.apply();
Then override the onResume method as follows
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("data", 0);
String imagePath = sharedPreferences.getString("image", ""); //default value is empty
}
Then load image using picasso or glide like..
Picasso.get().load(imagePath).into(imageview);
I am creating an android application, I am displaying images from drawable folder based on the numbering, my activity start showing images from number 1 and I am using buttons to show next or previous image.
I am trying to save the value of image user was viewing while pressed back button using shared preferences. my code looks like this
private int currentPage = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
final Button btnNext = findViewById(R.id.btnNext);
final Button btnBack = findViewById(R.id.btnBack);
listOfObjects = getResources().getStringArray(R.array.object_array);
images = getResources().obtainTypedArray(R.array.object_image);
itemImage = (ImageView)findViewById(R.id.imgSpace);
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,R.layout.my_spinner, listOfObjects);;
spinnerAdapter.setDropDownViewResource(R.layout.my_spinner);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
itemImage.setImageResource(images.getResourceId(spinner.getSelectedItemPosition(), -1));
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final ImageView img = findViewById(R.id.imgSpace);
PhotoView photoView = (PhotoView) findViewById(R.id.imgSpace);
img.setImageResource(getResources().getIdentifier("page_"+currentPage,"drawable",getPackageName()));
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItemPosition() < spinner.getAdapter().getCount()){
spinner.setSelection(spinner.getSelectedItemPosition()+1);
}
}
} );
}
currentPage is the variable which I want to save after pressing back button or to go to any other activity and also if user minimises the application, I want to pass it to main activity in order to show the extra button of resume activity and also to show the exact image the user was seeing before pressing the back button when user clicks on resume activity button.
I am using Chris Banes's photoview to show the image. I know how to pass variables and et them in PHP however android is new for me. ANy help would be appreciated.
SharedPreferences prefs = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", R.imageID).commit();
#Override
onBackPressed(){
image = prefs.getInt("image", defaultValue) //Default value is taken if the pref doesn't exist yet
}
onBackPressed() is called automatically by android when pressing the phone back button. You can call it manually:
onBackPressed();
I don't understand the question completely but you could write:
SharedPreferences prefs = getSharedPreferences("nameOFPref", MODE_PRIVATE);
private int currentPage = prefs.getInt("image", 1);
The way it works is it saves a file in nameOfPref in the "image" section so you get it back when the program launches. Here we put 1 as default value so the value it will take is 1 the first time you launch the program. You should write:
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", idOFImageCurrentlyVIewed).commit();
Later in the program each time the user changes image. So it will change the preference and will make sure that when you launch the program back currentImage will take the right value.
In android studio you can look at the file system of emulated phones. For preferences you need to go in Android/data/com.yourPackageName/preferences and you should see your file there if everything goes fine.
I have MainActivty and SettingsActivity, when I press a button in my SettingsActivity I want the background color of the MainActivity to change.
How do I achieve this?
Sorry if this question is a bit dumb, I recently started out and I'm a bit lost.
Save the color Hex as String or Integer of Color to SharedPreferences
and get it on activity #onCreate()
SharedPreferences preferences= context.getSharedPreferences(
"SharedPrefName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("SharedPrefKey","#FF0000" /*change this to what you want*/);
editor.apply();
then in activity get color
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String color = preferences.getString("SharedPrefKey", "#000000");
I have a series of ImageButtons in my app. Through the app, the user can set the background of the ImageButton to a drawable file.
This is working perfectly fine, when the user selects the image they would like and clicks a refresh button, the ImageButton's image changes.
The issue is, when I go to other activities the changed ImageButton's go and are returned to the default image.
I've been trying to do this through SharedPreferences. I've tried to get this working using all of the other similar questions on here with no luck.
I'm a complete beginner when it comes to SharedPreferences and I know that storing images isn't what it's built for, but it's the only way I can think of to solve my problem.
Any help would be MASSIVELY appreciated! Thanks in advance guys.
What I know about storing images with SharedPreferences:
I know that I have to convert the drawbable to a bitmap and then encode that into Base64 (because SharedPreferences will accept strings). I have done this, and I think the encoding is working.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
grey11.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] grey11base64 = byteArrayOutputStream.toByteArray();
final String encodedGrey11 = Base64.encodeToString(grey11base64, Base64.DEFAULT);
In my main activity (where the images are displayed), I currently have OnCreate and onStop methods and an onClick for the refresh button.
EDIT:
In my onCreate(Bundle savedInstantState):
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("drawableAgreen", R.drawable.a);
editor.commit();
Inside my Refresh button:
int drawableId = sharedPref.getInt("drawableId", 0);
ImageButton.setBackgroundResource(drawableId)
Just store the drawable id in SharedPreferences and refer it.
// store drawable id in SharedPreferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("drawableId", R.drawable.btn_background);
editor.commit();
// Read from sharedPref and set background
int drawableId = sharedPref.getInt("drawableId", 0);
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setBackgroundResource(drawableId);
Your'd better not store drawable id ,for every time compile your app, the id may be different.You could store drawable name in SharedPreferences and get those resources id by ResourcesUtils.
public class ResourcesUtils {
private static final String RES_ID = "id";
private static final String RES_STRING = "string";
private static final String RES_DRABLE = "drable";
public static int getId(Context context,String resName){
return getResId(context,resName,RES_ID);
}
public static int getStringId(Context context,String resName){
return getResId(context,resName,RES_STRING);
}
public static int getDrableId(Context context,String resName){
return getResId(context,resName,RES_DRABLE);
}
public static int getResId(Context context,String resName,String defType){
return context.getResources().getIdentifier(resName, defType, context.getPackageName());
}
}
I need some help getting a checkbox's state. Basically I want to get if a checkbox from an activity is checked then if it is, show some text on the main activity. I've read lots and lots of SO Q&As but nothing worked. I got this:
CheckBox show = (CheckBox) findViewById(R.id.checkBox);
public CheckBox getShow() {
return show;
}
So I'd use
CheckBox setty = Settings.getCheck();
on the other class. But I get an error:
Cannot resolve method 'getCheck()'
How can I do this? I need to get if it's on or off and display it on the main activity. Remember that I can't use Intents because I won't have a button to transition, the text and value must be always there on the main class.
you can use shared preference to store a checkbox check/uncheck value..and based on that value you can show text in your other activity.
here is the code:
public static final String MyPREFERENCES = "MyPrefs";
initialize shared preference in onCreate() method of first activity
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
CheckBox check1 = (CheckBox) view.findViewById(R.id.your_checkbox_id);
//now initialize listener for checkbox
check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("checked", "1");
editor.commit();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("checked", "0");
editor.commit();
}
}
});
Now in another activity you just have to load the shared preference data and show message based on condition
public void Load_checkbox() {
//define MyPREFERENCES in other activity too- same as first activity
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (shared.getString("checked", "").equals("1")) {
Toast.makeText(getApplicationContext(), "CheckBox Checked " ,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "CheckBox unchecked " ,Toast.LENGTH_LONG).show();
}
}
call this Load_checkbox() method in your second activity where u want to check the checkbox state of first activity