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á!
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.
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I started learning from the tutorials on android.developers and I had a question:
In their "Starting another activity" Tutorial they create a method sendMessage in the MainActivity class in order to send the content of an EditText in MainActivity to a ViewText in a second activity.
The content is sent by using the Intent's setExtramethod.
They display the content using this code:
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
....
}
I was wondering, why would they need to create a new TextView and not use the one given in the xml file of the activity by default (the "Hello World" one).
So I tried to do it by myself and my app crashes and I wanted to know what am I doing wrong and if this is the reason why they didn't do it the way I was thinking of doing it.
What I did is this:
Fragment_display_message.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="horizontal" >
<TextView
android:id="#+id/TVmessage"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
and they way I try to display the message in the DisplayMessageActivity :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView text = (TextView) findViewById(R.id.TVmessage);
text.setText(message);
}
also sendMessage is done this way:
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
In summery my question is: If the way I do it is possible and i'm just missing something to make it work, is there a reason why they didn't do it this way? Why they didn't use the Activity's layout and just created a TextView in the code and set it as the content of the activity ?
Thanks for reading my question !
Edit:
public class DisplayMessageActivity extends ActionBarActivity {
public static Intent intent;
public static TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
intent=getIntent();
text=(TextView) findViewById(R.id.TVmessage);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
text.setText(message);
return rootView;
}
}
Its because you change the content by adding the placeholder fragment and the TextView goes out of scope. If you remove the setting of the fragment it should work.
Another issue may be that the message variable is actually null when retrieved from the bundle. Double check that too.
I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")
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()
For my own practice I am a creating an array of 3 buttons in the instance field and i would like all of them to have setOnClickListeners,which allow each button to change the BackGround Color of a text View.Can any person please guide me towards the right direction.Here is my code:
public class MainActivity extends Activity {
Button b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
for(int i=0; i < b.length;i++){
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(butt[0].isPressed()){
tv.setBackgroundColor(Color.BLACK);
}
if(b[1].isPressed()){
tv.setBackgroundColor(Color.BLUE);
}
if(b[2].isPressed()){
tv.setBackgroundColor(Color.RED);
}
}
});
}
}
}
You aren't declaring an Array for your Buttons. I'm not sure what this would do or if it would even compile but I wouldn't think so
Button b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
Change it to
Button[] b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
Also, this code has to go after setcontentView() or you will get a NPE since your Buttons exist in your layout and your layout doesn't exist until you inflate it by calling setContentView().
You can declare your Array before onCreate() but you can't initialize them until you inflate your layout
So you can do something like this
public class MainActivity extends Activity {
Button[] b = new Button[3]; //initialize as an array
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),}; //add buttons AFTER calling setContentView()
...
Edit Since #pragnani deleted his answer I will edit with a bit of it that is a good idea
You can simplify your logic by choosing which Button was clicked with a switch by doing something like below in your for loop
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { / v is the button that was clicked
switch (v.getId()) //so we get its id here
{
case (R.id.button1):
tv.setBackgroundColor(Color.BLACK);
break;
case (R.id.button2):
tv.setBackgroundColor(Color.BLUE);
break;
case (R.id.button3):
tv.setBackgroundColor(Color.RED);
break;
}