XML / Java Button Click to change TextView - java

I am realitavely new to Java coding and am trying to use a button press (in an Android App) to update a text view. The code I am currently using is causing my app to crash whenever I try to press the button.
Here is my XML
<LinearLayout>
<TextView
android:id="#+id/myTextView_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="calculateNewNumber"
android:text="Calculate New Number" />
</LinearLayout>
And Here is my Java
package com.example.android.myapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int startNumber = 0;
public void calculateNewNumber(View view) {
startNumber = startNumber + 1;
display(startNumber);
}
private void display(int number) {
TextView myTextView = (TextView) findViewById(
R.id.myTextView_text_view);
myTextView.setText("" + number);
}
}
Thanks for any help you can give.

The code itself works fine so the problem must be with your XML, assuming you have provided it in full here.
Using this XML, your MainActivity code works fine for me.
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:id="#+id/myTextView_text_view"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="calculateNewNumber"
android:text="Calculate New Number" />
</LinearLayout>
</RelativeLayout>

Related

how do I add a reset button for my two TextViews in Android Studio

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="#+id/away"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="#string/away"
android:gravity="center"
android:textSize="20sp"/>
<TextView
android:id="#+id/score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="#string/_0"
android:textSize="20sp" />
<Button
android:id="#+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="50dp"
android:onClick="score1"
android:text="#string/score" />
<TextView
android:id="#+id/home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:text="#string/home"
android:textSize="20sp"
android:gravity="center"/>
<TextView
android:id="#+id/score2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginBottom="50dp"
android:text="#string/_0"
android:textSize="20sp" />
<Button
android:id="#+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="score2"
android:text="#string/score" />
<Button
android:id="#+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/reset"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textColor="#ff1100"/>
</LinearLayout>
I searched it on multiple websites but I still can't the answer. I also tried using the__setText("")it
didn't work as well as the the if() method. I have also tried the intent method also doesn't seem to
work, and many other codes , please help me because I am stuck at this bit , I know that it is simple but
I just can't find it. Thank you
The following codes will set the TextView score to blank when Button one is clicked
First approach
To use the android:onClick="score1" in your XML
Add this to your activity
TextView mTvScore1 = (TextView) findViewById(R.id.score)
public void score1(View v) {
mTvScore1.setText("");
}
Second approach
Button mBtn = (Button) findViewById(R.id.one)
TextView mTvScore1 = (TextView) findViewById(R.id.score)
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTvScore1.setText("");
}
});
Activity code
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 {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mTvScore1 = (TextView) findViewById(R.id.score);
Button mBtn = (Button) findViewById(R.id.one);
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
score1(v);
}
});
}
public void score1(View v) {
mTvScore1.setText("");
}
}

Add many CardViews with onclick method programmatically

I'm still new to the Android and I want to add a CardView to the activity each time a button is clicked. The CardView has text on it and a background image. I already have the XML file that can add this, but because I want to be able to add more than one, I can't use <include.>. The first image is when the button is clicked once and the second is when the button is clicked 3 times. I already have the onClick for the TextView that says "Click To Add Block" and the XML for the CardView, but I can't make it so that you can add them and change the text in the TextView in each and every one of them. I also can't seem to find a way to programmatically add an onClick listener to the programmatically created CardView. Later down the line, I would also like to be able to delete the CardView from a click of a button too.
Here is the CardView XML file (Before it was inside a Relative Layout)
<androidx.cardview.widget.CardView
android:id="#+id/cardviewClassesBlock1"
android:layout_width="330dp"
android:layout_height="75dp"
android:layout_marginTop="90dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background">
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:textSize="22sp"
android:fontFamily="#font/amiko_semibold"
android:textColor="#color/white"
android:text="Block A"/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_marginStart="10dp"
android:layout_below="#+id/textviewClassesBlock1"
android:background="#drawable/rounded_corner_edittext" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="5dp"
android:textColor="#color/white"
android:text="P - 0 | T - 0 | A - 0"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
I have created a sample project for You.
First You have to create a layout for Your CardView. In res/layout create card_base.xml. In this layout add:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp"
android:layout_margin="10dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background"
>
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:text="Block A"
android:textSize="22sp"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_below="#+id/textviewClassesBlock1"
android:layout_marginStart="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="5dp"
android:text="P - 0 | T - 0 | A - 0"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
This is basically Your CardView with small changes.
Next, in Your activity_main.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<Button
android:id="#+id/butAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Card"
/>
<Button
android:id="#+id/butDoSth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Do something"
/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
android:id="#+id/includedLayoutFirst"
layout="#layout/card_base"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
This is a starter (very simple) look of Your app. It has one button and one CardView which is already inserted.
Now in Your MainActivity.java paste this:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.cardview.widget.CardView;
public class MainActivity extends AppCompatActivity
{
private int starter = 66; //ASCII code for `B`
LinearLayoutCompat cards;
Button buttonAdd;
Button buttonDoSth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = findViewById(R.id.cards);
buttonAdd = findViewById(R.id.butAdd);
buttonDoSth = findViewById(R.id.butDoSth);
buttonAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CardView newCard = new CardView(MainActivity.this);
getLayoutInflater().inflate(R.layout.card_base, newCard);
TextView t = newCard.findViewById(R.id.textviewClassesBlock1);
String current = Character.toString((char) starter++);
t.setText("Block " + current);
newCard.setTag(current); //
cards.addView(newCard);
}
});
buttonDoSth.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
findBlockAndDoSomething("B");
}
});
}
private void findBlockAndDoSomething(String name)
{
Log.d("MyTAG", "CLICK");
for (int i = 0; i < cards.getChildCount(); i++)
{
CardView selected = (CardView) cards.getChildAt(i);
if (selected.getTag() != null && selected.getTag().toString().equals(name))
{
// do something. E.g change block name
TextView textViewClassesBlock1 = selected.findViewById(R.id.textviewClassesBlock1);
textViewClassesBlock1.setText("Block XXX");
return;
}
}
}
}
Result (starter code and with adding new CardView):

Android ID not found, when it is there

Android Studio is giving me errors in the Main Activity Java over unresolved symbols or id's. As far as I can see the id's refrenced in the java code exist.
In another app which used these same principles, it worked, I cross refrenced the two apps and could not find anything that stood out.
Here is my java code:
package com.example.android.quizapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
public class QuizMainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_main);
}
public void display(int value) {
TextView quantityTextView = findViewById(R.id.value_text);
quantityTextView.setText(value);
}
public void slider(View view){
SeekBar seekBar = (SeekBar)findViewById(R.id.i);
int Value = seekBar.getProgress();
EditText text = (EditText)findViewById(R.id.valueText);
String name = text.getText().toString();
text.setText(Value);
}
}
Here is my XML: (The id's are there)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.quizapplication.QuizMainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quiz"
android:textAlignment="center"/>
<TextView
android:id="#+id/question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="What is you favorite color?"
android:textAlignment="center"
android:paddingTop="20dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#000000"
android:layout_below="#+id/title"
/>
<TextView
android:id="#+id/value_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test"
android:textAlignment="center"
android:layout_alignParentBottom="true"
android:layout_marginBottom="300dp"/>
<SeekBar
android:id="#+id/i"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="146dp"
android:onClick="slider"/>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
Try adding this:
import com.example.android.quizapplication.R;

Android second activity is ignoring xml file

In my second activity I have a textview that is not responding to the changes in the xml file, I'm trying to change the text size and alignment but nothing I do works, I can only guess that it because in the java file for the activity I have a .setText method changing the text of the textView and that's causing the program to ignore the xml file, my question is how to I now change the text size?
Java code:
package com.powermedia.rps;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Joshua on 2/17/2015.
*/
public class ResultActivity extends ActionBarActivity implements View.OnClickListener
{
#Override
public void onCreate(Bundle savedInstanceState)
{
Button playAgainBtn;
TextView resulttv;
String userChoice = "";
String AndroidChoice = "";
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
playAgainBtn = (Button)findViewById(R.id.PlayAgain);
playAgainBtn.setOnClickListener(this);
resulttv = (TextView)findViewById(R.id.textView);
userChoice = this.getIntent().getExtras().getString("userChoice");
AndroidChoice = this.getIntent().getExtras().getString("AndroidChoice");
resulttv.setText("User chose " + userChoice + ", Android chose " + AndroidChoice +
"\n" + getWinner(AndroidChoice, userChoice) + " won!");
}
XML Code:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#ffd3d3d3"
android:id="#+id/test">
<Space
android:layout_width="fill_parent"
android:layout_height="24dp"
android:id="#+id/space3"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="95dp"
android:layout_height="wrap_content"
android:text="Play Again"
android:id="#+id/PlayAgain"
android:layout_below="#+id/space3"
android:layout_centerHorizontal="true"
android:background="#ff959595" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textStyle="bold"
android:text="Tell who won or tie"
android:textAlignment="center" />
Change:
android:textSize="20dp"
to:
android:textSize="20sp"

java.lang.RuntimeException: Unable to start activity and skipping frames

I am working on an android Temperature converter app(which does not work). At first I saw this message on LogCat
the application may be doing too much work on its main thread
I then removed the code that was never used.
Now, this is the error:
java.lang.RuntimeException: Unable to start activity
Code: Main_Activity.java
package com.example.tempconverter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editCelsius = (EditText) findViewById(R.id.editCelsius);
final EditText editFahrenheit = (EditText) findViewById(R.id.editFahrenheit);
Button buttonConvert =(Button)findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double celsius = Double.valueOf(editCelsius.getText().toString());
double fahrenheit = (celsius * 9)/5 +32;
editFahrenheit.setText(String.valueOf(fahrenheit));
}
});
}
}
The code in fragment_main.xml
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tempconverter.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textCelsius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="55dp"
android:text="Celsius"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="hardcodedtext" />
<EditText
android:id="#+id/editCelsius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textCelsius"
android:layout_marginLeft="52dp"
android:layout_toRightOf="#+id/textCelsius"
android:ems="7"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textFahrenheit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editCelsius"
android:layout_marginTop="31dp"
android:text="Fahrenheit"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="hardcodedtext" />
<Button
android:id="#+id/buttonConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editFahrenheit"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:text="Convert"
tools:ignore="hardcodedtext" />
<EditText
android:id="#+id/editFahrenheit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editCelsius"
android:layout_alignTop="#+id/textFahrenheit"
android:ems="7"
android:inputType="number" />
</RelativeLayout>
this is a part of the LogCat now ...
https://drive.google.com/file/d/0Bxd5Rg3QFBfbdkZULWxNUTVrV2M/edit?usp=sharing
Apparently, you are inflating the wrong view. You've got a RuntimeException, and you should have a NullPointerException, because the setContentView try to set (and methods findViewById try to find views inside) the wrong layout as:
setContentView(R.layout.activity_main);
whereas all your EditTexts, TextViews and Buttons are in fragment_main.xml.
Try to set the content view as follow:
setContentView(R.layout.fragment_main);
or, rename fragment_main.xml to activity_main.xml.
Update from comments:
These kinds of errors "Couldn't load memtrack module' occur with some devices with emulator. To avoid this, always test with multiple devices (real or not).

Categories