Why can't I set text to an Android? - java

``Hi, i have a calculator application and on the screen there are buttons for number and add, multiplication, clean, substruction and division buttons. But when I open and click buttons they couldnt make change on editText. When i write number on keybord, it edited. How can i fix it?
Here is full of my java code
private EditText screen; //textbox screen
private float numberBf; // save screen before pressing button operation
private String operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (EditText) findViewById(editText);
int idList[] = {R.id.button0,R.id.button,R.id.button2,R.id.button3,R.id.button4,
R.id.button5,R.id.button6,R.id.button7,R.id.button8,R.id.button9, R.id.buttonAdd,R.id.buttonMul,
R.id.buttonC, R.id.buttonDiv,R.id.buttonDot,R.id.buttonEq,R.id.buttonSub};
for(int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//new class
private class ButtonClickListener implements View.OnClickListener {
public void onClick(View view){
switch (view.getId()){
case R.id.buttonC: //clear button
screen.setText("0");
numberBf = 0;
operation = "";
break;
//adding function
case R.id.buttonAdd:
mMath("+");
break;
case R.id.buttonSub:
mMath("-");
break;
case R.id.buttonMul:
mMath("*");
break;
case R.id.buttonDiv:
mMath("/");
break;
case R.id.buttonEq:
mResult();
break;
default:
String num = ((Button) view).getText().toString();
getKeyboard(num);
break;
}
}
}
public void mMath(String s){
numberBf = Float.parseFloat(screen.getText().toString()); //save the screen
operation = s; //save operation
screen.setText("0"); //clear screen
}
public void mResult(){
float numberFl = Float.parseFloat(screen.getText().toString());
float result = 0;
if(operation.equals("+"))
result = numberFl + numberBf;
if (operation.equals("-"))
result = numberBf - numberFl;
if(operation.equals("*"))
result = numberFl * numberBf;
if (operation.equals("/"))
result = numberBf / numberFl;
screen.setText(String.valueOf(result));
}
public void getKeyboard(String str){
String scrCurrent = screen.getText().toString();
if (scrCurrent.equals("0"))
scrCurrent = "";
scrCurrent = str;
screen.setText(str);
}
}
and some part of my activity_main xml code, number 9 button and text place is
activity_main :
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:text="0"
android:layout_below="#+id/button0"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="57dp"
android:gravity="right"
android:editable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="#+id/button9"
android:layout_below="#+id/button5"
android:layout_toRightOf="#+id/button5"
android:textStyle="bold" />
please help me thank you

screen = (EditText) findViewById(editText);
The parameter editText is not a valid Resource Identifier. In XML you should have
<EditText ...
android:id="#+id/thetextid">
And then in your code you should have
screen = (EditText) findViewById(R.id.thetextid);

This should make it work:
screen = (EditText) findViewById(R.id.editText);

You haven't instantiated the button click listener. Add
btnClick = new ButtonClickListener();
before any of the setOnClickListener(btnClick) calls.

Related

A variable holds an unexpected value

I'm building a module for checking an answer in my Android java app and it doesn't work. While debugging it shows that the variable holds a value that is completely unexpected for it to hold. Could please someone explain what the problem might be? Here is the module:
private void QuizOperations() {
Toast.makeText(QuizActivity.this,"quizOperation", Toast.LENGTH_SHORT).show();
answered = true; // when the question is already answered Set bool to true
RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
int indexofchild =rbGroup.indexOfChild(rbSelected) +1;
int answerNr = indexofchild +1;
checkSolution(answerNr,rbSelected);// method checks if the answer that is selected by the user corresponds to the answer in the database
}
The intended way was rbselected getting the index of the RadioButton pressed by the user, and than answerNr gets the index of this button as int. Than it passes in to the checksolution() function which checks if the AnswerNr corresponds to the right answer in the database. However, while debugging answerNr holds the value of 5 whichever button I press.
Debug screenshot
Let me know if any additional code needed. Thanks a lot
Here is a very minimalistic example on how to detect the view is being pressed, set/get id from tag.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#333333">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton1"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton2"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton3"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private String[] answers = {
"January",
"February",
"March",
};
private RadioButton rb1, rb2, rb3;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rb1 = findViewById(R.id.radioButton1);
rb2 = findViewById(R.id.radioButton2);
rb3 = findViewById(R.id.radioButton3);
rb1.setTag("0");
rb2.setTag("1");
rb3.setTag("2");
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
final int index = Integer.parseInt((String)view.getTag());
switch(view.getId()) {
case R.id.radioButton1:
rb2.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
rb1.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
rb1.setChecked(false);
rb2.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
}
}
}

Android - Radiobutton click event to go to new activity

I would like to do something like a small selection form.
I would like to do a click event where if I select one of the first radiogroup and another one of the second it takes me to a new activity.
I got two radiogroups with two radiobuttons inside each.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/physic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="physic"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/math"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="math"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/theories"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="theories"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/problems_solving"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="problem solving"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
I declared my buttons and tried to use onRadioButtonClicked like below:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.math:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showFirstWord("math problem resolution");
break;
case R.id.theories:
if (checked)
showSecondWord("math theories");
break;
}
break;
case R.id.physic:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showThirdWord("physic problem solving");
break;
case R.id.theories:
if (checked)
showFourthWord("physic theories");
break;
}
break;
}
}
I want the strings in the functions to appear in a text view in the other activities like below:
private void showFirstWord (String text) {
Intent first_word = new Intent(this, FirstActivity.class);
first_word.putExtra("key", text);
startActivity(first_word);
}
private void showSecondWord (String text) {
Intent second_word = new Intent(this, SecondActivity.class);
second_word.putExtra("key", text);
startActivity(second_word);
}
private void showThirdWord (String text) {
Intent third_word = new Intent(this, ThirdActivity.class);
third_word.putExtra("key", text);
startActivity(third_word);
}
private void showFourthWord (String text) {
Intent fourth_word = new Intent(this, FourthActivity.class);
fourth_word.putExtra("key", text);
startActivity(fourth_word);
}
I tried to follow this page from Android developers but I'm still not sure what to do with it: https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/ui/controls/radiobutton.html
My method doesn't seem to be correct ass I can't get the strings to appear in the other activities. Is my reasonning ok for now or should I study another method?
Thanks :)
You can simplified your code onRadioButtonClicked just create first a String variable called subjectSelected.
then:
private String subjectSelected = "";
public void onRadioButtonClicked(View view) {
RadioButton radioButton = (RadioButton) view;
switch(view.getId()) {
case R.id.math:
subjectSelected = radioButton.getText().toString();
break;
case R.id.physic:
subjectSelected = radioButton.getText().toString();
break;
case R.id.problems_solving:
if (subjectSelected.equals("math")) {
showFirstWord ("math problem resolution");
} else if (subjectSelected.equals("physic")) {
showThirdWord("physic problem solving");
}
break;
case R.id.theories:
if (subjectSelected.equals("math")) {
showSecondWord("math theories");
} else if (subjectSelected.equals("physic")) {
showFourthWord("physic theories");
}
break;
}
}
and to display the text you pass to another activity. Use a Bundle to get the value of your key.
e.g.:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Bundle bundle = getIntent().getExtras();
String key = bundle.getString("key");
TextView textView = (TextView) findViewById(R.id.textView1); // Replace the textView1 with the id you set to your textview.
textView.setText(key);
}
}
You can copy the codes of your FirstActivity and paste to your SecondActivity, ThirdActivity and FourthActivity to get the key.
String str; // store the text corresponding to the RadioButton which is clicked
switch(view.getId()) {
case R.id.radioButton1:
if (checked)
str = "button1Text";
break;
case R.id.radioButton2:
if (checked)
str = "button2Text";
break;
case R.id.radioButton3:
if (checked)
str = "button3Text";
break;
}
Intent intent = new Intent(this, WinderDTActivity.class);
intent.putExtra("radioChosen", str); // pass "str" to the next Activity

Android Studio change background color multiple times with 1 button click

I am brand new to Android Studio and am trying to figure out how to change the background color of my start up app.
The moment the app loads, I see a button on the screen, and when I click, it goes to the color red.
What I want is when you click the button, it goes from red to green to blue than back to red.
However, I keep getting these errors:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
Error:(72, 9) error: class, interface, or enum expected
Main Activity XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Color"
android:onClick="onChangeColor"/>
</LinearLayout>
Test Activity Java Code:
private int colorIndex = 1;
public void onChangeColor(View view) {
int color;
if(colorIndex==0) {
color = Color.RED;
colorIndex = 1;
}else if(colorIndex==1) {
color = Color.GREEN;
colorIndex = 2;
}else {
//colorIndex = 2
color = Color.BLUE;
colorIndex = 0;
}
View layout = findViewById(R.id.layout);
layout.setBackgroundColor(color);
}
public class TestActivity extends AppCompatActivity {
View view;
//declare a string variable in java a class
//private var colour = "green";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View layout = findViewById(R.id.layout);
layout.setBackgroundColor(Color.RED);
view= this.getWindow().getDecorView();
view.setBackgroundResource(R.color.gray);
}
public void goRed(View v)
{
//if (colour == "green"){
view.setBackgroundResource(R.color.red);
//colour = "red";
//}
}
}
To give you a excellent help, it will be necessary to see you code.
Any way if i andersted you right maybe this will help you :
On your xml layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Color"
android:onClick="onChangeColor"/>
</LinearLayout>
On your activity :
private int colorIndex = 1;
public void onChangeColor(View view) {
int color;
if(colorIndex==0) {
color = Color.RED;
colorIndex = 1;
}else if(colorIndex==1) {
color = Color.GREEN;
colorIndex = 2;
}else {
//colorIndex = 2
color = Color.BLUE;
colorIndex = 0;
}
View layout = findViewById(R.id.layout);
layout.setBackgroundColor(color);
}
On you onCreate in the activity
View layout = findViewById(R.id.layout);
layout.setBackgroundColor(Color.RED);
If I understood correctly what you want is, to transition over a series of colours over time, and each colour lasting for some 1-2 seconds. You can use Android's default CountDownTimer.
Keep Your xml layout same.
In your Activity:
public class TestActivity extends AppCompatActivity {
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout)findViewById(R.id.layout);
layout.setBackgroundColor(Color.RED);
}
public void onChangeColor(View view) {
// start your timer on button click
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
changeBackground(3-millisUntilFinished/1000);
}
}.start();
}
private void changeBackground(int colorIndex){
int color;
if(colorIndex==1) {
color = Color.GREEN;
}else if(colorIndex==2) {
color = Color.BLUE;
}else {
color = Color.RED;
}
layout.setBackgroundColor(color);
}
}
Hope this might help. If I misunderstood something please comment.
Edit: I typecasted View to LinearLayout

Floating button setOnClickListener not gets called in Android

I want to integrate movable floating button same like "WhatsApp" Application When open, it displays hike floating button with motion. And also working click event.
I used with default OnTouch event it's working but I can't apply Click event on floating button. How can I apply both Click and touch event ?
Thanks in advance!
home.xml
<RelativeLayout
android:id="#+id/rl_parent_floating"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible">
<RelativeLayout xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="#+id/rl_floating_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp">
<TextView
android:id="#+id/txtCartCount"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignRight="#+id/fab"
android:layout_alignTop="#+id/fab"
android:background="#drawable/cart_gold_circle"
android:gravity="center"
android:singleLine="true"
android:text="2"
android:textColor="#android:color/white"
android:textSize="8sp" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:src="#drawable/ic_floating_cart"
fab:fab_colorNormal="#color/header_color_red"
fab:fab_colorPressed="#color/colorPrimaryDark"
fab:fab_colorRipple="#color/gold_color" />
</RelativeLayout>
</RelativeLayout>
Home.java
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
mRrootLayout = (ViewGroup) findViewById(R.id.rl_floating_button);
rl_floating_button = (RelativeLayout) findViewById(R.id.rl_floating_button);
rl_parent_floating = (RelativeLayout) findViewById(R.id.rl_parent_floating);
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(mActivity, Cart.class);
startActivity(mIntent);
}
});
mFloatingActionButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
view.setLayoutParams(layoutParams);
break;
}
mRrootLayout.invalidate();
return true;
}
});
Use SimpleOnGestureListener & GestureDetector class to get single tap on screen instead of using Interface setOnclickListner as it may not work with ontouchListner
private class SingleTapDetector extends SimpleOnGestureListener{
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
}
and then in onCreate method initialize GestureDetector like this
gestureDetector=new GestureDetector(this,new SingleTapDetector());
Now, check in OnTouchListener of floating bubble , if single tap is detected on floating button
Code
mFloatingActionButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
// code for single tap or onclick
// pass your intent here
} else {
switch(event.getAction()){
// code for move and drag
// handle your MotionEvents here
}
return true;
}
});
Hope this will help you.

Button properties won't change

So I have an android app (java in Eclipse) and I want to change the text of some buttons on a keyboard through a shift method. I implemented the same code as I did to change a textview text, the same as everyone says to on similar questions, but for some reason it WILL NOT work. For some reason, after testing other button functions, I've determined that there's something it doesn't like about me changing ANY property of the button. Tried cleaning the project, didn't help. Keep getting an invocation exception. Here is relevant code:
public class MainActivity extends Activity {
boolean shift = true;
static Vector<String> answer = new Vector<String>(1, 1);
static int ansLength = 0;
private TextView answerbox;
private Button a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeButtons();
setContentView(R.layout.activity_main);
answerbox = (TextView) findViewById(R.id.answerbox);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void initializeButtons() {
a = (Button) findViewById(R.id.a);
}
public void typeKey(View sender) {
Button pressed = (Button) sender;
answer.add(ansLength, (String) pressed.getText());
//answerbox.setText("test string");
ansLength++;
StringBuilder stringBuilder = new StringBuilder();
for (String string : answer) {
stringBuilder.append(string);
}
answerbox.setText(stringBuilder.toString());
}
public void backSpace(View sender) {
answer.remove(ansLength - 1);
ansLength--;
StringBuilder stringBuilder = new StringBuilder();
for (String string : answer) {
stringBuilder.append(string);
}
answerbox.setText(stringBuilder.toString());
}
public void shift(View sender) {
if (shift == true) {
shift = false;
a.setText("l");
}
}
}
XML below:
<Button
android:id="#+id/a"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="A"
android:onClick="typeKey"/>
<Button
android:id="#+id/shift1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="^"
android:textSize="24sp"
android:onClick="shift" />
First, findViewById() in initializeButtons() should be called after setContentView() since there is no layout data in Activity object before setContentView()
Therefore, move the statement as following:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeButtons(); // Move this.
answerbox = (TextView) findViewById(R.id.answerbox);
Second, I'd like to advise you that do not use Vector in Java except in a special purpose. Use ArrayList instead. Vector in Java is slow, and almost deprecated. It is just available because of compatibility issues.
static Vector<String> answer = new Vector<String>(1, 1);
should be replaced to
static ArrayList<String> answer = new ArrayList<String>(1, 1);
If you have sync issues, (I don't think you have this issue now) then use Collections.synchronizedList() method: Why is Java Vector class considered obsolete or deprecated?

Categories

Resources