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.
Related
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
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();
}
}
});
}
}
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", ""));
}
I am trying to show text with a button click.
Here is my onClick code:
public class Uteliv extends Activity {
public void onCrate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uteliv);
TextView tidiTekst = (TextView) findViewById(R.id.tidiTekst);
tidiTekst.setVisibility(View.GONE);
Button tidiKnapp= (Button) findViewById(R.id.tidiKnapp);
tidiKnapp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tidiTekst.setVisibility(View.VISIBLE);
}
});
}
}
What is wrong? When I test it on my phone I only get a blank page.
Unless this was a typo in your post, your problem is you haven't declared the proper Activity method
public void onCrate(Bundle savedInstanceState) {
should be
public void onCreate(Bundle savedInstanceState) {
Also, you should probably make your Views member variables (declare them before onCreate() and initialize them inside of onCreate())
Edit
To show/hide your TextView you can use getVisibility to determine what to do. So it would be something like
public void onClick(View v) {
tidiTekst.setVisibility((tidiTekst.getVisibility() == View.Visible)
? View.GONE : View.VISIBLE);
}
activity_Main.xml
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:padding="10dip" >
<Button
android:id="#+id/mybtn"
style="?buttonBarButtonStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_weight="1"
android:background="#c4c5c7"
android:shadowColor="#959597"
android:shadowDx="0"
android:shadowDy="1"
android:shadowRadius="1"
android:text="Button"
android:textColor="#ffffff"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="#+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="hidden"
android:visibility="gone"/>
</LinearLayout>
code for MainActivity.java
private TextView mytxtvw;
private Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mytxtvw=(TextView)findViewById(R.id.myTextView);
myButton=(Button)findViewById(R.id.mybtn);
onBtnClick();
}
public void onBtnClick()
{
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mytxtvw.setVisibility((mytxtvw.getVisibility() == View.VISIBLE)
? View.GONE : View.VISIBLE);
}
});
}
}
Define your button and textView variables outside of the on-create method. Until you post the error you are getting, I'm going to assume that you are getting a null pointer because they are going out of scope once onCreate is finished.
TextView tidiTekst;
Button tidiKnapp;
public void onCrate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uteliv);
tidiTekst = (TextView) findViewById(R.id.tidiTekst);
tidiTekst.setVisibility(View.GONE);
tidiKnapp= (Button) findViewById(R.id.tidiKnapp);
tidiKnapp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tidiTekst.setVisibility(View.VISIBLE);
}
});
}
Is it working if you decalre your textView as final ?
final TextView tidiTekst = (TextView) findViewById(R.id.tidiTekst);
Please check your R.layout.activity_uteliv in a WYSIWYG IDE such as Eclipse or IntelliJ IDEA, edit it in graphic mode, it must be something wrong with the layout(xml).
In xml :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_marginTop="#dimen/_6sdp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="MORE"
android:textStyle="bold"
android:textColor="#color/darkgray"
android:textSize="#dimen/_10sdp"
android:gravity="left"
android:id="#+id/moreone"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/darkgray"
android:layout_marginTop="#dimen/_6sdp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_marginTop="#dimen/_9sdp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="16) I will not indulge in any way in any act that is against the spirit of law and society. "
android:textStyle="bold"
android:textColor="#color/darkgray"
android:textSize="#dimen/_10sdp"
android:gravity="left"
android:id="#+id/tandcone"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_marginTop="#dimen/_6sdp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="17) I will treat all with dignity irrespective and provide them with high level of service and remedies for their dissatisfaction any time during the course of my business as an Independent Associate."
android:textStyle="bold"
android:textColor="#color/darkgray"
android:textSize="#dimen/_10sdp"
android:gravity="left"
android:id="#+id/tandctwo"/>
</LinearLayout>
In MainActivity :
moreone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tandcone.setVisibility((tandcone.getVisibility() == View.VISIBLE)
? View.GONE : View.VISIBLE);
tandctwo.setVisibility((tandctwo.getVisibility() == View.VISIBLE)
? View.GONE : View.VISIBLE);
}
});
Hey guys im making an app using zxing integrater I have the scanner working propelry and show the results fine but would like the reslts to showon a separate class activity any ideas?
JavaActivity
public class QRGOLFActivity extends Activity {
TextView contents = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contents = (TextView) findViewById(R.id.contents);
}
public void doScan(View v) {
IntentIntegrator.initiateScan(this);
}
public void onActivityResult(int request, int result, Intent i) {
IntentResult scan = IntentIntegrator.parseActivityResult(request,
result, i);
if (scan != null) {
contents.setText(scan.getContents());
}
}
#Override
public void onSaveInstanceState(Bundle state) {
state.putString("contents", contents.getText().toString());
}
#Override
public void onRestoreInstanceState(Bundle state) {
contents.setText(state.getString("contents"));
}
}
and the Xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="doScan"
android:text="Scan!" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/contents"
android:layout_width="fill_parent"
android:layout_height="116dp"
android:textSize="20dp" />
</ScrollView>
<Button
android:id="#+id/score"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:text="Scorecard" />
<Button
android:id="#+id/about"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="About Us" />
<Button
android:id="#+id/contact"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Contact Us" />
Call startActivity() on "a separate class activity", passing whatever data you want (such as the ZXing results) via extras on the Intent you supply to startActivity(). Your "separate class activity" can then use getIntent() to retrieve the Intent and the various get...Extra() methods to retrieve those values.