Intent doesnt hand over variable from one class to another - android

I am new to Android programming and tried to create a small App. I have a MainClass with one EditText and one TextField. EditText is for users to type in a number and the TextField shows the value of the input when clicking on the first button. The second button is for switching to the other class (MainClass2). Now i want to show the input number from EditText (that I defined as "number") in the next class MainClass2 in an empty TextField. I implemented an OnClickListener for the two different buttons mentioned in the MainClass (first screen). Since I only defined the input variable "number" when clicking the first button (cause "number" is then shown in the TextField as mentioned because it is only created via EditText when clicking the first button), "number" is not defined in the code of clicking the second button. Therefore I cant hand it over to the MainClass2 via Intent. Do you have any solutions for this? Thank you in advance. These are the codes for my Classes:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
Button button2 = findViewById(R.id.button2);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(this);
}
public void onClick(View v) {
// default method for handling onClick Events..
switch (v.getId()) {
case R.id.button:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
TextView textView = findViewById(R.id.textView);
textView.setText(String.valueOf(number));
Random randomizer = new Random();
int name = randomizer.nextInt(number+1);
TextView textView2 = findViewById(R.id.textView2);
if (name == 1 ) {
textView2.setText("Player 1");
}
if (name == 2 ) {
textView2.setText("Player 2");
}
break;
case R.id.button2:
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number); //here is the error cause number is not
defined, although it is..
startActivity(intent);
break;
default:
break;
}
}
}
And this is the code for MainClass2:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView3 = findViewById(R.id.textView3);
Intent intent = getIntent();
String number = intent.getStringExtra("number");
textView3.setText(number);
}
}

In case R.id.button2: you have not set the value of number. So it will give number undefined error. To solve this issue either you have to initialize number globally or get the value of number in case R.id.button2: also. Like
case R.id.button2:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
Intent intent =
new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number);
startActivity(intent);
break;

Related

Android OnClickListener infinite button use problem

I am trying to make an simple button that will cooperate with TextView, array and method changer (in public class Change). However the application uses the method changer only twice (below). It should work on every click. The changer method is used for the change in displayed array.
1-click: 1 |
2-click: 4 |
3-click: 1 |
4-click: 1 |
...-click: 1 |
I don't know where is the problem.
My target solution should be 1,4,1,4,1,4 ...
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String[] numbers = {"1", "2","3","4"};
private Button mButton;
int i = 0;
Change ch = new Change();
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button2);
text = (TextView) findViewById(R.id.tv1);
ch = new Change();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text.setText(numbers[0]);
numbers = ch.changer(numbers);
i++;
}
});
}
}
Change.java
public class Change {
String[] arraynew = new String[4];
public String[] changer(String[] array){
arraynew[0]=array[3];
arraynew[1]=array[2];
arraynew[2]=array[1];
arraynew[3]=array[0];
return arraynew;
}
}
The arraynew variable in your code is global - so it will not create a new array every time you call the changer method, only rearranges its contents.
Here comes the tricky part: When you call the method for the second time, the parameter is the same object as arraynew. So when you do arraynew[0]=array[3] it changes 4 to 1 on the first slot; but arraynew[3]=array[0] will copy that newly changed 1 to the third index (where it is still the same 1 you put there). It basically eliminates the 4, making it impossible to recover.
Solution: Make arraynew local. If you declare it in the method, it will never be the same array, so the issue won't appear.

OnClick method does not start new activity

This code isn't calling the next activity. I don't understand why, but this onClick method isn't starting the next activity, though the same code in other activities does. Tested calling other activities and it didn't work even. The button is created, but when I tap it, nothing happens.
Edit: Folks, when we make a question about code, we want to know what is wrong, why is wrong, how to fix and why and this fixing works. We want to understand both the problem and the solution, and just drop a sample of code alone as an answer doesn't quite help some people. I thank you all for spending time with my question and for helping me solve this issue, but keep this words in mind when you are answering someone's question.
package com.example.conjuradortormenta;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class ListadePersonagens extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listade_personagens);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Using shared preferences, we get information about the characters
SharedPreferences informacoesdepersonagem = getSharedPreferences("com.example.conjuradortormenta_informaçoes_de_personagem", MODE_PRIVATE);
int num = informacoesdepersonagem.getInt("numero_de_personagens", 0);
String nome, resumo;
Button botao[]= new Button[num+1];
if(num!=0)
{
for(int i=1; i<=num; i++)// cria os botões de cada personagem
{
nome = informaçõesdepersonagem.getString("nome_personagem"+(i+1), "Nenhum");
resumo = informaçõesdepersonagem.getString("raça_personagem"+(i+1), "Nenhum")+ " " + informaçõesdepersonagem.getString("classe_personagem"+(i+1), "Nenhum") + " " + Integer.toString(informaçõesdepersonagem.getInt("nivel_personagem"+(i+1), 0));
botao[i]=new Button(this);
botao[i].setText(nome+" "+resumo);
botao[i].setId(i);
botao[i].setOnClickListener(this);
layout.addView(botao[i]);
}
}
botao[0]=new Button(this);
botao[0].setText("Criar Novo");
botao[0].setId(1);
botao[0].setOnClickListener(this);
layout.addView(botao[0]);
}
#Override
public void onClick(View view)
{
Intent nova = new Intent (this, CriadordePersonagem.class);
startActivity(nova);
}
}
You seem to add a bunch of buttons to your LinearLayout, but you don't actually add layout to your view hierarchy. Can you try calling setContentView(layout) and clicking on the buttons then?
I think you can use this example :-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button:
startActivity(new Intent(this, Doctor.class));
break;
}
}
}
Would be useful to see your XML layout, but my first guess is that you didn't add the layout anywhere.
Your layout seems to be R.layout.activity_listade_personagens so if you want to edit it, you should get it instead of creating a new one:
setContentView(R.layout.activity_listade_personagens);
LinearLayout layout = findViewById(R.layout.activity_listade_personagens);
layout.setOrientation(LinearLayout.VERTICAL);
// Rest of your code
In onClick method, you did not get Id of which view be clicked. So android cannot know onClick for what view. You should do that:
#Override
public void onClick(View view){
switch (view.getId()){
case R.id.button:
Intent nova = new Intent (this, CriadordePersonagem.class);
startActivity(nova);
break;
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(OneActivity.this, TwoActivity.class);
startActivity(intent);
}
});

Last Button added Dictatorship in android

I know that title is fancy but this is going on in my android app.
I am storing the names of websites which user wants to open in an arraylist of strings. Then an array of buttons is made whose size depends on the size of arraylist.
Then I set the text of the buttons using the arraylist. This works perfectly and all the buttons are assigned correct text.
Then I set the on click listeners of each button and create an implicit intent to open the web site.
Problem that is occuring is that despite the fact the text of the buttons are set perfectly , There is some problem with the listener because no matter which button i press, always the site of last button is opened and hence last button dictatorship.
Here is my code.
package com.example.hp.myproject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created #CreativeLabsworks
*/
public class Act3 extends Activity
{
LinearLayout ll1; Button[] bt_arr; String s;
LinearLayout.LayoutParams params1;
ArrayList<String> sites;TextView t1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent=getIntent();
sites= intent.getStringArrayListExtra("arraylist");
/*Creating a linear layout to hold editTexts*/
ll1=new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
/*set the width and height of the linear layout*/
params1=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
setContentView(ll1, params1);
/*Initializing the button array*/
bt_arr = new Button[sites.size()];
/*Initialize each button*/
for(int i=0;i<bt_arr.length;++i)
{
bt_arr[i] = new Button(this);
ll1.addView(bt_arr[i]);
}
setText();
attach_listeners();
}
public void attach_listeners()
{
/*this function attaches listeners with all buttons in the button array*/
for(int i=0;i<bt_arr.length;++i)
{
s=sites.get(i);
bt_arr[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
}
});
}
}
public void setText()
{
/*This function sets the text of the various buttons*/
int j;
for(int i=0;i<bt_arr.length;++i)
{
j=sites.get(i).indexOf(".com");
bt_arr[i].setText(sites.get(i).substring(4,j));
}
}
}
The problem that you have is that
s=sites.get(i);
S is being set by the last element.
Whenever a button is clicked it is taking the S from the last element since S is outside the onClickListener instance that you have.
I would suggest to save the url in the Button tag and then use it When the button is clicked.
for (int i = 0; i < bt_arr.length; ++i) {
s = sites.get(i);
bt_arr[i].setTag(s);
bt_arr[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String website = (String)v.getTag();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://" + website));
startActivity(i);
}
});
}
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
Maybe you do not write i.setclass()?

How to switch text view from one thing to the next when a button is clicked - Android

Below is my main activity file. I am stuck with the bottom area (commented out). I want to make it so that when I hit button b1, the text changes from what it is for default. So say it says "hello" by default, I want to switch the text to something like "how are you" when you press button b1. I have tried many things, but I always get errors. Can someone help me?
package com.wdmc85.donottouch;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DoNotTouchActivity extends Activity
implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) this.findViewById(R.id.b1);
b1.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.b1:
//WHAT DO I PUT IN HERE?? I WANT IT SO WHEN YOU HIT BUTTON B1, THE
//TEXT CHANGES FROM WHAT IT IS FOR DEFAULT. SO SAY IT SAYS "HELLO"
//AS DEFAULT, HOW DO I MAKE IT SO WHEN YOU PRESS BUTTON B1 THE TEXT
//CHANGES FROM "HELLO" TO "HOW ARE YOU?" I HAVE TRIED ALL SORTS OF
//THINGS BUT NOTHING HAS WORKED
break;
}
}
}
if want to change text of the button itself
switch(v.getId())
{
case R.id.b1:
Button b1 = (Button) v;
b1.setText("HOW ARE YOU?");
break;
}
if want to change text of the any other Textview
switch(v.getId())
{
case R.id.b1:
TextView tv = (TextView ) this.findViewById(R.id.<tvid>);
tv .setText("HOW ARE YOU?");
break;
}
You should use below method to change text of text view.
textView.setText("your text");
reference link is >> textview>>setText()
can use same for button and other views.

How the detect the "edittext" box whether it is nothing in Android?

I want to program a function that the toast exist when there is nothing
in the "edittext" box (id / password), but it dosen't work.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.text.Editable;
public class Test extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
EditText id = (EditText) findViewById(R.id.id);
EditText pwd = (EditText) findViewById(R.id.pwd);
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v){
if(Str_id==null || Str_pwd == null){
Toast.makeText(Test.this, "Please Enter User ID / Password", Toast.LENGTH_LONG).show();
}
});
}
}
move the following lines inside onClick and try:
Str_id = id.getText();
Str_pwd = pwd.getText();
EDIT: Move
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
inside onClick().
I do not recommend toasting a message that a field is required. You're better off just giving the EditText focus, this focus tells the user that this field is required. Its less information on the screen and its subtle, which is important. You don't want to disturb the user too much.
The idea is...
When the submit button is clicked, check the EditTexts if any of them are empty, notify the user through requesting focus, also make sure your UI tells them before hand that the fields required. The hint of the EditText works well for this.

Categories

Resources