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(...)
...
}
}
Related
I am trying to save the data received by the fragment into a shared preference so that I can reuse the data stored in shared preference when the same fragment is recreated. But somehow the data is not getting saved and the default value of preference is returned to my fragment.
Below is the code.
Fragment implementing SharePreference
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
SharedPreferences playerSettings;
public StreamFragment(){};
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
SharedPreferences playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString(streamUrl,"No Link Found");
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString("streamLink","No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
public void getUrl(String data)
{
streamUrl=data;
playerSettings = this.getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString("streamLink", streamUrl);
editor.commit();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
Thanks in advance!
Instead of streamUrl = playerSettings.getString(streamUrl,"No Link Found");
You should use
streamUrl = playerSettings.getString("streamLink","No Link Found");
And also use apply instead of commit
I try to explain the point here:
Refer to this image:
As you can see, the onCreate is fired before the onCreateview.
Lets analyze your code:
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
SharedPreferences playerSettings;
public StreamFragment(){};
Here, your streamUrl is null.
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
/*SharedPreferences -- no needed*/playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString(/*streamUrl -- replace with a key value*/,"No Link Found");
}
That's the first method fired. here you are trying to get a String from sharedPref which should be named null. This point is wrong. the first parameter on getString should be a key, and should be unique everywhere for the same value.
Another thing is that you are istantiating another istance of SharedPreferences with the same name, so remove the cast in the istantiation.
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
//playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE); -- they are already istantiated
streamUrl = playerSettings.getString(/*streamUrl -- replace with a key value*/,"No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
Now you are setting streamUrl to the sharedPreferences's value named with the same variable streamUrl.this means:
streamUrl /*which is currently null*/ = playerSettings.getString(null, "No Link Found");
You should still replace the key from streamUrl to a static unique field.
public void getUrl(String data)
{
streamUrl=data;
//playerSettings = this.getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE); -- already done above
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString("streamLink", streamUrl);
//editor.commit(); --replace with apply
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
This should be the point where you save the value, so the "streamLink" should be the key used above.
Replace commit with apply and remove the istantiation because it's already done
Now.. said that this is how it should look like:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
public static final String valueKey="streamLink";
SharedPreferences playerSettings;
public StreamFragment(){};
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString(valueKey,"No Link Found");
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
streamUrl = playerSettings.getString(valueKey,"No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
public void getUrl(String data)
{
streamUrl=data;
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString(valueKey, streamUrl);
editor.apply();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
Hope this can help you.
Your key to the preference value is not correct. Note the below line.
streamUrl = playerSettings.getString(streamUrl,"No Link Found");
Use some constant value as key.
private static final String STREAM_URL = "stream_url";
and the use the constant as key as mentioned below.
streamUrl = playerSettings.getString(STREAM_URL,"No Link Found");
Your getUrl(String) method not called. So your Shared preference value not stored, called it before playerSettings.getString(streamUrl,"No Link Found");
Also you create instance of "SharedPreferences" two times, remove from onCreateView.Use editor.apply() instead of editor.commit().
you are using two SharedPreferences playerSettings; one globally and one in onCreate and you are using upper one which is not initialized
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class StreamFragment extends Fragment {
public String streamUrl=null;
TextView textView;
public static final String playerData="pData";
SharedPreferences playerSettings;
public StreamFragment(){};
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString("streamLink","No Link Found");
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
playerSettings = getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
streamUrl = playerSettings.getString("streamLink","No Link Found");
//getData();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
return view;
}
public void getUrl(String data)
{
streamUrl=data;
playerSettings = this.getActivity().getSharedPreferences(playerData, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = playerSettings.edit();
editor.putString("streamLink", streamUrl);
editor.commit();
Toast.makeText(getActivity(),"Stream Saved"+streamUrl,Toast.LENGTH_LONG).show();
}
}
i want to create ids for three buttons so that i can use them in a switch case i want the ids to be unique in each loop like btna[1].setid("btna"+1),btnb[1].setid("btnb"+1),btnc[3].setid("btnc"+3) somethimg like that and i want to repet this for n number of times
here is my code:
package com.astro.famouspandit.Activities.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.astro.famouspandit.Database.DatabaseHelper;
import com.astro.famouspandit.R;
import com.astro.famouspandit.datasets.ItemProfile;
import java.util.ArrayList;
import mehdi.sakout.fancybuttons.FancyButton;
public class ProfleList extends AppCompatActivity implements View.OnClickListener{
private TextView txtProfileName,txtProfileDate,txtProfileTime,txtProfileLocation;
private FancyButton btnEdit[],btnDelete[],btnView[];
LinearLayout linearlist ;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profle_list);
mydb = new DatabaseHelper(this);
long count = mydb.getCount();
Log.d("count", "onCreate: "+count);
if (count == 0){
}else{
ArrayList<ItemProfile> listprofile = mydb.profilelist();
for (int i = 1; i < count+1; i++ ) {
ItemProfile itemProfile = listprofile.get(i-1);
linearlist = (LinearLayout)findViewById(R.id.layoutlist);
View[] myView = new View[i];
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView[i-1] = inflater.inflate(R.layout.profile_list, null);
txtProfileName = (TextView)myView[i-1].findViewById(R.id.txtName);
txtProfileDate = (TextView)myView[i-1].findViewById(R.id.txtDate);
txtProfileTime = (TextView)myView[i-1].findViewById(R.id.txtTime);
txtProfileLocation = (TextView)myView[i-1].findViewById(R.id.txtLocation);
btnEdit[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_edtProfile);
btnDelete[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_deleteProfile);
btnView[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_viewProfile);
btnEdit[i].setOnClickListener(this);
btnDelete[i].setOnClickListener(this);
btnDelete[i].setOnClickListener(this);
String profileName = itemProfile.getProfileName();
txtProfileName.setText(profileName);
Log.d("ProfileName", "onCreate: "+itemProfile.getProfileName());
int dd = itemProfile.getDay();
int mm = itemProfile.getMonth();
int yy = itemProfile.getYear();
txtProfileDate.setText(dd+"/"+mm+"/"+yy);
Log.d("Profiledate", "onCreate: "+itemProfile.getDay()+itemProfile.getMonth()+itemProfile.getYear());
int hour = itemProfile.getHour();
int min = itemProfile.getMinute();
txtProfileTime.setText(hour+":"+min);
Log.d("ProfileTime", "onCreate: "+itemProfile.getHour()+itemProfile.getHour());
String city = itemProfile.getCity();
txtProfileLocation.setText(itemProfile.getCity());
Log.d("citylocation,city", "onCreate: "+itemProfile.getCity()+","+city);
linearlist.addView(myView[i-1]);
}
}
}
#Override
public void onClick(View v) {
}
}
I recommend using View.setTag(), where you can set an object to a View.
View also has a method called findViewWithTag(Object tag) where it searches between the child views for the given tag (using Object.equals()).
So to adapt it to your case:
btna[1].setTag("btna" + 1);
btnb[1].setTag("btnb" + 1);
btnc[3].setTag("btnc" + 3);
You can easily make a for loop from this.
And then later:
Button btnc = (Button)container.findViewWithTag("btnc3");
Just make sure that the buttons are direct children of the ViewGroup named container.
To handle click events, modify your onClick() this way:
#Override
public void onClick(View v) {
String tag = v.getTag();
if (tag.equals("btna1")) {
Log.i("Test", "Clicked on button A 1");
} else if (tag.equals("btnb1")) {
Log.i("Test", "Clicked on button B 1");
}
}
And so on...
You can use switch-case with Strings only in Java 7, which is available from ADT 22.6.
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);
}
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();
}
I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));