SharedPreferences Click Checkbox And Hiding Button - android

I have two activities, ActivityA and ActivityB. ActivityA has a Checkbox, ActivityB has a Button. When I click the Checkbox in ActivityA, I want the Button in ActivityB to be invisible. I want it to be visible when I lift the tick. And most importantly I want to save it with SharedPreferences. So I want to exit the program and re-enter the last process I do. Could someone please help me? Thanks in advance.

activity_a.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<CheckBox
android:id="#+id/chk"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FF5722"
android:textStyle="bold"
android:textSize="18sp"
android:layout_margin="25dp"
android:text="Show Button"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:background="#000"
android:textSize="14sp"
android:textColor="#fff"
android:textAllCaps="false"
android:text="Next Screen"/>
</LinearLayout>
In Activity A :you can acheive using sharedpreference.
Step 1 : put below code in your A activity and yes btn is used for checking next screen button is hidden or not
SharedPreferences sharedPreferences = getSharedPreferences("ButtonPrefs", MODE_PRIVATE);
#SuppressLint("CommitPrefEdits") final SharedPreferences.Editor editor=sharedPreferences.edit();
chk=findViewById(R.id.chk);
btn=findViewById(R.id.btn);
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(isChecked)
{
editor.putBoolean("isShow",false);
editor.apply();
}
else
{
editor.putBoolean("isShow",true);
editor.apply();
}
}
});
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
activity_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity"
android:orientation="vertical">
<android.support.v7.widget.AppCompatButton
android:layout_margin="50dp"
android:id="#+id/btnshoworhide"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:background="#000"
android:visibility="gone"
android:textSize="14sp"
android:textColor="#fff"
android:textAllCaps="false"
android:text="show me or not"/>
</LinearLayout>
Step 1 : put below code in your B activity
boolean showornot;
btnshoworhide=findViewById(R.id.btnshoworhide);
SharedPreferences sharedPreferences = getSharedPreferences("ButtonPrefs", MODE_PRIVATE);
showornot=sharedPreferences.getBoolean("isShow",false);
if(!showornot)
{
btnshoworhide.setVisibility(View.GONE);
}
else
{
btnshoworhide.setVisibility(View.VISIBLE);
}
Its Easy && Nice
I run this code successfully ;)

You can pass data from activity A to B by Intent,
Intent intent = new Intent(ctx, B.class);
intent.putExtra("checkbox_result", "true");
startActivity(intent);
And get data in B Activity and save this string in shared preference:
String check= getIntent().getStringExtra("checkbox_result");

You can use a common sharedPreference which is accessible allover your application. put data on it from activity A and read it from activity B.
get instance of it from both activity like this.
SharedPreference sp = PreferenceManager.getDefaultSharedPreference(context);
saved data on it,
SharedPreference.Editor editor = sp.getEditor();
editor.putBoolean(MY_BOL, checkboxValue).apply();
read saved value from same preference you used to save to, get an instance of it the same way you did while saving as shown above,
get value, do this in onCreate() method of activity N.
boolean bol = sharedPreference. getBoolean(MY_BOL, false);
button.setVisibility(bol);

Related

Android Studio - Save TextView value for different users

My application has an authentication service made in .net and SSMS(SQL Server)
In one of my activities, I want to store a TextView value (that is incrementing due to the user using the application) so that each user has his own value. For example, user 1 uses the application 1h and closes the application. If user 2 logins in the app, the value should be different. When user 1 logins again, the value should be the last one before he closes the app.
Which method should I use in this case? Should I use SharedPreferences?
EDIT 08/09/2020
UserPoints.java
public class UserPoints extends AppCompatActivity{
private TextView userMoneyTV;
private BroadcastReceiver minuteUpdateReceiver;
private int userMoney = 0;
private Button saveMoney, loadMoney;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_points);
userMoneyTV = (TextView) findViewById(R.id.userMoney);
final String UserMoney = userMoneyTV.getText().toString();
saveMoney = (Button) findViewById(R.id.saveMoney);
saveMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preferences = getSharedPreferences("MYPREFS",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("money", UserMoney);
editor.putString("email", String.valueOf(R.id.email));
editor.commit();
}
});
loadMoney = (Button) findViewById(R.id.loadMoney);
loadMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preferences = getSharedPreferences("MYPREFS",MODE_PRIVATE);
String money = preferences.getString("money",UserMoney);
String email = preferences.getString("email",String.valueOf(R.id.email));
userMoneyTV.setText(money);
}
});
}
public void startMinuteUpdateReceiver(){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
minuteUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
userMoney++;
userMoneyTV.setText(""+ userMoney);
}
};
registerReceiver(minuteUpdateReceiver,intentFilter);
}
#Override
protected void onResume() {
super.onResume();
startMinuteUpdateReceiver();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(minuteUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
activity_user_points.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/rewardLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rewardInfoLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<ImageView
android:id="#+id/chestReward"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_marginTop="120dp"
android:src="#drawable/chestreward"
android:layout_alignParentLeft="true">
</ImageView>
<TextView
android:id="#+id/rewardText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginBottom="68dp"
android:layout_toRightOf="#+id/chestReward"
android:text="Earn money every minute you use the app"
android:layout_marginTop="175dp">
</TextView>
</RelativeLayout>
<RelativeLayout
android:id="#+id/moneyInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/rewardInfoLayout">
<TextView
android:id="#+id/userMoneyText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:fontFamily="casual"
android:text="Your Money: "></TextView>
<TextView
android:id="#+id/userMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_toRightOf="#+id/userMoneyText"
android:layout_marginTop="20dp">
</TextView>
<TextView
android:id="#+id/euro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="€"
android:layout_toRightOf="#+id/userMoney"
android:layout_marginTop="20dp"
android:layout_marginLeft="5dp">
</TextView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/moneyInfo">
<Button
android:id="#+id/saveMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Money"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:onClick="startVideoAd">
</Button>
<Button
android:id="#+id/loadMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Money"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/saveMoney">
</Button>
</RelativeLayout>
</RelativeLayout>
EDIT 9/9/2020
My problem was solved with EDIT 8/9/2020
Now my question is, how can i make the value increasing when i'm in another activity? AsyncTask?
Yes, you can use the SharedPreferences but if the user uninstalls the application user will lose its data and the value you've stored in SharedPreferences.
And if you want to save data even after uninstalling the app you can use any lightweight database i.e. Realm,Room,SQLite,Firebase and store your local database in users sd card. Else use Google backup service or store it in another place like on your server.

save the URLs entered by the user in Android using Shared Preferences

So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my Interface:
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
So I am stuck in the save and list. I am using shared preferences, but I am not able to save and list the URLS. This is the code I wrote:
public class MainActivity extends AppCompatActivity {
public static final String MY_EMP_PREFS = "MyPrefs";
private EditText url;
private Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("save", url.getText().toString());
// Commit the changes
edit.commit();
Toast.makeText(getApplicationContext(), "URL Saved", Toast.LENGTH_SHORT).show();
}
Where am I going wrong? What should I do?
Thanks
You have to add the method reference in your Widget:
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:onClick="save" //HERE
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Also, when you use a SharedPreferences, you are putting a String value using the key "save". So when you click on save button, you are overriding the old value and put a new value in the place.
To solve this issue, I think the best solution is use a Framework to persist the data and list it after.
edit.putString("save", url.getText().toString()); //here you are overriding the vlaue

OnClickListener on non-Mainactivity & change first activity

i've a problem. I want to make a app with a loggin activity and a main activity. (To the OnClickListiner later)
fist:
What ive done so far:
i've created a login. java and login.xml
login.java:
public class Login extends Activity implements OnClickListener {
Button btnStartAnotherActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
boolean hasLogedIn = true;
if (hasLogedIn) {
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
}
}
public void onClick(View view) {
//calling an activity using <intent-filter> action name
Intent inent = new Intent("android.name.MainActivity ");
startActivity(inent);
}
}
i've created a MainActivity.java and activity_main.xml
moreover i've some other java and xml files to make a materiel designed Tab view for my MainActivity.
i have 3 tabs thats how it looks so far
[![tab1 with buttons][1]][1]
-now i'be added to the first tab 3 buttons.
example of one button: (the others are the same just a other id )
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kommt"
android:clickable="false"
android:textColor="#190707"
android:id="#+id/kommt"
android:layout_alignParentStart="true"
android:layout_below="#+id/space" />
-So the app is running now without problems. ( All Tabs and there content is showing like i want it )
when i build the project the mainactivity is open first( see that link of the picture )
HOW TO SET: the login interface to be started once, when starting the app for the first time. After login is succesfully, then the mainactivity will always open. Thats my first problem. What should i add to the Login.java ? and how to set that the login.xml starts before the mainactivity ?
Second:
As i told you ive added some buttons. To test the buttons i've tried to implement a code for toast notification when clicking on button. But every time i build the project with the toast notifitcation code, the app doenst start anymore. Here the code for the toast notification i'm using:
public class MainActivity extends ActionBarActivity implements OnClickListener {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // but my main_activity doesnt have buttons ... tab1.xml have b
Button kommtbutton;
kommtbutton= (Button) findViewById(R.id.kommt);
kommtbutton.setOnClickListener(this);}
#Override
public void onClick(View v) {
setContentView(R.layout.tab1); // not sure if this is right ive did it cause the buttons are in the tab1 layout and not main_activity
switch(v.getId())
{
case R.id.kommt:
{
Toast toast1 = Toast.makeText(getApplicationContext(),
"Eingestempelt",
Toast.LENGTH_SHORT);
toast1.show();
break;
} ....}
here i have implemented all 3 buttons in a switch case.
It looks right but the onclicklistinier seems to kill my application before it can start. Maybe someone can help me.
i have following files:
Login.java, MainActivity.java, Tab1.java,Tab2.java,Tab3.java, SlidingTabsLayout.java, SlidingTabStrip.java and ViewPagerAdaper.
and i have this layouts.
acitivy_main.xml, login.xml, tab1,tab2,tab3.xml, toolbar.xml.
I'm not allowed to send pictures cause i'm new here.
Where have i do implement the code for the toast notification ?
thats my activity_main:xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<android_package.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"/>
and this is my tab1.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Tabs"
android:background="#FDFDFE"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/buchungen"
android:textColor="#190707"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Geht"
android:clickable="false"
android:textColor="#190707"
android:id="#+id/geht"
android:layout_alignParentBottom="true"
android:layout_alignEnd="#+id/textClock"
android:layout_marginBottom="36dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name:"
android:paddingBottom="7dp"
android:paddingTop="7dp"
android:textColor="#190707"
android:id="#+id/name"
android:layout_alignParentStart="true"
android:layout_below="#+id/buchungen" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#190707"
android:paddingBottom="7dp"
android:paddingTop="7dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Status:"
android:id="#+id/status"
android:layout_below="#+id/name"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#190707"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Letzte Buchung:"
android:paddingBottom="4dp"
android:paddingTop="7dp"
android:id="#+id/letzteBuchung"
android:layout_below="#+id/status"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_alignBottom="#+id/buchungen"
android:weightSum="1"
android:id="#+id/linearLayout">
<ImageView
android:layout_width="314dp"
android:layout_height="310dp"
android:id="#+id/profilbild"
android:layout_gravity="center_horizontal"
android:src="#drawable/time" />
</LinearLayout>
<Space
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_above="#+id/geht"
android:id="#+id/space" />
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#190707"
android:id="#+id/textClock"
android:layout_alignTop="#+id/name"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kommt"
android:clickable="false"
android:textColor="#190707"
android:id="#+id/kommt"
android:layout_alignParentStart="true"
android:layout_below="#+id/space" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Pause An/Aus"
android:textColor="#190707"
android:id="#+id/textView"
android:layout_alignTop="#+id/textView3"
android:layout_alignStart="#+id/pause" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Einstempeln"
android:textColor="#190707"
android:id="#+id/textView2"
android:layout_above="#+id/kommt"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Ausstempeln"
android:textColor="#190707"
android:id="#+id/textView3"
android:layout_alignBottom="#+id/geht"
android:layout_alignStart="#+id/geht"
android:layout_alignTop="#+id/textView2" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause"
android:textColor="#190707"
android:id="#+id/pause"
android:layout_alignBottom="#+id/kommt"
android:layout_centerHorizontal="true"
android:checked="false" />
</RelativeLayout>
The buttons are in the tab1.xml. Where have i to acces them to make a Interaction ( show toast when pressing the button ) ? in the MainActivity.java or the Tab1.java or somewhere else ?
When i try to add toast notification my app just kills itself ...
You have to put all the findViewById and setContentView in the onCreate method or they won't do the job.
First point :
public class MainActivity extends ActionBarActivity
{
// Layout elements
private Button kommtbutton = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Attach layout
setContentView(R.layout.activity_main); // but my main_activity doesnt have buttons ... tab1.xml have b
// Retrieve layout elements
kommtbutton= (Button) findViewById(R.id.kommt);
// Attach listeners
kommtbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view)
{
// Do not use getApplicationContext(), this is an activity
Toast.makeText(MainActivity.this, "Eingestempelt", Toast.LENGTH_SHORT).show();
}
});
}
[...]
}
Second point :
public class LoginActivity extends Activity
{
// Layout elements
private EditText edit_login = null;
private EditText edit_password = null;
private Button btn_login = null;
// Class variables
private SharedPreferences prefs = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Check if the user is already logged in
prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
if (prefs.getBoolean("isLoggedIn", false))
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
// Attach layout
setContentView(R.layout.login);
// Retrieve layout elements
edit_login = (EditText) findViewById(R.id.edit_login);
edit_password = (EditText) findViewById(R.id.edit_password);
btn_login = (Button) findViewById(R.id.btn_login);
// Attach listeners
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view)
{
// Retrieve information
String login = edit_login.getText().toString();
String password = edit_password.getText().toString();
// Do job
boolean canConnect = true; // TODO
if (canConnect)
{
// Update prefs
prefs.edit().putBoolean("isLoggedIn", true).commit();
// Move to activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
// Update prefs
prefs.edit().putBoolean("isLoggedIn", false).commit();
// Display error message
Toast.makeText(LoginActivity.this, "Wrong crendentials", Toast.LENGTH_LONG).show();
}
}
});
}
}

How to keep a TextView's content when changing the Activity

I'm pretty new to Android Development and I've come across a problem with my TextView. I have an XML file that contains a ScrollView and a TextView:
<ScrollView
android:id="#+id/scroll1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:freezesText="true">
</TextView>
</ScrollView>
And I have included it in two different XML files
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<include
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/story_view"
layout="#layout/story_view" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/add_text">
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:text="#string/end_button"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:onClick="endButtonPressed">
</Button>
<Button android:text="#string/submit_button"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:onClick="textAdded">
</Button>
</LinearLayout>
and
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/story_view" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:text="#string/save"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:onClick="saveToDevice">
</Button>
<Button android:text="#string/facebook"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:onClick="saveToFacebook">
</Button>
</LinearLayout>
But when I go from the first XML file to the other (and changing the Activity in the process), the content of the TextView disappears. I have tried freezesText but that doesn't seem to work.
Ordinarily I would just pass the content in an intent but my text is in different colours and I want to maintain that.
I could pass a Bitmap image in an intent but I want to avoid that if possible.
Thanks.
You could use the Activity state to save some values like
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
That happen because when you come back to the first activity, the onCreate method is called, so your textView is a new textView.
Take a look to Activity Lifecycle, here is explained much better.
You can use sharedPreferences or a Singleton (a design pattern), where the class can be instantiate only one time:
public class MySingleton{
private static MySingleton INSTANCE = null;
private String textViewInformation;
private MySingleton() {
}
public static MySingleton getInstance(Context context) {
synchronized (MySingleton.class) {
if (INSTANCE == null) {
synchronized (MySingleton.class) {
if (INSTANCE == null)
INSTANCE = new MySingleton();
}
}
}
return INSTANCE;
}
public String getTextViewInformation(){
return textViewInformation;
}
public void setTextViewInformation(String textViewInfo){
textViewInformation = textViewInfo;
}
}
and then:
public void onDestroy() {
super.onDestroy();
MySingleton.getInstance(this).setTextViewInformation("textViewText");
}
public void onResume() {
super.onResume();
if(MySingleton.getInstance(this).getTextViewInformation() != null){
yourTextView.setText(MySingleton.getInstance(this).getTextViewInformation());
}else{
yourTextView.setText("new text");
}
Maybe this way it's longer than the shared preferences, but it's very useful.
Excuse my bad english!
I hope this help.
you can use the sharedpreferences for this purpose it allows you to store and retrieve data using key-value pairs. for satisfying your purpose you need to store your activity state in sharedpreferences.
particularly in your case
first you need to store the textview value in shared preferences when you destroy the activity
#Override
public void onDestroy() {
super.onDestroy();
TextView tvText = (TextView) findViewById(R.id.yourelement);
SharedPreferences.Editor prefEditor = getSharedPreferences("Preferences", Context.MODE_PRIVATE).edit();
prefEditor.putBoolean("text", tvText .getText().toString());
prefEditor.commit();
}
Then in onCreate you need to set the textview text from your shared preferences.
TextView tvText = (TextView) findViewById(R.id.yourelement);
SharedPreferences prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
if (prefs.contains("text")){
tvText .setText(prefs.getString("text", ""));
}

How to create a Settings Panel with RadioGroup and save changes

in my Android app there are two Activity (Main and Settings) with main.xml and settings.xml. I want to create a RadioGroup in Settings that works like a settings panel for users so they can select Backgroundcolor of Buttons. I'm trying to use onClick with each RadioButton and it work well but if I come back to main.xml che color is not saved. How can I create a settings panel for set BackgroundColor of Buttons in other activity and save it (or with a Save Button for users)?
Here, Settings' code:
public class Settings extends Main implements OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
final Button back;
back= (Button) findViewById(R.id.back);
RadioButton redbtn, blubtn, grebtn;
redbtn= (RadioButton) findViewById(R.id.redbtn);
blubtn= (RadioButton) findViewById(R.id.blubtn);
grebtn= (RadioButton) findViewById(R.id.grebtn);
redbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
back.setBackgroundColor(Color.RED);
add.setBackgroundColor(Color.RED);
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
}
}
settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/settings"
android:textSize="40sp" />
<TextView
android:id="#+id/ButtonSettingsView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/title_settings"
android:layout_marginTop="17dp"
android:text="#string/BtnSet"
android:textSize="30sp" />
<Button
android:id="#+id/back"
android:layout_width="70sp"
android:layout_height="70sp"
android:layout_alignBaseline="#+id/title_settings"
android:layout_alignBottom="#+id/title_settings"
android:layout_alignRight="#+id/ButtonSettingsView"
android:text="Back"/>
<RadioGroup
android:id="#+id/ButtonSettings"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/ButtonSettingsView"
android:layout_marginTop="14dp"
android:orientation="vertical" >
<RadioButton
android:id="#+id/redbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/red"/>
<RadioButton
android:id="#+id/blubtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/blue" />
<RadioButton
android:id="#+id/grebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/grey"/>
</RadioGroup>
</RelativeLayout>
Thanks
Of course it won't save it for other Activities because when you start another then that Activity will use whatever its default is in xml. You need to save the color somehow then reference it in your other Activities. One way to do this, if you want it to persist when the user leaves and reenters the app, is to use SharedPreferences. Then you can open up these prefs in your other Activites, value saved, and change background accordingly.
If you only want it to change the color for the time that the user is currently in the app then you could create a static class to store this variable and change the colors according to that value.

Categories

Resources