I have three different classes and when the ImageButton in class1 is clicked I want that the TextView in class3 should change to "50". On the other hand when the ImageButton in class2 is clicked I want that the TextView in class3 should change to "0".
class1:
ImageButton button1 = (ImageButton) this.findViewById(R.id.imageButton);
if (button1 != null) {
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent passdata_intent1 = new Intent(class1.this, class3.class);
String data1 = "50";
Bundle bundle1 = new Bundle();
bundle1.putString("firstdata", data1);
passdata_intent1.putExtras(bundle1);
startActivity(passdata_intent1);
}
});
}
class2:
ImageButton button1 = (ImageButton) this.findViewById(R.id.imageButton);
if (button1 != null) {
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent passdata_intent2 = new Intent(class2.this, class3.class);
String data2 = "0";
Bundle bundle2 = new Bundle();
bundle2.putString("seconddata", data2);
passdata_intent2.putExtras(bundle2);
startActivity(passdata_intent2);
}
});
}
class3:
TextView score = (TextView) findViewById(R.id.textViewscore);
Bundle bundle1 = getIntent().getExtras();
String data_1 = bundle1.getString("firstdata");
score.setText(data_1);
Bundle bundle2 = getIntent().getExtras();
String data_2 = bundle2.getString("seconddata");
score.setText(data_2);
So my problem is that when I start the application and I click on the ImageButton in class2 the TextView in class3 changes. But when I click the ImageButton in class1 nothing changes in class3.
From the snippets of code I see the problem seems to be that you first check for "firstdata" extra in the intent set it to the text view and then you check for "seconddata" extra and override the value in the text view with it.
When you pass the firstdata to the activity the seconddata (if not passed) should be null and thus you set the score text to null and erase the first data value from it.
There is no need to user 2 different names for the extras in order to pass data to the same textview from 2 different entry points.
Use "firstdata" extra name for both class1 and class2 to pass the data and it should work.
Yo uare overriding the score value in both cases. If else logic will work fine.
if(getIntent().hasExtras("firsdata")){
Bundle bundle1 = getIntent().getExtras();
String data_1 = bundle1.getString("firstdata");
score.setText(data_1);
} else{
Bundle bundle2 = getIntent().getExtras();
String data_2 = bundle2.getString("seconddata");
score.setText(data_2);
}
Related
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 have two class Profile.class and Details.class,
In profile class i have used a spinner with values like (ATM,Banking,Personal,Others etc)
and a button (OK).
on clicking ok button it will go to next activity that is details activity where i will be taking some details like-name,description etc.
after filling the details i have given a button (save).
on clicking button save i will be saving the name and description in database but i want to save the profile name also along with details. i am unable to transfer selected spinner text from Profile.class to Details.class
how to transfer?
create.class code
public class Create extends Activity {
public ArrayList<String> array_spinner;
Button button4;
String spinnertext;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
array_spinner=new ArrayList<String>();
array_spinner.add("ATM");
array_spinner.add("Bank");
array_spinner.add("Mail");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, array_spinner);
adapter.setNotifyOnChange(true);
spinner.setAdapter(adapter);
spinner.setLongClickable(true);
spinner.setOnLongClickListener(new OnLongClickListener(){
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}}
);
button4 = (Button)findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent4 = new Intent(view.getContext(), Details.class);
startActivityForResult(myIntent4, 0);
myIntent4 .putExtra("key", array_spinner.getSelectedItem().toString());
startActivity(myIntent4);
}
});
}}
details.class code
public class Details extends Activity {
EditText editText4,editText5,editText6;
Button button8,button9,button10;
TextView textView7;
String et4,et5,et6;
//SQLite Database db;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
String spinnervalue = getIntent().getExtras().getString("Key");
please kindly explain me what is this "key"?
You can use :
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", yourData.getText().toString());
then you can get it from your second activity by :
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
example
this is what you have to write in your first activity
Intent i = new Intent(getApplicationContext(), Product.class);
i.putExtra("productname", ori);
i.putExtra("productcost", position);
i.startActivityForResult(i,0);
then in your next activity you need to have this code
String productname,productcost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product);
tv1= (TextView)findViewById(R.id.tv1);
tv2= (TextView)findViewById(R.id.tv2);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
position = extras.getString("position"); // get the value based on the key
tv1.setText(productname);//use where ever you want
productname = extras.getString("productname"); // get the value based on the key
tv2.setText(productname);
}
First of all take a spinner and provide value to them what you want and then the selected spinner value change it to string value and this string variable will be used in OK button to pass value through use of Intent or Shared preference to take this value to another activity and through there you can use it in database to display this value.
If you want to send data to another activity, you can do it using intent.
Bundle bund = new Bundle();
bund.putString("myKey",name);
Intent intent = new Intent(Profile.this, Detail.class);
intent.putExtras(bund);
startActivity(intent);
Now in Detail class, receive this data in onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
.......
String nameReceived = getIntent().getExtras().getString("myKey");
}
I have given the example of passing String to another activity however, you can pass boolean, int, double etc to another activity. See the full list on here
I am doing a quiz app in which there are Act1 and Act2. Act1 shows the view for each question answers to select.
public class ACT1 extends Activity
{
EditText question=null;
RadioGroup choices = null;
-------
------
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
/* //---get the Bundle object passed in---
Bundle bundle = getIntent().getExtras();
//---get the data using the getInt() method---
int qId = bundle.getInt("questionIndex");
//dont know what to do here
question = (EditText) findViewById(R.id.question);
RadioGroup questionLayout = (RadioGroup)findViewById(R.id.answers);
------
this.getQuestionView(questionNo);
FrameLayout quizLayout = (FrameLayout) findViewById(R.id.quizLayout);
quizLayout.setVisibility(android.view.View.VISIBLE);
}
and in the method getQuestionView() the rest of code for getting questions and answers next submit buttons everything is there.
private void getQuestionView(questionNo)
{
------
------
//next and previous buttons OnClicklisteners
------
private OnClickListener finishListener = new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Act1.this,Act2.class);
}
}
And Act2 shows a view for results which includes a table for questionlinks. on clicking the question link the respective question view shall be shown which is from Act1 and on back button clicked it goes back to Act2. i am new to android so anybody please help.
public class Act2 extends Activity {
--------
-------
TableLayout questionsTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
int totalQues = Act1.getQuestions().length;
questionsTable =(TableLayout)findViewById(R.id.questions);
-------
-------
for(int i=0;i<totalQues;i++)
{
------
--------
TableRow tr = new TableRow(this);
TextView queText = new TextView(this);
tr.addView(queText,LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
tr.setClickable(true);
tr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this,Act1.class);
//---use a Bundle object to add new key/values pairs---
Bundle extras = new Bundle();
//here i wanna check whether 2nd question is displaying
extras.putInt("questionIndex",2 );
//---attach the Bundle object to the Intent object---
intent.putExtras(extras);
startActivity(intent);
}
});
thanks in advance.
If I'm not mistaken, you need is to pass some data from one activity to another. This is done through the Intent class, it can contain "extras" which are actually simply key-value pairs which can be written by the calling activity and later read by the called activity.
For example, I can write the code like this:
public static final String EXTRA_QUESTION = "question";
// When you need to create the intent:
Intent intent = new Intent(this, Act2.class);
// questionId is whatever identifies the question in your code
intent.putExtra(EXTRA_QUESTION, questionId);
And in the other activity you write:
Intent intent = getIntent();
// In this example questionId is int, but it could be something else
int questionId = intent.getIntExtra(Act1.EXTRA_QUESTION, 0);
I have an android program which sends to another activity after clicking on a button. Mainly, I want to set the text from textview in the new windows so that it corresponds to the selected button. For example, if I click on button Writers, the next new activity should have a textview on which the word Writers appears. Everything works fine, except when I try to setText on the TextView icon for category. I also tried to call this change in the first activity, before launching the second one, it didn't work.
I also mention that if I comment the line with the setText, the program works just fine.
private String category;
public final static String CATEGORY_MESSAGE = "e.c.project.CATEGORY";
public void onClick(View v) {
switch(v.getId())
{
case R.id.actors:
category = "actors";
playTheGame(v);
break;
case R.id.cartoons:
category = "cartoons";
playTheGame(v);
break;
case R.id.singers:
category = "singers";
playTheGame(v);
break;
case R.id.writers:
category = "writers";
playTheGame(v);
break;
}
}
public void playTheGame( View view ){
Intent intent = new Intent(this, PlayGame.class);
String category = playGameButton.getText().toString();
intent.putExtra(CATEGORY_MESSAGE, category);
// TextView tv = (TextView) findViewById(R.id.categoryTV);
// tv.setText(category);
startActivity(intent);
}
this is the OnCreate method from the second activity:
private TextView categoryTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);
categoryTV = (TextView) findViewById(R.id.categoryTV);
categoryTV.setText(category);
setContentView(R.layout.activity_play_game);
// Show the Up button in the action bar.
setupActionBar();
}
You need to call setContentView(R.layout.activity_play_game); before categoryTV = (TextView) findViewById(R.id.categoryTV); Otherwise your TextView is null
private TextView, categoryTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game); // make this call BEFORE initializing ANY views
Intent intent = getIntent();
String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);
categoryTV = (TextView) findViewById(R.id.categoryTV);
categoryTV.setText(category);
// Show the Up button in the action bar.
setupActionBar();
}
Your Views exist in your Layout so if you try to access any of them before inflating your Layout, with setContentView() or an inflater, they will be null resulting in a NPE when you try to call a method on them such as setText()
I'm trying to get a string value from a listview and put into another view. I've managed to do this successfully for my first listview but it won't seem to work for my third. ( I managed to get it to work but its stopped working now for reasons I cant understand) I am using the exact same method and the information i'm trying to retrieve is being retrieved as I have confirmed while running the problem is its just not getting changed.
Code
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statseditor);
dbHelper = new PlayerStatsDatabase(this);
dbHelper.open();
Bundle extras = getIntent().getExtras();
if(extras !=null){
//String value = extras.getString("Name");
}
//Clean all data
// dbHelper.deleteAllStats();
//Add some data
//dbHelper.insertSomeCountries();
//Generate ListView from SQLite Database
//displayListView();
// list = getListView();
PlayerNameText = extras.getString("Name");
btnSave2 = (Button) findViewById(R.id.btnSaveStats);
btnClear = (Button) findViewById(R.id.btnClearStats);
txtGoalsScored = (EditText) findViewById(R.id.txtGoal);
txtMinutesPlayed = (EditText) findViewById(R.id.txtMinPlayed);
txtSubstituteIn = (EditText) findViewById(R.id.txtSubIn);
txtSubstituteOut = (EditText) findViewById(R.id.txtSubOut);
radioSubIn = (RadioButton) findViewById (R.id.rdoSubIn);
radioSubOut = (RadioButton) findViewById (R.id.rdoSubOut);
playerRating = (RatingBar) findViewById (R.id.ratingBar1);
//playerTitle = (TextView) findViewById (R.id.textTitle);
playerName = (TextView) findViewById (R.id.textView1);
playerName.setText(PlayerNameText);
//playerTitle.setText (PlayerNameText);
checkBox = (CheckBox) findViewById (R.id.checkBox1);
if (checkBox.isChecked()){
checkBox.append("Booked");
}
final CharSequence checkText = checkBox.getText();
//final Context context =
btnSave2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PlayerStatsDatabase db = new PlayerStatsDatabase(getApplicationContext());
db.open();
db.createStats(txtGoalsScored.getText().toString(), txtMinutesPlayed.getText().toString(),txtSubstituteIn.getText().toString(),txtSubstituteOut.getText().toString(), checkText.toString());
db.close();
dipsplayPlayerName();
displayListView();
//Intent intent = new Intent(context, ListItemsActivity.class);
// startActivity(intent);
}
});
}
In this first instance where I use this method playerName actually gets changed to PlayerNameText
But further down when I try to use it again it doesnt work
private void dipsplayPlayerName() {
setContentView (R.layout.statslist);
Bundle extras = getIntent().getExtras();
PlayerNameText = extras.getString("Name");
playerTitle = (TextView) findViewById (R.id.textTitle);
playerTitle.setText (PlayerNameText);
}
Any ideas? The is no LogCat as the app doesnt crash
Put the text data you received into a field and use it instead of getting it from the intent again.
Also, check that displayListView() doesn't change the textView.