Call same PreferenceActivity from different Views, different values - android

Let's say I have 10 buttons whose ID's are 1,2,...,10. I have an XML file called preferences.xml that contains a checkbox:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="applicationPreference" android:title="#string/config">
<CheckBoxPreference
android:key="checkbox" />
</PreferenceScreen>
My buttons all call the same function which calls for the intent to start the PreferenceActivity.
What I want to do is to call the same model with every button but save the values of the checkbox for each button. Currently, every time I click on a button, it launches the activity, but, for example, the value of my button 1 will be found in the value of my button 5.
Should I use SharedPreferences or something else?
I know it's possible but as I am still unfamiliar with many concepts, I just don't find it.

This is your problem: The PreferenceActivity automatically saves settings for you in the shared preferences of your application. For each setting, you define a key in your preferences.xml. In your case this is
android:key="checkbox"
so the value "checkbox" in your SP gets set to true, when you open your preferences with button 5. When you open the preferences with button 1 again, the PreferencesActivity looks up the SPs, sees that "checkbox" is true and therefore sets the checkbox to checked.
To avoid this issue, like Adrian said, you have to pass information to your PreferenceActivity about what button get clicked. In your PreferenceActivity you have to get a reference to your checkbox preference and add your passed button id to the key.
Preference checkboxPreference = findPreference("checkbox");
checkboxPreference.setKey(checkboxPreference.getKey() + buttonId);
Now there are 10 uniquely named boolean values ("checkbox1","checkbox2",..) saved in your SP for each of your buttons.
have fun

If I understood correctly, you have to tell the PreferenceActivity which button was press. You can achieve this by setting the button id as a parameter when starting the activity.
/*
* This is the common method used by all the buttons after the click
* was done in order to start the PreferenceActivity and pass
* the button id as a parameter
* #param sender - Button which was pressed and will start the
* PreferenceActivity
*/
private void startPreferenceActivity(Button sender)
{
// create the intent
Intent intent=new Intent(context, PreferenceActivity.class);
// add button id as a parameter
intent.putExtra("buttonID", sender.getId());
// start activity
startActivity(intent);
// or you can start it to way for a result
// startActivityForResult(intent, 0);
}
Now, in the PreferenceActivity you have to get the parameter which you have sent:
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the extras where the parametrs are stored
Bundle bundle = getIntent().getExtras();
if(bundle.getInt("buttonID") != null)
{
// get id as int with default value as 0
int id= intent.getInt("buttonID", 0);
}
if(bundle.getString("buttonID") != null)
{
// get id as string with default value as ""
string id= intent.getString("buttonID", "");
}
// other code here ...
}
Hope this will help you.

Related

How to setText to a TextView in a different Activity [duplicate]

This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 4 years ago.
So what I am trying to make happen is when you check this checkBoxA, some text will appear in a different TextView in a different Activity that the user will reach later on. The app is kind of like a quiz app so this off the text being displaid like the final score or something.
At first I tried this:
if (checkBoxA.isChecked()){
systemView.setText("Business");
}
But then I got a nullPointerException cause the "systemView" is not in the same activity. The activity is extended to the other activity that the "systemView" is located. So I am not really sure whats wrong anyone know what I should do?
Your issue is that even though you can get the ID of the systemView TextView by using R.id.systemView when you try to find that view using findViewById(R.id.systemView) the view cannot be found as it is not in the current activity's list of ViewGroup. As such null is returned.
Note systemView as the id given to the TextView has been assumed.
That is, You can only successfully use findViewById to find views within the current ViewGroup (e.g. for this.FindyViewById the layout as set by setContentView).
Instead you need to make the value available to the other activity and then retrieve the value in the other activity.
There are various ways that you can make the value available, some options are :-
To pass it to the activity via the Intent that starts the other activity as an intent extra, you could store the value in shared preferences and then retrieve it in the other activity or you could store the value in a database, e.g. SQLite and retrieve it.
Using an IntentExtra is ideal if you are directly starting the other activity with a limited number of values.
using chained Intent Extras is also feasible (that is passing to one activity, then to another and so on).
Shared preferences could suit a situation where there are a limited number of values to be passed and the other activity isn't directly started from the activity.
A database would suit a situation where there is a fair amount of structured data and/or related data (or if you are using a database for other aspects).
An example of using an Intent could be :-
In the Activity that is passing the value
Intent i = new Intent(this, yourOtherActivity.class);
i.putExtra("YOURINTENTEXTRAKEY","Business"); //<<<< 1st parameter is a Key for identification, the 2nd parameter is the value to be passed
startActivity(i);
In the other Activity's onCreate (after you've set the contentView)
TextView mSystemView = this.find(R.id.systemView);
if (this.getIntent().getStringExtra("YOURINTENTEXTRAKEY") != null) {
mSystemView.setText(this.getItent().getStringExtra("YOURINTENTEXTRAKEY"));
} else {
mSystemView.setText("NO VALUE PASSED");
}
You set pass and return multiple IntentExtras see Intent for various options and types of values that can be passed/retrieved.
Simple Working Example
The following is code for a working example. The first activity (MainActivity) has a CheckBox and a Button.
The Button can be clicked or longClicked. If the latter then nothing is passed to the second activity. If the former then depedning upon whether or not the CheckBox is ticked will either pass "Not Checked" or "Business".
The second activity, if passed a value (either "Not Checked" or "Business") will display the passed value, if nothing is passed then it will display "NOTHING PASSED". The button on the second activity will return to the first activity (alternately using the back button will return to the first activity).
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String INTENTKEY_CHECKBOXA = "checkboxa";
CheckBox checkBoxA;
Button nextActivity;
String valueToPass = "Not Checked";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBoxA = this.findViewById(R.id.checkBoxA);
checkBoxA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBoxA.isChecked()) {
valueToPass = "Business";
} else {
valueToPass = "Not Checked";
}
}
});
nextActivity = this.findViewById(R.id.nextActivity);
//Set onlick listener (pass value via intent)
nextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callNextActivity(true);
}
});
// Set onlongclick listener (doesn't pass value via intent)
nextActivity.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
callNextActivity(false);
return true;
}
});
}
private void callNextActivity(boolean passvalue) {
Intent i = new Intent(this,NextActivity.class);
if (passvalue) {
i.putExtra(INTENTKEY_CHECKBOXA, valueToPass);
}
startActivity(i);
}
}
activity_main.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="#+id/nextActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NEXT ACTIVITY"/>
<CheckBox
android:id="#+id/checkBoxA"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
NextActivity.java
public class NextActivity extends AppCompatActivity {
Button doneButton;
TextView systemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
systemView = this.findViewById(R.id.sysstemView);
doneButton = this.findViewById(R.id.done);
if (this.getIntent().getStringExtra(MainActivity.INTENTKEY_CHECKBOXA) != null) {
systemView.setText(this.getIntent().getStringExtra(MainActivity.INTENTKEY_CHECKBOXA));
} else {
systemView.setText("NOTHING PASSED");
}
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doneWithActivity();
}
});
}
// Return from this activity
private void doneWithActivity() {
this.finish();
}
}
activity_next.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NextActivity">
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DONE"/>
<TextView
android:id="#+id/sysstemView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
you can pass your text in the intents of navigations between the activities .. otherwise if you want to save your text to recover it later, even if you close and restart your application, you can save it in a shared preferences file, to retrieve it from this file when you want to display it later.. but you can not set a text to a textview of an activity that is not in foreground.
There are many ways to do this depending on your exact use case one may be better suited than the others.
You can wrap the data in a bundle and pass it to your other activity through an intent if you are opening a second activity
Or you could store the values (in shared prefs or sqlite) and then retrieve them in the next activity.
You could use RxJava to create a stream via a subject (bevahior subject most likely in this case) and write to the stream in the first activity, then subscribe on the stream in the next to get the values.
If you are using an intent to go to the next activity you could put the value in a string and pass the string as an extra to the intent. Take the value in the next activity and set the text view.
//First Activty
String valueToPass = "";
if (checkBoxA.isChecked()){
valueToPass = "Business";
}
startActivity(new Intent(CurrentActivity.this, NextActivity.class).putExtra("value", valueToPass));
//Second Activity
if(getIntent().getString("value") != null)){
systemView.setText(getIntent().getString("value"));
}
Just use SharedPreferences to save the TextView value and then when go to the Activity that contain the TextView get the saved value and set it to the TextView in the onCreate method

How to replace the edit text value in android?

I have stored value in First screen and pass that value and set the value in Edit Text of Second screen. While i am back into first screen and change the value and pass again to second screen and set that value in edit text. Here, it shows previous value only doesn't replace that value.
EditText mobilenumber = (EditText) rootView.findViewById(R.id.mobilenumber);
mobilenumber.setText(mobile);
Above mobile is a variable and I stored the value from first screen and pass it to second screen to set that value in mobilenumber edit text.
1)if you are using activity(first screen and second screen). you can send value using intent.
intent.putExtra("mobile",mobile);
and access it in second screen using
getIntent().getExtras().getString("mobile","defaultvalue");
OR
2) Make mobile as global and static variable in first activity
and in second activity(screen)
in onResume()
setText(firstactivity.mobile);
As you said both the screen are fragment you can share a global variable in activity(if both fragment part of same activity) or
can communicate via passing value in bundle would be safest and
reliable way
Using the Bundle
From your first activity :
public void onCreate(Bundle b){
super.onCreate(b);
String number = "" + R.id.IDInYourFirstActivity;
b.putString("mobilenumber", number);
}
in your next activity
public void onCreate(Bundle bd){
super.onCreate(bd);
String mobileNo = bd.getString("mobilenumber");
EditText mobilenumber = (EditText) rootView.findViewById(R.id.mobilenumber);
mobilenumber.setText(mobileNo);
}
You can use a static variable in second screen. Then in first screen when you change the value then
Second.mobile=your value.
It will change the value accordingly.

How to pass the value of a pressed button

I was wondering how to pass the value of a button to another activity. I have a screen with 7 buttons, and each button shows different data from the SQLitedatabase. So I was wondering how I can implement that in the activity so that I can select different data from the database, dependable which button was clicked in the previous activity. I know I have to use Bundles and Intents, but I cannot find how I can implement that so that the Activity knows which button was clicked and which data to select. Thanks!
How to pass the value of a pressed button
Buttons don't really have a "value". You could use the button's ID, though:
public void onClick(View v) {
startActivity(new Intent(this, YourOtherActivity.class)
.putExtra(YourOtherActivity.EXTRA_SOME_KEY, v.getId()));
}
This will pass the widget ID of the Button that was clicked in an extra (named YourOtherActivity.EXTRA_SOME_KEY) to YourOtherActivity. YourOtherActivity, in onCreate() or elsewhere, could call getIntent().getIntExtra(EXTRA_SOME_KEY, -1)) to retrieve the widget ID of the button that was clicked, then use a switch statement or some such to route your behavior as needed.
Set it with
Intent myIntent = new Intent(this, ACTIVITY.class);
myIntent.putExtra("buttonValue", BUTTON VALUE);
startActivity(myIntent);
Get it with
getIntent().getStringExtra("buttonValue")
Button Text
String buttonText = button.getText().toString()

While using same spinner in all the activities

I am using the same spinner to all the activities in my app. Let's say, items in spinner are English, Finnish, Polish, blah.. When I select Finnish in one activity, the dropdown of spinner gets close and Finnish can be seen on the spinner. But when I go to the next activity it does not show the Finnish anymore, instead, it shows English (item) at the top. Is there any method to make appear the item on the spinner that has been selected to all the activities. Or, should not change unless it has not been changed.
In BaseActivity;
int currentLanguage = spinner.getSelectedItemPosition();
SharedMemory.getInstance().setCurrentPosition(currentLanguage);
Log.i("SET POSITION", Integer.toString(currentLanguage));
In other activity to save the state of item position;
int position = SharedMemory.getInstance().getCurrentPosition();
Base_Activity.spinner.setSelection(position);
Log.i("GET POSITION", Integer.toString(position));
I managed to set the selected language to set it in SharedMemory which is Singleton class.
But how can I still get the same currentLanguage in all the activities. I am not able to get it when I change the activity.
Note: this spinner is in action bar in Base_Activity class where all the other activities are extended this class.
Thank you.
Finally, I managed to solve my problem. Before I was trying to do stuffs inside spinner.setOnItemSelectedListener() method, which was really wrong.
In my BaseActivity;
Configuration conf = getResources().getConfiguration();
//creating the position of the language in spinner from arraylist
int currentLanguage = Arrays.asList(language_codes).indexOf(
conf.locale.getLanguage());
spinner.setSelection(currentLanguage);
This allows me the selected item of spinner remain on the top always when I even change the activities. Hope this might help others. :)
That is because the spinner in the other activity is different from the one in the first activity.
You will have to pass the current selection of the spinner as argument to the second activity and set the other spinners selection to that position.
In BaseActivity:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("pos", spinner.getSelectedItemPosition());
startActivity(intent);
In second Activity:
spinner.setSelection(getIntent().getIntExtra("pos", 0));
The singleton class should probably look like this:
public class SharedMemory {
public static SharedMemory sharedMem = new SharedMemory();
private String valueSelected; // or position here
public SharedMemory getInstance() {
return sharedMem;
}
public String getCurrentLanguage() {
Log.i("tag","valueSelected: " + valueSelected);
return valueSelected;
}
public void setCurrentLanguage(String currLang) {
valueSelected = currLang;
Log.i("tag","valueSelected: " + valueSelected);
}
}
EDIT:
onItemSelectedListener(...) {
if(ShareMemory.getInstance().getCurrentLanguage().equalsIgnoreCase("0")) {
// then set the value to 0
}else {
// set the value still but then set the gui also
}
}
// in the onResume or onCreate method
write the following:
spinner.setSelection(ShareMemory.getInstance().getCurrentLanguage());
Using Log print the values in the singleTon class, and also the onItemSelected listener of the spinner.

Change Value of TextView, ImageView, ImageButton when i press button in other Activity

I am developing one simple app but i have problem.
The problem I have is that two activities, Activity1, have 26 button A-Z and Activity2 have textView,ImageView. I don't know how to set the button with default value.
Question
How can I change the value of textView, ImageView, and button in Activity2 whenever I press any button in Activity1?
Question
if i click buttonA how can i change texView display from "TextView" to "A" and imageView to other Image can u guys help me?
In simple way you can pass the value within intent like
Intent Activity2Intent = new Intent(this, Activity2.class);
Activity2Intent.putExtra("BUTTON_TEXT", yourText);
Activity2Intent.putExtra("IMAGE_VIEW", yourText);
startActivity(Activity2Intent);
Else if the data is needed later you can store that in SqliteDatabase
UPDATE
You should also need to extract the values passed from the bundle on Activity2.
You can use SharedPreferences or Intent for passing the value from Activity A and retrive the value in next Activity .
In Activity A:::
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Do something and save the value and pass it using intent
// pass the button name or use boolean is_state= true;
}
});
In Activity B:::
By using getIntent() retrive the button name and change theTextViewandImageView` as per your requirement

Categories

Resources