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()?
Related
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;
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);
}
});
So I'm new to android development and I'm having a bit a of a trouble.
I'm developing an an app which is going to have a similar background every time but imports a new image every time the user touches the screen.
HOWEVER my problem is that I'm having an issue right now in which I'm trying to load a new activity when a user click a button, 1) I followed one tutorial which had me use XML to add the button and program MAIN_activity to to switch to second_Activity using setcontent(R.layout.main_Activity) and works fine.
2) I also started another tutorial which had me use setContent(layout1) where layout one is in fact a LinearLayout which you addView(stuff) such as a button and program it to switch the second activity, but I'm failing terribly.
long story short, using this line setcontent(R.layout.main_Activity) overrides the setContent(layout1) info and I cant combine them. In addition I dont know how to make a button and click to switch activity except using the first method, I'm open to suggestions.
package self.name.firstandroidprogram;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton, switchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout1 = new LinearLayout(this);
number1Text = new EditText(this);
number2Text = new EditText(this);
calcButton = new Button(this);
switchButton = (Button)findViewById(R.id.button1);
////////////////////////////////////////////////////////////////////////BUTTON ACTIVITY SWTICH
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Class2.class);
startActivity(intent);
}
});
////////////////////////////////////////////////////////////////////////////
answerText.setText("0");
calcButton.setText("X");
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
layout1.addView(answerText);
layout1.addView(switchButton);
setContentView(R.layout.activity_main);// Works
// setContentView(layout1) failes when i run
}
I am not sure, but try it
public class MainActivity extends Activity {
LinearLayout layout1;
EditText number1Text;
EditText number2Text;
Button calcButton, switchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout1 = new LinearLayout(this);
// Do it before adding views in it.
setContentView(layout1);
number1Text = new EditText(this);
number2Text = new EditText(this);
calcButton = new Button(this);
switchButton = (Button)findViewById(R.id.button1);
////////////////////////////////////////////////////////////////////////BUTTON ACTIVITY SWTICH
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Class2.class);
startActivity(intent);
}
});
////////////////////////////////////////////////////////////////////////////
answerText.setText("0");
calcButton.setText("X");
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
layout1.addView(answerText);
layout1.addView(switchButton);
// setContentView(R.layout.activity_main);// Works
}
You can set LinearLayout as your main layout. When user clicks the switch button, you need to set background of the LinearLayout
activity_main.xml :
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/main"
android:background="#drawable/default"
>
<!-- put your Button here switch button -->
</LinearLayout>
MainActivity.java :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchButton = (Button)findViewById(R.id.button1);
LinearLayout lv1 = (LinearLayout) findViewById(R.id.main);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// we have reference of LinearLayout as lv1
// we will change background of lv1 here when user clicks
lv1.setBackgroundResource(<your_new_background_image_id>);
}
});
<your_new_background_image_id> can be fetched from /res/drawable/ folder. You store 10-20 images of small size in drawable and rename them with similar name i.e. image1, image2 etc
When setting them as background, you can code like :
int[] imageArray = {R.drawable.image1, R.drawable.image2,...}
lv1.setBackgroundResource(imageArray[(i++)%10]);
If you are creating view programatically you have to set each view LayourParameters using view.setLayoutParams()
Try this
layout1 = new LinearLayout(this);
EditText number1Text = new EditText(this);
EditText number2Text = new EditText(this);
Button calcButton = new Button(this);
calcButton.setText("X");
//impt : width=MATCH_PARENT and height=MATCH_PARENT
layout1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
layout1.setOrientation(LinearLayout.VERTICAL); //setting LL orientation
layout1.addView(number1Text);
layout1.addView(number2Text);
layout1.addView(calcButton);
setContentView(layout1);
I'm working on an app that's main layout consists of a row of buttons on top of a LinearLayout which holds a column of EditTexts. I've created a Form object to hold all the values to be displayed in the Editexts, and there will be a Form object for every button in the row. Each button is clicked to change the form's data to show the values held in each Form object. I have the Form objects kept in a List called formList, so that I can access each one when the corresponding button is pressed.
When I click one of the buttons, I want the EditText values to change to a different set of values which correspond to that button. But when I click these buttons, the previously entered values do not show up.
When I click Next Drink, it dynamically creates a button as well as a Form object, and clears the EditTexts so that it looks like a new form has been created for the new button. I should then be able to add strings to the EditTexts, and the strings should be stored in the Form object so that if I click that button again, the Form object will fill the EditTexts with the strings stored in that object.
So, if I click button 3 after having clicked button 2, it should set the text of each EditText to the values contained in the the third Form object, which contains strings for Name, Volume, Percentage, Price, and Quantity.
My problem is the values do not show up in the EditTexts after clicking a button. So if I click Button 3, the values from Form 3 don't show up. I've been at this for a long time and cannot figure out why, so I'd really appreciate any help. Here is the activity:
package com.example.DrinkApp;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
//view variables
final Button newDrink[] = new Button[100];
LinearLayout drinkSelectionContainer;
EditText name;
EditText vol;
EditText perc;
EditText pri;
AutoCompleteTextView quant;
//counters
int numOfDrinks = 0;
int selectedForm = 0;
//array to hold all Form objects.
List<Form> formList = new ArrayList<Form>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get views
drinkSelectionContainer = (LinearLayout) findViewById(R.id.drinkSelectContainer);
name = (EditText) findViewById(R.id.etName);
vol = (EditText) findViewById(R.id.etVol);
perc = (EditText) findViewById(R.id.etPerc);
pri = (EditText) findViewById(R.id.etPrice);
quant = (AutoCompleteTextView) findViewById(R.id.etQuantity);
Button saveDrink = (Button) findViewById(R.id.bSaveForm);
Button nextDrink = (Button) findViewById(R.id.bNextDrink);
Button crunkOut = (Button) findViewById(R.id.bCalc);
///////////////////////// next drink method
addNewDrinkButton();
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
formAdd();
}
#Override
public void afterTextChanged(Editable editable) {
// mNames.add(selectedForm, name.getText().toString());
// newDrink[selectedForm].setText(name.getText().toString());
}
});
nextDrink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewDrinkButton();
}
});
}
//listener for drink select buttons. when button is clicked, it finds out which one it was,
//and then displays the correct values.
public View.OnClickListener drinkSelectListener = new View.OnClickListener() {
public void onClick(View v) {
selectedForm = v.getId();
Form form = formList.get(selectedForm);
Button v1 = (Button) findViewById(selectedForm);
v1.setText(" " + selectedForm);
// Do something depending on the value of the tag
Log.v("My Logs:", "Select Drink " + selectedForm + " button pressed.");
Log.v("My Logs:", "Drink " + selectedForm + " name: " + form.getName());
formDisplay(form);
}
};
private void addNewDrinkButton() {
formClear();
formAdd();
numOfDrinks++;
selectedForm = numOfDrinks;
Log.v("My Logs:", "Next Drink button pressed.");
newDrink[numOfDrinks] = new Button(getBaseContext());
newDrink[numOfDrinks].setOnClickListener(drinkSelectListener);
newDrink[numOfDrinks].setId(numOfDrinks);
newDrink[numOfDrinks].setText("" + selectedForm);
newDrink[numOfDrinks].setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// name.setText("Drink " + (numOfDrinks+1));
drinkSelectionContainer.addView(newDrink[numOfDrinks]);
//TODO: save form values, clear edit texts, and create new variables for edittexts.
}
void formAdd(){
Form tempForm = new Form();
tempForm.setId(selectedForm);
tempForm.setName(name.getText().toString());
tempForm.setVolume(vol.getText().toString());
tempForm.setPercentage(perc.getText().toString());
tempForm.setPrice(pri.getText().toString());
tempForm.setQuantity(quant.getText().toString());
formList.add(selectedForm, tempForm);
}
void formDisplay(Form form){
name.setText(form.getName());
vol.setText(form.getVolume());
perc.setText(form.getPercentage());
pri.setText(form.getPrice());
quant.setText(form.getQuantity());
}
void formClear(){
name.setText("");
vol.setText("");
perc.setText("");
pri.setText("");
quant.setText("");
}
}
!Here's the main layout. So if I click button 4, I want to have the EditTexts display the values
I'd entered the last time I'd clicked on it. It's really very simple.
You are calling formClear() before formAdd()?
Setting EditText values on button press
edittext.setText("nexteditText");
edittext.requestfocus();
I have a image button and i want that image button when pressed it changes the text in a textbox and it changes a image to a different image how do i do this?
You need an OnClickListener: http://developer.android.com/reference/android/view/View.OnClickListener.html
When clicked your text can be changed with (something like) text.setText("new text");
I'll find a link in a minute which will help more.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class TestesetetActivity extends Activity {
/** Called when the activity is first created. */
TextView textview = null;
ImageButton buttonResume = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonResume = (ImageButton) findViewById(R.id.imageButton1);
textview = (TextView) findViewById(R.id.textView1);
buttonResume.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textview.setText("test");
buttonResume.setImageResource(R.drawable.push_pin);
}
});
}
}
In the xml file, you can give the image an onClick attribute, which calls a method in the java class, which calls the xml resource, and passes it the id of the ImageView.
In that java method, you can use
((ImageView) view).setImageResource(int id)
or
setImageDrawable(Drawable d)
to change the image.
Likewise, you can identify the TextView you wish to change using, for example,
TextView tv = (TextView) findViewById( id )
with id being the id of the TextView you wish to find.
You can then use
tv.setText(String s)
to set the text in this view.
In your OnClickListener, you could use
button.setBackgroundResource(YOUR_BUTTON_ID);
or
button.setImageResource(YOUR_BUTTON_ID);