How to read/write preferences from a DialogFragment? - android

I want to read from a preferences file in a DialogFragment. If I do this:
prefs = getSharedPreferences("numberPicker.preferences", 0);
then I get a compile time error, because getSharedReference is a ContextWrapper method but DialogFragment isn't a ContextWrapper (I use android.support.v4.app.DialogFragment for backwards compatibility by the way).
If alternatively, as a 'workaround', I use a SharedPreferences object prefs created in a class InitSpel (which is a FragmentActivity and therefore IS a ContextWrapper) then I get no error (nor at compile time nor at runtime) however the values are not stored (next time I start the app the values baan1 and baan2 are still 0).
How to solve?
package mypackage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class VraagBanenDialogFragment extends DialogFragment {
private View v;
private EditText editText1;
private EditText editText2;
//private ArrayList<Baan> baanNummers;
private int[] oldBanen;
private int[] currentBanen;
private SharedPreferences prefs;
/* public VraagBanenDialogFragment(ArrayList<Baan> baanNummers) {
this.baanNummers = baanNummers;
}
*/
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Restore preferences
//prefs = InitSpel.prefs;
prefs = getSharedPreferences("numberPicker.preferences", 0);
int baan1 = prefs.getInt( "BAAN_01", 0 );
int baan2 = prefs.getInt( "BAAN_02", 0 );
//oldBanen = new int[InitSpel.aantalParallel];
oldBanen = new int[2];
oldBanen[0] = baan1;
oldBanen[1] = baan2;
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
v = inflater.inflate(R.layout.vraag_banen, null);
// velden vullen met opgeslagen waarden
editText1 = (EditText) v.findViewById(R.id.editText1);
editText2 = (EditText) v.findViewById(R.id.editText2);
editText1.setText(String.valueOf(baan1));
editText2.setText(String.valueOf(baan2));
//editText1.setText(String.valueOf(baanNummers.get(0).getBaanNummer()));
//editText2.setText(String.valueOf(baanNummers.get(1).getBaanNummer()));
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
int baan1 = Integer.valueOf(editText1.getText().toString());
int baan2 = Integer.valueOf(editText2.getText().toString());
InitSpel.setBaanNummer(0, baan1);
InitSpel.setBaanNummer(1, baan2);
// en banen nog bij de preferences op schijf opslaan...
// We need an Editor object (prefs.edit()) to make preference changes.
// All objects are from android.context.Context
prefs.edit().putInt("BAAN_01", baan1);
prefs.edit().putInt("BAAN_02", baan2);
// Commit the edits!
prefs.edit().commit();
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO cancel;
}
});
return builder.create();
}
}

Use getActivity() since Activity extends Context, and Context has a getSharedPreferences() method.
prefs = getActivity().getSharedPreferences("numberPicker.preferences", 0);
I'd also recommend keeping a reference to the Editor object to ensure proper saving.
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("BAAN_01", baan1);
editor.putInt("BAAN_02", baan2);
// Commit the edits!
editor.commit();
or chain:
prefs.edit()
.putInt("BAAN_01", baan1)
.putInt("BAAN_02", baan2)
.commit();

Related

Update fragment on all activities

I created a fragment which is basically a counter. When pressed, it updates the number of water glasses you've drunk. This data is stored in SharedPreferences. I also update this number once a day as well.
So i inserted fragment in xml of two activities: Main and the Timer.
It's perfectly work on the Main, when i start the TimerActivity it's also work, but when i go back to Main from Timer i see the last number i've reached in MainActivity, it's not updating and ignore my clicks from TimerActivity.
I think the trouble in "this.getActivity", but i don't know how to fix it. Thanks
Fragment code:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.example.fitapp.R;
import java.util.Calendar;
public class WaterBottleFragment extends Fragment {
LinearLayout waterBottle;
TextView iconName;
SharedPreferences sPref;
int counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_water_bottle, container, false);
// Update once a day
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
sPref = this.getActivity().getSharedPreferences("startApp", Context.MODE_PRIVATE);
int lastDay = sPref.getInt("day", 0);
if(lastDay != currentDay){
SharedPreferences.Editor ed = sPref.edit();
ed.putInt("day", currentDay);
ed.commit();
counter = 0;
} else {
counter = (int) loadText();
}
waterBottle = (LinearLayout) view.findViewById(R.id.ll_water_bottle);
iconName = (TextView) view.findViewById(R.id.tv_icon_water);
iconName.setText(counter + " glasses");
waterBottle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
iconName.setText(counter + " glasses");
saveText();
}
});
return view;
}
// Save number of glasses
private void saveText() {
sPref = this.getActivity().getSharedPreferences("water_counter", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putInt("num_of_glasses", counter);
ed.commit();
Toast.makeText(this.getActivity(), "updated", Toast.LENGTH_SHORT).show();
}
// Load number of glasses
private int loadText() {
sPref = this.getActivity().getSharedPreferences("water_counter", Context.MODE_PRIVATE);
int savedCounter = sPref.getInt("num_of_glasses", 2);
return savedCounter;
}
}
its not a big deal just create an interface like:
Public interface WaterBottleEventListener{
void onBottleClick();
}
create an object of your interface inside your fragment:
WaterBottleEventListener listener;
Then call it inside your waterBottle.setonclicklistener:
waterBottle.setonclicklistener(){
#override
onclick(View v){
listener.onbottleclick();
}
}
Then make both of your activities implement this interface and inside each implementation put your update glass code like this:
Activity1 implement waterBottleEventListener{
#override
onBottleclick(){
counter++;
IconName.setText(...)
...
}
}

getText() in EditText is not working

I am currently trying to get a string out of an EditText field.
Here is my Code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class FirstRunDialog extends DialogFragment {
public static final String DEBUG_TAG = FirstRunDialog.class.getSimpleName();
private static final String PREFS_NAME = "MyPrefsFile";
private LayoutInflater inflater;
private View dialogView;
private EditText input;
private DialogInterface.OnClickListener listener;
private SharedPreferences settings;
private SharedPreferences.Editor editor;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof DialogInterface.OnClickListener) {
listener = (DialogInterface.OnClickListener) activity;
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.app_name);
builder.setView(R.layout.first_run_dialog);
builder.setCancelable(false);
builder.setPositiveButton("Key-Testen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
dialogView = getActivity().getLayoutInflater().inflate(R.layout.first_run_dialog, null);
input = (EditText) dialogView.findViewById(R.id.editText);
editor = settings.edit();
editor.putString("apiKey", input.getText().toString());
editor.commit();
Log.d(DEBUG_TAG, "apiKey Input: " + input.getText().toString());
Log.d(DEBUG_TAG, "apiKey: " + settings.getString("apiKey", ""));
dialog.dismiss();
}
});
builder.setNegativeButton("Key-Erstellen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Open Browser, then go to: https://account.arena.net/applications
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://account.arena.net/applications"));
startActivity(browserIntent);
}
});
return builder.create();
}
}
This code is not working! According to the answers how to retrieve text from an EditText I did nothing wrong. The EditText is located in an AlertFragment.
The current output for the Log.d(...) is (and the same goes for the second):
apiKey Input:
Thx in advance.
Do not inflate a new view when the button is pressed.
Try using getDialog():
builder.setPositiveButton("Key-Testen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
input = (EditText) getDialog().findViewById(R.id.editText);
editor = settings.edit();
editor.putString("apiKey", input.getText().toString());
editor.commit();
Log.d(DEBUG_TAG, "apiKey Input: " + input.getText().toString());
Log.d(DEBUG_TAG, "apiKey: " + settings.getString("apiKey", ""));
dialog.dismiss();
}
});
try this
take out this line from the onclick
input = (EditText) dialogView.findViewById(R.id.editText);
and inflate the view
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
builder .setView(dialogView);
EditText input = (EditText) dialogView.findViewById(R.id.editText);
then input.gettext().tostring in the onclick, sorry for my english
and I hope to help

How to present different UI on first vs subsequent app use?

I have a simple android page with a spinner, two check boxes and a submit button. The java code for the screen is as follows:
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import org.json.JSONException;
import org.json.JSONObject;
public class Main extends AppCompatActivity implements View.OnClickListener{
private Button submit;
private Button edit;
Spinner place;
private CheckBox male;
private CheckBox female;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
submit = (Button) findViewById(R.id.btn_submit);
submit.setOnClickListener(this);
edit = (Button) findViewById(R.id.btn_edit);
edit.setVisibility(View.GONE);
place = (Spinner) findViewById(R.id.place);
place.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String item = adapter.getItemAtPosition(position).toString();
str_specimen = item;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
male = (CheckBox) findViewById(R.id.male);
male.setChecked(false);
female = (CheckBox) findViewById(R.id.female);
female.setChecked(false);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Main.this,
home.class);
startActivity(intent);
}
});
}
}
I have a edit button that is not visible initially. When I choose a value from spinner and check a value in the check box and click on submit button. These values are sent to database and home page will launch.
What I want to do is that, when I visit the main page again, I want the previously selected values to appear and the spinner and checkbox should not be clickable, and the edit button should show up. If i click on the edit button the spinner and checkbox should be clickable and i should be able to submit again.
Can someone tell me how to do this?
Have a method, say isFirstVisit(), that returns a boolean if this is the first time the user is on that activity:
private boolean isFirstVisit() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
return prefs.getBoolean("IsFirstVisit", true);
}
Call it before you start adjusting your UI and then based on its value show/hide/check/uncheck/enable/disable various UI elements:
boolean firstTime = isFirstVisit();
edit = (Button) findViewById(R.id.btn_edit);
if(firstTime) {
edit.setVisibility(View.GONE);
}
Don't forget to set IsFirstVisit to false when done:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("IsFirstVisit", false);
ed.commit();
Use SharedPreferences after click
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("place", place.getSelectedItem().toString(););
editor.putInt("male", male.getText());
editor.putInt("female", female.getText());
editor.commit();
Retrieve data from preference after setContentView(R.layout.main);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String place = prefs.getString("place" null);
String male = prefs.getString("male", null);
String female = prefs.getString("female", null);
}

How to create an Alert with don't show this again option in a centralized Alerts class

I have an Alerts class where I define all alert windows of my app with methods in this forms
public static void Alert1(Context con) {
AlertDialog.Builder builder = new AlertDialog.Builder(con);
builder.setTitle("my title");
builder.setIcon(android.R.drawable.ic_dialog_info);
DialogListner listner = new DialogListner();
builder.setMessage("my message");
builder.setPositiveButton("ok", listner);
AlertDialog diag = builder.create();
diag.show();
}
Now I want to create in a similar way also an Alert windows with a checkBox "Don't show this again" that if is selected avoid the view of this Alert
I have a clarity and right approach for this question
package com.example.user.testing;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
public class MainActivity extends AppCompatActivity {
CheckBox dontShowAgain;
public static final String PREFS_NAME = "MyPrefsFile1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
LayoutInflater adbInflater = LayoutInflater.from(MainActivity.this);
View eulaLayout = adbInflater.inflate(R.layout.checkbox, null);
dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.skip);
adb.setView(eulaLayout);
adb.setTitle("Attention");
adb.setMessage("Your message here");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("skipMessage", dontShowAgain.isChecked());
editor.commit();
dialog.cancel();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Boolean skipMessage = settings.getBoolean("skipMessage", false);
if (skipMessage.equals(false)) {
adb.show();
}
}
}
You can use the application SharedPreference object. Add an item in you shared preference, by trying to read it for the first time. The all you have to do is put a value to the object and just check it every time.
You can create a separate layout for your dialog with this checkbox and textview. Inflate this layout and add set it as view for your dialog
well it would be something like below.
View view = layoutInflator.inflate(R.layout.dialogView,null);
//and set to your dialog
dialog.setView(view);
//Or you can set it to your builder also
And handle onCheckListener for checkbox
As others suggested, you should create a custom layout with the desired message and controls (Checkbox), and use SharedPreferences to keep track of the user choice
Here are 2 blog posts that describes these topics.
Creating and Displaying a Custom Dialog in Android
Writing and Reading from SharedPreferences
(Disclaimer: my blog.)

how to set a text to a Edittext which is in a dialog box?

The question is as you can see that I cant set the value of edittext dynamically before showDialog().
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int DIALOG_TEXT_ENTRY = 7;
private int user_id;
private int dialogChoice;
private String mobileNum;
private EditText input2 ;
private EditText input1 ;
public TextView textView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert_dialog_text_entry);
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
mobileNum =tm.getLine1Number();
// input1.setText(mobileNum);
textView.setText("hello");
showDialog(DIALOG_TEXT_ENTRY);
}
#Override
protected Dialog onCreateDialog(int i) {
switch (i) {
case DIALOG_TEXT_ENTRY:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
input2 = (EditText) textEntryView.findViewById(R.id.number_edit);
input1 = (EditText) textEntryView.findViewById(R.id.username_edit);
textView = (TextView) textEntryView.findViewById(R.id.username_view);
return new AlertDialog.Builder(MainActivity.this)
// .setIconAttribute(android.R.attr.accountType)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent i = new Intent(MainActivity.this, IccActivity.class);
startActivity(i);
/* User clicked OK so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
}
return null;
}
}
textView.setText("hello"); this line kills the app.
thanks in advance.
you should put this line textView.setText("hello"); into onCreateDialog() method as you are setting the value before it gets initialized.
You haven't initialized textView. You need this in your onCreate() before you do the textView.setText()
textView = (TextView) textEntryView.findViewById(R.id.username_view);
I guess you are getting NullPointerException? You should first ser your 'textView' field.
Find the TexView text that is in the dialog and set the text of the TextView
Try this link

Categories

Resources