I used to have some experience with developing for android but I started up again after 6 months and forgot most of it. I am now using a macbook to do my developing on and had to set up Eclipse, the Android SDK and AVD all over again and I'm worried I messed something up.
When I start a new project with the default activity that displays "Hello World" on my screen the app runs fine. I then tried to put in two buttons that cause the text in a new TextView to change. But whenever I include the textView part I get a runtime error. When I comment it out, the app runs but obviously nothing happens. Based upon the tutorials I've been reading, this is the appropriate place and way to declare/create the textView but I can't figure out what's wrong. Any suggestions?
[Edit] I was messing around and found that I can make the mytext a field instead of a TextView and that worked. So in my onCreate(), I put
mytext = (TextField)findViewById(R.id.TextView1);
but that doesn't seem the right way to do things.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class IntroActivity extends Activity {
TextView myText = (TextView)findViewById(R.id.textView1);
//i've tried this with final added on to it as well (recommended by eclipse)
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setButtonClickListener();
}
private void setButtonClickListener() {
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myText.setText("Hello");
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// myText.setText("Goodbye");
}
});
}
}
This:
TextView myText = (TextView)findViewById(R.id.textView1);
should be separated. The declaration should be at the same place:
private TextView myText;
But the assignment should come only after setContentView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.textView1);
This is done since before setContentView, Dalvik doesn't know from which layout to take the view that matchs the id R.id.textView1
Related
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.
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);
}
});
I am new to android programming and am building a quiz app in which a question has 4 options and if the user clicks on one of the options the other options should be unclickable. I am currently able to only make a single button unclickable. Here is the java code.
package com.example.android.quiz;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//This method is called when option 1 of question 1 is selected
public void verifyQuestion1Option1(View view) {
Button QuestionOption1 = (Button) findViewById(R.id.question1_option1);
QuestionOption1.setBackgroundColor(getResources().getColor(R.color.solid_red));
question1Answer();
}
public void verifyQuestion1Option2(View view) {
Button Question1Option2 = (Button) findViewById(R.id.question1_option2);
Question1Option2.setBackgroundColor(getResources().getColor(R.color.solid_red));//solid red is not a predefined colour. It is declared in colors.xml
question1Answer();
}
public void verifyQuestion1Option3(View view) {
Button Question1Option3 = (Button) findViewById(R.id.question1_option3);
Question1Option3.setBackgroundColor(getResources().getColor(R.color.solid_green));
question1Answer();
}
public void verifyQuestion1Option4(View view) {
Button Question1Option4 = (Button) findViewById(R.id.question1_option4);
Question1Option4.setBackgroundColor(getResources().getColor(R.color.solid_red));//We call the getResources() method because R.colour.solid_red passed the id of the color not the actual colour value.
question1Answer();
}
public void question1Answer() {
TextView q1Answer = (TextView) findViewById(R.id.question1_answer);
String answer = "Rajinish Kumar is the current Chairman of SBI who took over after Arundhati Bhattacharya retired on 6 October.Shikha Sharma is the Managing Director and CEO of Axis Bank and Chanda Kochhar is the managing director and CEO of ICICI Bank";
q1Answer.setText(answer);
}
}
Either you can use a buttongroup which will have only 1 active button at any point of time or else, you need to disable other button programatically.
To disable the button you can use the following code:
Button button = (Button) findViewById(R.id.button);
button.setEnabled(false);
You can use .setEnabled(false); to disable a button. That button will grey out and does not respond to click events any more.
To disable all buttons, get the handle to each button and set them to disabled.
Button Question1Option1 = (Button) findViewById(R.id.question1_option1);
Button Question1Option2 = (Button) findViewById(R.id.question1_option2);
Button Question1Option3 = (Button) findViewById(R.id.question1_option3);
Button Question1Option4 = (Button) findViewById(R.id.question1_option4);
Question1Option1.setEnabled(false);
Question1Option2.setEnabled(false);
Question1Option3.setEnabled(false);
Question1Option4.setEnabled(false);
That way, all buttons of this question become disabled.
You can also come up with a solution where you save that the button is already pressed and ignore further click events. You could introduce some sort of variable bool question1answered = false; that is set to true as soon as the onClick event is fired.
public void verifyQuestion1Option4(View view) {
if (question1Answered == true) {return;}
question1Answered =true;
//Do the rest of your checks here
}
Two tips for for programming Java:
Java (in contrast to i.e C#) used lower letter variables as convention.
Button question1Option1 = (Button) findViewById(R.id.question1_option1); would be a better way.
If you have more questions, it would make sense to put them in some sort of array and reuse the same four buttons multiple times. That would save you much programming overhead and code rewrites if you have to change something. And it keeps the code cleaner.
I'm a noob Android studio programmer (this is hour 2 of learning!) and I expect this is a real rookie error I'm making!
I've got a Plain Text field in my application and I would like to set the text of this dynamically. I've given the plain text field the ID of: "resultText". Here's what I try;
public void calcnums(View v)
{
int x=firstNum + seondNum;
resultText.setText("Result: " + x);
}
For some reason I get 'resultText' highlighted in red and the hover over message is; Cannot resolve symbol 'resultText'.
I have the feeling that I'm doing something wrong by using the ID, but I'm lost!
Full code as suggested in comments;
import android.app.Application;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
public class AddNumbers extends AppCompatActivity {
private int firstNum;
private int seondNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_numbers);
}
public void calcnums(View v)
{
int x=firstNum + seondNum;
resultText.setText(String.format("Result: %d", x);
}
public void setNums(View v)
{
TextView tx= (TextView) findViewById(R.id.text);
Random r = new Random();
int x=r.nextInt(2) + 1; // r.nextInt(2) returns either 0 or 1
firstNum = x;
r = new Random();
x=r.nextInt(2) + 1;
seondNum = x;
num1.setText(""+firstNum);
num2.setText(""+seondNum);
}
}
It seems you need to declare the View resultText
Like,
EditText resultText = (EditText) findViewById(R.id.resultText);
Also make sure that the name you are using for the resultText View in xml is written correctly as provided in the method findViewById()
usually cannot resolve symbol means some problems in variable declarations.
I am too learning android and I stumbled upon this problem as well.
I don't have the whole snippet of your code.But the thing you might be missing is to point your EditText object to view in xml.
EditText resultText = (EditText) v.findViewById(R.id.result_edit_text);
<EditText
android:id="#+id/result_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/result_edit_text"
/>
Let's assume that we have an layout with an edittext
<EditText
android:id="#id/txt_user_email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text" />
It has an ID. In your actitivy you must find and cast the EditText as follow:
EditText txtUserEmail = (EditText) findViewById(R.id.txt_user_email);
txtUserEmail.setText("klaus.dieter#lusty-swingers.de");
You need to find your text view in onCreate(), like that:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_numbers);
TextView tx= (TextView) findViewById(R.id.text);
}
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);