My application is related to alarm. I used material AlertDialog in my application. I choose one value from AlertDialog and press choose button. I want to store that selected values. It value sets until I do not changed it. How do I?
final Dialog dialog = new MaterialDialog.Builder(Settings_Activity.this)
.title(R.string.full_battery_alarm1)
.iconRes(R.mipmap.ic_launcher)
.limitIconToDefaultSize()
.items(R.array.full_battery_alarm)
.itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog mdialog, View view, int pos, CharSequence text) {
manager.sessionWork(pos);
showToast(pos + " = " + text);
int i = Integer.parseInt(text.toString());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Settings_Activity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("select full", Integer.toString(i));
editor.apply();
String abc = preferences.getString("select full", null);
final int l = Integer.parseInt(abc);
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
showToast("level full" + level);
if (level == l) {
showToast("level full 2"+level);
Intent i1 = new Intent(Settings_Activity.this, StopActivity.class);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
}
}
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
mdialog.setSelectedIndex(pos);
return true;
}
})
.positiveText(R.string.choose)
.show();
Store it in shared preference or just use a db line sql lite
You can use SharedPreferences like this. Create your SharedPreferences and Editor.
static SharedPreferences sharedData;
static SharedPreferences.Editor editor;
now
sharedData = getSharedPreferences("mySharedPreference", Context.MODE_PRIVATE);
editor = sharedData.edit();
after this to save your value do
editor.putString("valueKey", ""+yourvaluevariable); editor.commit();
Now this value is saved and will be retrieved event when you will start the app later after closing it.
To access that value afterwards use
sharedData.getString("valueKey", "");
Related
I am constructing widgets which give you the best currency rate for the values you choose. On the homePage, when I click on widgets and select the widget I want to create, the WidgetConfigure Application should launch.
However, it crashes before the configure page even launches and I get this error:
java.lang.RuntimeException:java.lang.IndexOutOfBoundsException: Index: 2, Size: 2. This is the code it refers to:
// Set the currencies for each object
for(String currency: preferredCurrencies){
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount+=1;
}
The code is in one of my widget methods responsible for updating it.
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId, List<CurrencyObject> currencyObjects, Intent clickIntent) {
theAppWidgetManager = appWidgetManager;
// There may be multiple widgets active, so update all of them
// Get the preferred Currencies
Set<String> preferredCurrencies = AppWidgetConfigure.loadCurrencyPref(context,appWidgetId);
// Inflate the layout
RemoteViews view = new RemoteViews(context.getPackageName(), layout);
// if the preferred Currencies have been declared already
if(preferredCurrencies!= null){
// Set the currencies for each object
*for(String currency: preferredCurrencies){
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount+=1;
}*
}
else{
for(CurrencyObject curObj:currencyObjects){
curObj.setCurrencyType("EUR");
}
}
currencyCount = 0;
}
In my widget configure class I have these methods, where I set the preferredCurrencies:
private static final String PREFS_NAME = "change.Widgets";
private static final String PREF_PREFIX_KEY = "appwidget_";
int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
private List<String> currencies = new ArrayList<>();
private int checkCounter;
private Set<String> chosenCurrencies = new TreeSet<>();
static void saveCurrencyPref(Context context, int appWidgetId, Set<String> chosenCurrencies) {
SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
prefs.putStringSet(PREF_PREFIX_KEY + appWidgetId, chosenCurrencies);
prefs.apply();
}
static void deleteCurrencyPref(Context context, int appWidgetId) {
SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
prefs.remove(PREF_PREFIX_KEY + appWidgetId);
prefs.apply();
}
public static Set<String> loadCurrencyPref(Context context, int appWidgetId) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
Set chosenCurrencies = prefs.getStringSet(PREF_PREFIX_KEY + appWidgetId, null);
return chosenCurrencies;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If this activity was started with an intent without an app widget ID, finish with an error.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
return;
}
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if the user presses the back button.
setResult(RESULT_CANCELED);
// Create the layout with the checkboxes and the Button.
setContentView(R.layout.widget_configure);
LinearLayout ll = (LinearLayout) findViewById(R.id.configure_layout);
TextView txt = new TextView(this);
txt.setText("Must have: " + Integer.toString(checkBoxLimit) + " checkboxes");
ll.addView(txt);
// Create the checkboxes
currencies.addAll(Arrays.asList(getResources().getStringArray(R.array.currency_array)));
for(String item:currencies){
CheckBox ch = new CheckBox(this);
ch.setText(item);
ll.addView(ch);
ch.setOnCheckedChangeListener((cb, isChecked)->{
//If it's checked and more than the allowed limit, don't consider it
if(isChecked){
if(checkCounter>=checkBoxLimit){
cb.setChecked(false);
Toast.makeText(this, txt.getText(), Toast.LENGTH_SHORT).show();
}
// If it's within the allowed limit, add to list of chosenCurrencies.
else{
checkCounter+=1;
chosenCurrencies.add(cb.getText().toString());
}
}
// If its, unchecked remove the currency from the list of chosenCurrencies.
else{
checkCounter-=1;
chosenCurrencies.remove(cb.getText().toString());
}
});
}
// Create the button
Button btn = new Button(this);
btn.setText(R.string.apply);
ll.addView(btn);
// Finish this
//Launch the widget once the button is pressed
btn.setOnClickListener(v->{
//If User selects right amount of checkboxes
if(checkBoxLimit == checkCounter){
final Context context = AppWidgetConfigure.this;
// delete the previous currencies that existed there for that widget Id
deleteCurrencyPref(context, mAppWidgetId);
// Save the preferences
saveCurrencyPref(context, mAppWidgetId, chosenCurrencies);
// It is the responsibility of the configuration activity to update the app widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] oneIdList = new int[1];
oneIdList[0] = mAppWidgetId;
//Update the current type of widget
widget.onUpdate(context, appWidgetManager, oneIdList);
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
else{
Toast.makeText(this, txt.getText(), Toast.LENGTH_SHORT).show();
}
});
}
// Set the currencies for each object
for (String currency : preferredCurrencies) {
if (currencyCount >= currencyObjects.size()) {
return
}
currencyObjects.get(currencyCount).setCurrencyType(currency);
currencyCount++;
}
your app crash because you want to get a invalid item of list. ex your list have 2 items but you call list.get(2)
I made an Android app that has a lot of pdf serially in a listview. Now I want to give a feature to the user that the user can view his/her last viewed PDF with a Floating Action Button. This FAB will open the PDF that was opened/studied at last by the user. But how can I do that? Thanks in Advance. Any help Appreciated.
Now I will add my code here -
public static final String mypreference = "mypref";
public static final String PDF = "pdfKey";
String a = "One";
String b = "Two";
String c = "Three";
String d = "Four";
String e = "Five";
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(PDF)) {
}
if (list.isItemChecked(0)){
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(PDF)) {
Intent intent = new Intent(getApplicationContext(), c2017p1.class);
startActivity(intent);
}
}
else if (list.isItemChecked(1)){
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(b)) {
Intent intent = new Intent(getApplicationContext(), c2017p2.class);
startActivity(intent);
}
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(getApplicationContext(), c2017p1.class);
startActivity(intent);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(PDF, a);
editor.commit();
SharedPreferences preferences = getSharedPreferences(PDF, 0);
preferences.edit().remove(b).apply();
SharedPreferences preferences1 = getSharedPreferences(PDF, 0);
preferences1.edit().remove(c).apply();
SharedPreferences preferences2 = getSharedPreferences(PDF, 0);
preferences2.edit().remove(d).apply();
SharedPreferences preferences3 = getSharedPreferences(PDF, 0);
preferences3.edit().remove(e).apply();
}
if (position == 1) {
Intent intent = new Intent(getApplicationContext(), c2017p2.class);
startActivity(intent);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(PDF, b);
editor.commit();
SharedPreferences preferences = getSharedPreferences(PDF, 0);
preferences.edit().remove(a).apply();
SharedPreferences preferences1 = getSharedPreferences(PDF, 0);
preferences1.edit().remove(c).apply();
SharedPreferences preferences2 = getSharedPreferences(PDF, 0);
preferences2.edit().remove(d).apply();
SharedPreferences preferences3 = getSharedPreferences(PDF, 0);
preferences3.edit().remove(e).apply();
}
Now I found out that to listen that if a item is clicked, we have to use list.isItemChecked(position). But I still can not decide how to open this last viewed PDF from this? I want to store the Index of Shared Preferences of the last Viewed PDF and delete other one indexs. Then after clicking on the Floating Action Button, it will detect the Index of Last Viewed PDF as it will store only Last ones, and open the last one. Please Help me guys.
you can save the source to the shared preferences so that every time a new pdf is opened its source is to be saved in the shared preferences............
I hope this helps
I'm very new to coding in android, so I barely know any of the syntaxes. I am defining a variable in MainActivity.java and assigning it a random 4 digit value. I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. Help me out if any of you know a fix for this. The following is my current code
Random r = new Random();
int i1 = r.nextInt(9999 - 1) + 1;
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString("key for value", somrRandonNumber);
editor.putBoolean("is first lunch", false);
editor.commit();
Then retrive it with
int number = sharedPref.getInt("key for value";
Sometimes you need to specify a default value like:
SharedPref.getBoolean("is first lunch",true);
Good luck
Use SharedPreference for saving value use this code
int i1=0;
if (getIntValue() == 0) {
Random r = new Random();
i1 = r.nextInt(9999 - 1) + 1;
saveIntValue(i1);
} else {
i1 = getIntValue();
}
here are two method
public void saveIntValue(int myIntValue) {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", myIntValue);
editor.commit();
}
public int getIntValue() {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", 0);
if (myIntValue == 0) {
return 0;
} else {
return myIntValue;
}
}
Store in Preference if value is 0 else get stored value
Random r = new Random();
int value= r.nextInt(9999 - 1) + 1;
if(getValue()==0)
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putInt("uniqueInt", value).apply();
else {
int uniqueIntFromPref = getValue();
}
Retrieve from Preference
private int getValue() {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString("uniqueInt", 0);
}
Just copy and paste above code
Am just wondering if there is a way to save data into a text file without being overwritten.
Currently i am using sharedpreferences and it overwrites the data which is okay but coinciding with this, i want somewhere where i can keep record of the value before being overwritten in a list or column form.
So it goes something like this:
60, 65, 70..etc
The values are stored one after another without being overwritten. I am thinking of doing this locally in a text file which can be read as well.
I am doing this so i can create a stats page or something like that.
I hope someone can help me find a solution.
My code:
public class workout extends Activity {
TextView weightresultText, newweightresultText, difficultyrating;
Boolean male, strength;
double newweight, newweight1;
int weight, age;
Button button, button4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
button = (Button) findViewById(R.id.button);
button4 = (Button) findViewById(R.id.button4);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
weight = Integer.parseInt(sharedPreferences.getString("storedweight", "Your Weight"));
age = Integer.parseInt(sharedPreferences.getString("storedage", "Your Age"));
male = sharedPreferences.getBoolean("is_male", false);
strength = sharedPreferences.getBoolean("is_strength", false);
weightresultText = (TextView) findViewById(R.id.weightresultLabel);
newweightresultText = (TextView) findViewById(R.id.newweightresultLabel);
difficultyrating = (TextView) findViewById(R.id.difficultylevel);
if (sharedPreferences.getBoolean("firstrun", true)) {AgeCalculation();
sharedPreferences.edit().putBoolean("firstrun", false).commit();}
AfterFirstLaunch();
}
public void SaveWeight(){
savePreferences("storednewweight", (Double.toString(newweight)));
}
//Should only happen on first launch.
public void AgeCalculation() {
if (strength == true){
if (male == true && age >= 18) {
newweight = (weight * 0.8);
}
if (male == true && age >= 30) {
newweight = (weight * 0.6);
}
if (male == true && age >= 50) {
newweight = (weight * 0.4);
}
if (male == true && age >= 70) {
newweight = (weight * 0.2);
}
if (male == true && age > 80) {
newweight = (weight * 0.1);
}
if (male == false && age >= 20 ){
newweight = (weight * 0.3 );
}
weightresultText.setText(Double.toString(newweight));
SaveWeight();
}}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
// On every other launch, it is based on button, the newweight is saved and loaded each time.
public void buttonClick1(){
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 5;
//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight1)));
//save to shared preference, and load value on new launch?
//also store into local database for review later.
difficultyrating.setText("1");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
public void buttonClick4(){
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 10;
//saves value into sharedpreference
//save to text file in array
savePreferences("storednewweight", (Double.toString(newweight1)));
difficultyrating.setText("2");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
//runs on every other launch
public void AfterFirstLaunch(){
buttonClick1();
buttonClick4();
//receive value on other launches and show on field.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
weightresultText.setText(newweight);
}
}
For something like this, where you're storing multiple entries of similar data, you'd really want to use an SQL database with a content provider. You'd just create new rows for each entry.
For writing into a textFile with overwritten use the following code
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
File logFile = new File(path + "filename.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append("Message");
buf.newLine();
buf.flush();
buf.close();
Make sure you have permission defined in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have a listview with choice mode, and it working. I want to save that checked item to shared preference, then use it in another activity. But, my SharedPreferences doesn'nt save my string correct, and save another file call DATA_Preferences that i never call in my code.
The result is my Next activity get wrong value..
Here is my code that i use to save my string and call it use by another activity:
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<DBLokasi> selectedItems = new ArrayList<DBLokasi>();
// Item position in adapter
SharedPreferences prefs = getSharedPreferences("DATA_COOR", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
// Add slected if truee
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
prefsEditor.putFloat(POINT_LATITUDE_KEY + i, Float.parseFloat(values.get(position).getLat()));
prefsEditor.putFloat(POINT_LONGITUDE_KEY + i, Float.parseFloat(values.get(position).getLng()));
}
prefsEditor.commit();
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = String.valueOf(selectedItems.get(i));
}
Bundle b = new Bundle();
Location location = new Location("POINT_LOCATION");
for (int i = 0; i < checked.size(); i++) {
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + i, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + i, 0));
double latitude = prefs.getFloat(POINT_LATITUDE_KEY + i, 0);
double longitude = prefs.getFloat(POINT_LONGITUDE_KEY + i, 0);
prefsEditor.commit();
b.putDouble("Latitude" + i, latitude );
b.putDouble("Longitude" + i, longitude);
}
int banyakPilih = checked.size();
b.putInt("banyakPilih", banyakPilih);
Intent intent = new Intent(getApplicationContext(),
HasilPilihanActivity.class);
// Create a bundle object
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
I save my Prefernces in DATA_COOR.xml file name, it save my string, but i got another file that save my preference with file name DATA_Preferences in my Explorer. Some body can give me solution? Thanks before..
Define private SharedPreferences mediaPrefs = null;
put this on your constructor mediaPrefs = this.getSharedPreferences("Testing", 1);
put below method to the source:
public void storeStateString(String prefsKeys, Float prefsValue) {
SharedPreferences.Editor prefEditor = mediaPrefs.edit();
prefEditor.putFloat(prefsKeys, prefsValue);
prefEditor.commit();
}
Use this method to store the state like:
storeStateString("POINT_LATITUDE_KEY"+i,Float.parseFloat(values.get(position).getLat()));
and now you can get this preference through:
Float finalValue = mediaPrefs.getFloat("POINT_LATITUDE_KEY1","2.0l");
where 2.0l is defalut value if mediaPrefs is null;
Let me know if any issues regarding that.