In my projects I kept different images for categories. When I click on each category image I am passing its category id to other page statically and setting the drawable image of that category in the new page.
My Code:
Firstpage.java
public static String categoryid;
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="0";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="1";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="2";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
Nextpage.java
public static String catid = Firstpage.categoryid;
ImageView categorytype=(ImageView)findViewById(R.id.imageView1);
if(catid=="0")
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid=="1")
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid=="2")
{
categorytype.setBackgroundResource(R.drawable.image3);
}
First time when I am clicking on the category image it is passing the category id to the next page and that particular image is setting in the nextpage. After that I clicked the back button(android back button) and went to Firstpage.java and again clicked on other image. But this time also the same image stored. The category id didnt changed. The category id is not refreshing...How to refresh the category id? Any suggestion will be thankful.....
You are comparing two strings by == operator, instead you should compare by equals method, try following:
if(catid.equals("0"))
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid.equals("1"))
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid.equals(2"))
{
categorytype.setBackgroundResource(R.drawable.image3);
}
Don't use static variables for this. Pass the category ID to your Nextpage activity through the intent. In Firstpage.java:
public static final String CATEGORY_KEY = "category";
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(this,Nextpage.class);
myIntent.putExtra(CATEGORY_KEY, "0");
startActivityForResult(myIntent, 0);
}
});
Then retrieve it in the onCreate(Bundle) method of Nextpage.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String categoryid = intent.getStringExtra(Firstpage.CATEGORY_KEY);
. . .
}
The reason your method doesn't work is that Nextpage.catid is initialized when the class is loaded, but the assignment statement is not executed again unless the class is unloaded and needs to be reloaded.
I think problem is here you are comparing String values using this if(catid=="0") Which you should be compare it using if(catid.trim().equals("0"))
Update this change in your code and check it.
Related
I've made a list made of TextViews and Buttons, made that when a person clicks on a button, a fragment opens and there is a list of values he can select. The problem is when i press on another button to select a value again for a different field, the previous value disappears. So the question would be how to save the fragments values, and keep it saved until the app is closed ?
priceButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
PriceFragment priceFragment = new PriceFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, priceFragment).commit();
setToHideElements();
}
});
yearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
YearFragment yearFragment = new YearFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, yearFragment).commit();
setToHideElements();
}
});
this is the year fragment
yearEndListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity().getBaseContext(), MainMenuActivity.class);
String yearTo = yearList[i].toString();
int yearTint = Integer.valueOf(yearTo);
if (combinedYear != null) {
combinedYear = combinedYear + " " + yearTo;
intent.putExtra("Years", combinedYear);
getActivity().startActivity(intent);
} else {
combinedYear = null;
combinedYear = yearTo;
}
}
});
this is the method to retrive data
private void retriveDataFromFragment(){
Intent intent = getIntent();
String fragmentDataPrice = intent.getStringExtra("PriceData");
String fragmentDataYear = intent.getStringExtra("Years");
if(fragmentDataPrice != null){
priceButton.setText(fragmentDataPrice);
} else {}
if (fragmentDataYear != null){
yearButton.setText(fragmentDataYear);
} else {}
}
I use RetriveDataFromFragment method in OnResume method.
Thank you, for your time.
you are initiating every time a new fragment so it will never retain its state. you have to use listener while closing the fragment so you can get back your data.
I got the anwser if someone else needs a similar menu, all you have to do is create a class that extends Application, and include into your manifest (the part with application tags). From there you just use getters and setters and all is well.
I have RecyclerView + cards. In the cards I set the random color in class ViewHolder -
` int[] androidColors = view.getResources().getIntArray(R.array.androidColors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
if (frameLayout != null) {
frameLayout.setBackgroundColor(randomAndroidColor);
}`
By clicking on the card, open activity. And the color of her toolbar should be like that of a card.
Intent putExtra I can not use here, because in the intent, I already pass the tag.
public ViewHolder(View itemView) {
....
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long poemId = (Long) v.getTag();
onPoemClickListener.onPoemClick(poemId);
}
});
}
}
public interface OnPoemClickListener {
void onPoemClick(long poemId);
}
fragment class where recycler is located
private final PoemsAdapter.OnPoemClickListener onPoemClickListener = new PoemsAdapter.OnPoemClickListener() {
#Override
public void onPoemClick(long poemId) {
Intent intent = new Intent(getActivity(), ReadActivity.class);
intent.putExtra(ReadActivity.EXTRA_POEM_ID, poemId);
startActivity(intent);
}
};
How can I get the random color that I generate in the adapter in activity? Thank!
You can put as many extras as you want:
Intent intent = new Intent(getActivity(), ReadActivity.class);
intent.putExtra(ReadActivity.EXTRA_POEM_ID, poemId);
intent.putExtra("mycolor", color);
startActivity(intent);
then get it in the activity that opens, just like you get any other extra value,
I need help with my code. Let me try to explain the problem:
At the first activity I have two fields where I'll set values from an Enum, for this I made a button for each field that basically shows me another activity, calls the value and brings it to the main activity. Still in the first activity I have a button that starts another activity and (at the same time) take all the values from the enum end sends to another activity. The point is, everything is working, but this last button no, when I click it the app crashes. What is happening and how can I solve it?
Here goes the code of the first activity:
public class MenuInicial extends AppCompatActivity {
public static final int CONSTANTE_BANZO = 1;
Button escolherM;
Button escolherB;
Button next;
TextView campoM;
TextView campoB;
Intent intent1;
Intent intent2;
Intent intentBundle;
Intent intentNext;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_inicial);
intent1 = new Intent(MenuInicial.this, Montante.class);
campoM = (TextView) findViewById(R.id.fieldM);
escolherM = (Button) findViewById(R.id.chooseM);
String perfilM = getIntent().getExtras().getString("nameM");
campoM.setText(perfilM);
escolherM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivity(intent1);
}
});
intent2 = new Intent(MenuInicial.this, Banzo.class);
campoB = (TextView) findViewById(R.id.fieldB);
escolherB = (Button) findViewById(R.id.chooseB);
escolherB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivityForResult(intent2, CONSTANTE_BANZO);
}
});
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
}
protected void onActivityResult(int codigo, int resultado, Intent intent){
if(codigo == CONSTANTE_BANZO){
Bundle bundleB = intent.getExtras();
if(bundleB != null){
String perfilB = bundleB.getString("nameB");
campoB.setText(perfilB);
}
}
}
}
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
Which activity do you want to go to? choose one. When you do, you can get those extras then when you need to goto the other activity, you can put those extras there too.
A better way to do it is to create a model (constructor with setters and getters) and put these in a list. At that point you can loop through the list and take what you need. It all depends on what you are doing though as the list will not be instantiated like intent extras would be.
Or, you can use SharedPref which is similar to a HashMap (which is also similar to the Intent Extras). SharedPref will store the key and value on the phones cache and then you can pull from that when you need it. Again, keep in mind that if the user clears the cache on the app, then it'll delete those shared pref.
Finally, you can also use a database such as Parse Server or Firebase.
I'm currently trying to guess how do I save a data from a previous Activity.
An example is:
At the startPage.class, I have a few options to choose from(Animation Mode, Image Mode, Text Mode) so if I choose for example Text Mode so the it'll be the RadioButton3 and when I press next it goes to the another Activity. So lets say in that new Activity it has this Intent command. How do I retain the data from the previous activity when I press the backSelection3?
Meaning, when I press the back, I want the RadioButton3 to be the selection still instead of it resetting to the default choice.
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backSelection3 = new Intent(imagemode64by64.this, startPage.class);
startActivity(backSelection3);
}
});
You can use onSaveInstanceState
void onSaveInstanceState(Bundle out) {
String val = ...
out.putString("MYVALUE", val);
super.onSaveInstanceState(val);
}
Then
void onCreate(Bundle savedState) {
if(savedState != null) {
String val = savedState.getString("MYVALUE");
}
}
Or do you mean how to put data for another activity? Then you can do
Intent i = new Intnet(this, OtherActivity.class);
String val = ...
i.putExtra("MYVALUE", val);
startActivity(i);
Then in the other activity
void onCreate(Bundle savedState) {
...
Intent i = getIntent();
String val = i.getStringExtra("MYVALUE");
}
Here is an age old example of passing data between classes:
class A{
static int num = 0;
public void setNum(int number){
num = number
}
}
class B{
public static void main(){
A obja = new A();
obja.setNum(3);
}
}
As soon as you do the operation in class B you can use the num variable in class A.
I want to pass the value of an EditText in one activity to another activity on button press and use that value in my code. However, there is one more activity between those activities in which I don't want to use that value
My Activity1 has:
textOut = (EditText)findViewById(R.id.ipadd);
Button ip = (Button) findViewById(R.id.ipad);
ip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent("com.shaz.hello"));
}});
From the Activity1 the user goes to the Activity2
Activity2
if ( x ==10 ) {
startActivity(new Intent("com.shaz.hello2"));
}
From the Activity2 the user goes to the Activity3
Activity3
Here I want to use that value as a String.
this is an another solution;
create one Bean class like this,
public class Bean {
public static String value;
public static String getValue() {
return value;
}
public static void setValue(String value) {
Bean.value = value;
}
}
On first Activity set the variable in Bean.
Bean bean = new Bean();
bean.setValue("your value");
And get the variable value on last or any Activity
Bean bean = new Bean();
String yourValue=bean.getValue();
You can using putExtra() and getExtra(), Add this in your current activity:
ip.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent mIntent = new Intent(currentActivity.this, hello.class);
mIntent.putExtra("valuename", Integer.valueOf(textOut.getText.toString));
startActivity(mIntent);
}
}
To get result from last activity put this line after onCreate():
int myValue = getIntent().getIntExtra("valuename", 0);
if (myValue == 10)
{
Intent mIntent = new Intent(currentActivity.this, hello2.class);
startActivity(mIntent);
}
Edited
You need to add your activities in android manifest file, e.g:
<activity android:name=".hello2"></activity>