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()
Related
I made a TableLayout 3x3 in "Activity A"(Chose a Table Layout, because I thought it suits my needs)
7 of the 9 cells are clickable and open "Activity B" which is a custom number picker I made.
I used an intent to pass an array and other data to activiy B
The idea of my number picker is to set a value in the cell I just clicked in Activiy A(I wanted something like the calendarDatePicker)
In "Activity B" I have a method to update the values from "Activity A" and finish() "Activity B" when an image View is clicked wich works very fine except that it does not set the value for the clicked Text View
How can I set the TextValue from another activity when the TextValue is contained in a Table Layout?
I don't use intent, because honestly I don't know how to handle it when the "Activity B" is closed.
I mean where in "Activity A" should I handle this intent from "Activity B"
Using the debugger I found out that trying to set the text using the TextView Id does not works as it shows a "null" object in the debugger.
Activiy A
package com.example.racu.threebythree;
public class threebythree extends AppCompatActivity {
public static ArrayList<Integer> ColumnA = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnB = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnC = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three_by_three);
for (int i = 1; i < 28; i++) {
if (i > 0 && i < 10)
ColumnA.add(i);
if (i > 10 && i < 19)
ColumnB.add(i);
if (i > 19 && i < 28)
ColumnC.add(i);
}
}
public void openNumberPicker(View v) {
// I used this to "guess" the location of the cell in the table layout as I could not find a way to do it.
String cellName = v.getResources().getResourceName(v.getId());
String cellLetter = cellName.substring(cellName.lastIndexOf("/") + 1);
// Send intent
Intent intent = new Intent(this, NumberPicker.class);
intent.putExtra("Id", (cellLetter.substring(0, 1) + cellLetter.substring(2)).toUpperCase());
switch (cellLetter.substring(0, 1)) {
case ("a"):
intent.putIntegerArrayListExtra("Column", ColumnA);
break;
case ("b"):
intent.putIntegerArrayListExtra("Column", ColumnB);
break;
case ("c"):
intent.putIntegerArrayListExtra("Column", ColumnC);
break;
}
intent.putExtra("Cell ID", v.getId());
startActivity(intent);
}
}
Avtivity B
package com.example.racu.threebythree;
public class NumberPicker extends AppCompatActivity {
GridView numberPicker;
ArrayList<Integer> numbersToDisplay;
TextView viewToDisplay;
ImageView ok, cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_picker);
numberPicker = (GridView) findViewById(R.id.arrayNumbers);
viewToDisplay = (TextView) findViewById(R.id.number_to_select);
ok = (ImageView) findViewById(R.id.add_number_to_card);
ok.setClickable(false);
Intent intent = getIntent();
String idFromIntent = intent.getStringExtra("Id");
numbersToDisplay = intent.getIntegerArrayListExtra("Letter");
TextView numberPosition = (TextView) findViewById(R.id.numberPosition);
numberPosition.setText(idFromIntent);
final TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, R.layout.number_for_picker, numbersToDisplay);
numberPicker.setAdapter(adapter);
numberPicker.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
chosenNumber.setText(((TextView) v).getText());
ok.setImageResource(R.drawable.ok_blue);
ok.setClickable(true);
}
});
}
public void updateThreByThree(View v) {
Intent intent = getIntent();
int currentCell = intent.getIntExtra("Cell ID", 0);
String idFromIntent = intent.getStringExtra("Id").substring(0, 1);
TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
// Here I try to Set the text to the cell in Activity A, using its R.id, but in the debugger I get a null reference, therefore my app crashes
TextView currentCellToEdit = (TextView) findViewById(currentCell);
currentCellToEdit.setText(chosenNumber.getText());
int temp = Integer.parseInt(chosenNumber.getText().toString());
switch (idFromIntent) {
case "A":
threebythree.ColumnA.remove(Integer.valueOf(temp));
break;
case "B":
threebythree.ColumnB.remove(Integer.valueOf(temp));
break;
case "C":
threebythree.ColumnC.remove(Integer.valueOf(temp));
break;
}
finish();
}
public void cancel(View view) {
finish();
}
}
Thanks to Pavan for the hint I found two more very helpful post here and this one was EXACTLY what I was looking for.
Like that ( make sure you give the TableLayout an id ):
TableLayout tl = (TableLayout)findViewById( R.id.tableLayout );
TextView tv = (TextView)tl.findViewById( R.id.textView );
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);
}
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 having a problem with passing strings from a fragment to another activity.
I have tried numerous methods of passing them using intents (eg normal extras, bundles) , but the extras are always null in the activity.
I have looked at
http://www.vogella.com/articles/AndroidIntent/ But no change
http://developer.android.com/training/basics/firstapp/starting-activity.html This method of passing the data also doesn't work
Other similar questions on stackoverflow - but these are not quite the same
What I'm trying to do is get the text that was input in the two EditTexts in the fragment, and then pass that text to the activity where the two EditTexts there are filled with the same text. The problem is that nothing appears in the the two EditTexts in the activity. I know that the EditTexts in the fragments are working because a can create a notification using them.
My code: I have removed things I think are unneccessary eg adding the fragment to a navigation drawer layout. Please excuse missing brackets - I have removed a lot of code and some may have been removed accidentally! :-)
This is the fragment where I create an intent:
// Package declaring and importing stuff
public class QuickNoteFragment extends Fragment implements OnClickListener {
// Removed some stuff
EditText body;
EditText title;
Button create;
int counter = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
body = (EditText) rootView.findViewById(R.id.qn_et_body);
title = (EditText) rootView.findViewById(R.id.qn_et_title);
create.setOnClickListener(this);
// Removed stuff
getActivity().setTitle(noter_activity); // Part of navigation drawer?
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String content_text = body.getText().toString();
String content_title = title.getText().toString();
if (content_title.length() >=1){
Context context = v.getContext();
// This intent does not seem to work
Intent eIntent = new Intent(context, QuickNoteEdit.class);
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
PendingIntent EditPendingIntent = PendingIntent.getActivity(context, 0, eIntent, 0);
// This intent works comletely. This is called when a notification action button is pressed
Intent qnCancel = new Intent();
qnCancel.setAction("com.RiThBo.noter.qnCancelBroadcast");
Bundle extras = new Bundle();
extras.putInt("valueOfCounter", counter);
qnCancel.putExtras(extras);
startBroadcast(qnCancel);
PendingIntent pQnCancel = PendingIntent.getBroadcast(this.getActivity(), 0, qnCancel, 0);
// Creates Notification
} else {
// Do something
}
case R.id.*** // Does something else
}
}
private void startBroadcast(Intent qnCancel) { // This is part of the correctly working intent
// TODO Auto-generated method stub
}
}
This is the activity where I'm trying to get the extras
// Removed package and imports
public class QuickNoteEdit extends Activity implements OnClickListener {
EditText body;
EditText title;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quicknote_edit);
variableConnector(); // This gets the id for all the items in the xml
Intent intent = getIntent();
String gotTitle = intent.getStringExtra("content_title"); // This is where I think it equals null. Because the
String gotBody = intent.getStringExtra("content_text");
title.setText(gotTitle);
body.setText(gotBody);
}
private void variableConnector() {
// TODO Auto-generated method stub
body = (EditText) findViewById(R.id.qne_et_body);
title = (EditText) findViewById(R.id.qne_et_title);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Thank you
You're putting:
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
and when you read them:
String gotTitle = intent.getStringExtra("content_title");
String gotBody = intent.getStringExtra("content_text");
You need to match the keys ... put "eTitle" and read "eTitle", not "*content_title*"!
You're tagging your extras with "eTitle" and "eText" and trying to retrieve them with "content_title" and "content_text".
Switch to
String gotTitle = intent.getStringExtra("eTitle");
String gotBody = intent.getStringExtra("eText");
it should work.
I'm trying to use setText to show different text within the same layout everytime someone clicks a different picture.
So all the layout files stay the same the only thing that needs to change is the android:text in that layout.
I've created a class with case statement for when someone presses on a picture and then call setText().
But it looks like the setText isn't even called. because I can see my Log.v that is called within the same case statement but the text doesn't change.
PictureInfo.java
public class PictureInfo extends Activity implements OnClickListener {
private static final String TAG = "Popup";
public TextView infoText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
infoText = (TextView)inflater.inflate(R.layout.information, null);
View a1Button = findViewById(R.id.a1);
a1Button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.a1:
Intent a = new Intent(this, Information.class);
startActivity(a);
Log.v(TAG, "Change setText");
infoText.setText(R.string.a2_text);
break;
}
}
}
information.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/information_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/a1_text"
/>
It appears that you are inflating a layout - R.layout.information, but casting this to a TextView. I'm really not sure what you are doing there.
I think you want the destination Activity to use some text in its layout that the source Activity provides to it. Why not pass the id of the text you want displayed as an Extra on the Intent?
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.a1:
Intent a = new Intent(this, Information.class);
intent.putExtra("com.packagename.identifier", R.string.a2_text);
startActivity(a);
break;
}
}
Then in your Information Activity:
public class Information extends Activity {
...
TextView myTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
...
myTextView = (TextView) findViewById(R.id.myTextViewId);
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
int textId = extras.getInt("com.packagename.identifier");
infoText.setText(textId);
}
}
}
Change the order of the code to:
//First change text
Log.v(TAG, "Change setText");
infoText.setText(R.string.a2_text);
//Then call new activity
Intent a = new Intent(this, Information.class);
startActivity(a);
And voilá!