Firing an action to be executed when a button is pressed - java

Just started learning Java for application development through Android Studio. Creating an application that collects the user's inputs of which include their Name and Age of which when a Submition button is clicked the output is a string based on their Age range. code below:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Action to the Button
Button BtnSubmit = findViewById(R.id.BtnSubmit);
BtnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TbName = "";
int TbAge =0;
String TxtOuput;
if (TbAge>0 && TbAge<=18)
{
TxtOuput = TbName + ("You Are Still A Child");
}
else if(TbAge>18 && TbAge<=64)
{
TxtOuput = TbName + ("You Are Grown");
}
else if(TbAge>64)
{
TxtOuput = TbName + ("You Are About To Die") + ("R.I.P");
}
}
});
}
}
Tried various methods from google, youtube and other sources but the application will not still execute an output.
Application layout/blueprint:

You are not getting your text fields values in a variable anywhere in code you have shared. Similarly you are not setting those values back to Status text field as well.
So it should be something like this:
If I assume you have firstEditText EditText View for name, secondEditText for age, and resultTextView for status, then your code would be something like below:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Action to the Button
Button BtnSubmit = (Button)findViewById(R.id.BtnSubmit);
EditText firstEditText = (EditText) findViewById(R.id.firstEditText);
EditText secondEditText = (EditText) findViewById(R.id.secondEditText);
TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
BtnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TbName = firstEditText.getText();
int TbAge = Integer.parseInt(secondEditText.getText().toString());
String TxtOuput;
if (TbAge>0 && TbAge<=18)
{
TxtOuput = TbName + ("You Are Still A Child");
}
else if(TbAge>18 && TbAge<=64)
{
TxtOuput = TbName + ("You Are Grown");
}
else if(TbAge>64)
{
TxtOuput = TbName + ("You Are About To Die") + ("R.I.P");
}
resultTextView.setText(TxtOuput);
}
});
}
}
Try this and let me know

AS per your question, you want user to add his name and age in the editText fields. When clicked on SUBMIT button, that entered data should be displayed on the next screen(activity).
To achieve this:
use 2 editText fields and 1 button in your xml layout file.
Problem:
You have added only button view in your layout file and not the editText.
Let me know if you want the code for the same then.

Best and easy way of using onclick listener,
In your xml layout,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onclick="goToMethod"/>
</LinearLayout>
In your activity,
class MainActivity extends Activity{
public void goToMethod(View view){
//do your code here
}
}
Note: In tools:context you should mention the activity where you are using layout and onclick

Related

How do I take a number input, change it, then out put it, with submit button?

I am completely lost and don't have enough knowledge on coding/android studio.
I have the EditTexts (FoodIncomeCounter, FoodCampX, and FoodUpgradeX) as inputs.
Then the TextView (FoodIncomeResult) as output.
The 1st button (IncomeSubmitButton) Works properly. The 2nd button (FoodCampSubmitButton) does not, I want it to take the input of the FoodCampXs and FoodUpgradeXs then do a calculation and put that into integer TotalFood, then output TotalFood to the FoodIncomeResult TextView.
How the heck do I do this? I feel like I am close but I don't know what is wrong.
Thank you for the help!!!
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText FoodIncomeCounter;
EditText FoodCamp1Counter, FoodCamp2Counter, FoodCamp3Counter, FoodUpgrade1Counter, FoodUpgrade2Counter, FoodUpgrade3Counter;
TextView FoodIncomeResult;
int FoodIncome;
int FoodCamp1, FoodCamp2, FoodCamp3, FoodUpgrade1, FoodUpgrade2, FoodUpgrade3;
int TotalFood;
Button IncomeSubmitButton, FoodCampSubmitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
FoodIncomeResult = (TextView) findViewById(R.id.FoodIncomeResult);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
//Submit button
IncomeSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive the inputted values
Food = Integer.parseInt(FoodIncomeCounter.getText().toString());
//to show the inputted values into the result fields
FoodIncomeResult.setText(FoodIncomeCounter.getText().toString());
}
});
//Submit button
FoodCampSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
FoodIncomeResult.setText(String.valueOf(TotalFood));
}
});
}
}

button doesn't click in android studio

private Button mfactbutton;
private TextView mfacttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_fun_fact);
Button mfactbutton = (Button) findViewById(R.id.button);
TextView mfacttext = (TextView) findViewById(R.id.textView2);
// now we need to make out button to click
View.OnClickListener Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] facts = {
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built." };
String fact = "";
// randomly select a fact
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";
}
};
mfactbutton.setOnClickListener(Listener);
}
}
Hey everyone! i need help! my button doesn't just simply clicl!!!!! heeeeeeeeelp!i'm just trying to make a simple button that changes the textview2 with each click! at first it was working but now it started not to work.
Your Button clicked properly but the main thing is you did not set fact value to TextView.
#. As you have declared Button and TextView outside onCreate(), no need to declare it again inside onCreate().
Use:
mfactbutton = (Button) findViewById(R.id.button);
mfacttext = (TextView) findViewById(R.id.textView2);
Instead of:
Button mfactbutton = (Button) findViewById(R.id.button);
TextView mfacttext = (TextView) findViewById(R.id.textView2);
#. In onClick() method show fact value on TextView or show Toast message:
// TextView
mfacttext.setText(fact);
// Toast
Toast.makeText(getApplicationContext(), "Fact: " + fact, Toast.LENGTH_SHORT).show();
Here is the working code:
public class MainActivity extends AppCompatActivity {
private Button mfactbutton;
private TextView mfacttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfactbutton = (Button) findViewById(R.id.button);
mfacttext = (TextView) findViewById(R.id.textView2);
// now we need to make out button to click
View.OnClickListener Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] facts = {
"Ants stretch when they wake up in the morning.",
"Ostriches can run faster than horses.",
"Olympic gold medals are actually made mostly of silver.",
"You are born with 300 bones; by the time you are an adult you will have 206.",
"It takes about 8 minutes for light from the Sun to reach Earth.",
"Some bamboo plants can grow almost a meter in just one day.",
"The state of Florida is bigger than England.",
"Some penguins can leap 2-3 meters out of the water.",
"On average, it takes 66 days to form a new habit.",
"Mammoths still walked the earth when the Great Pyramid was being built." };
String fact = "";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";
mfacttext.setText(fact);
Toast.makeText(getApplicationContext(), "Fact: " + fact, Toast.LENGTH_SHORT).show();
}
};
mfactbutton.setOnClickListener(Listener);
}
}
OUTPUT:
Do you set your selected fact to your textView ? Add
mfacttext.setText(fact);
after selecting your random fact.
Random randomGenerator = new
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";
mfacttext.setText(fact);
use this
mfactbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code goes here
}
});
Hi I just created a simple project. if you click on the button, it will generate random text on the textview2.
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView secondTextView;
String[] Textlist = { "Hello man ", "sonam", "tashi","i am man","hellow world"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondTextView = (TextView) findViewById(R.id.textView2);
Button mybtn = (Button) findViewById(R.id.btn);
mybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeTextView_two_text();
}
});
}
private void changeTextView_two_text() {
Random random = new Random();
String rand = Textlist[random.nextInt(Textlist.length)];
// String randomText = TextList[random.nextInt(TextList.length)];
secondTextView.setText(rand);
}
}
and activity_main.xml
<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"
android:orientation="vertical"
tools:context="com.example.hello.googlemap.MainActivity">
<Button
android:id="#+id/btn"
android:text="click me"
android:layout_width="368dp"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp" />
<TextView
android:gravity="center"
android:id="#+id/textView2"
android:text="no text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/></LinearLayout>
Hope this helps you.

Crash if digit is more than 9

My app has an input where the user can enter a port number,I tried out of curiosity inputting more than 9 digits of number (Ex: 1234567890),and the app will crash.How do I prevent it from crashing?
EDIT
I am using Java language for Android
CODING
public class addActivity extends Activity{
EditText savedName,savedIP,savedPort,savedUserID,savedUserPass,savedChannel;
Button btnSave;
Button btnBack;
String addressList;
FileOutputStream outputStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
savedName = (EditText)findViewById(R.id.editName);
savedIP = (EditText)findViewById(R.id.editIP);
savedPort = (EditText)findViewById(R.id.editPort);
savedUserID = (EditText)findViewById(R.id.userID);
savedUserPass = (EditText)findViewById(R.id.userPass);
savedChannel = (EditText)findViewById(R.id.editChannel);
btnSave = (Button)findViewById(R.id.btnSave);
btnBack = (Button)findViewById(R.id.btnBack);
try{
String channelNumString = savedChannel.getText().toString();
int channelNum = Integer.parseInt(String.valueOf(channelNumString));
addressList = savedName.getText().toString();
outputStream = openFileOutput(addressList, Context.MODE_PRIVATE);
//outputStream.write(savedName.getText().toString().getBytes());
outputStream.write("4-".getBytes());
outputStream.write(savedIP.getText().toString().getBytes());
outputStream.write(":".getBytes());
outputStream.write(savedPort.getText().toString().getBytes());
outputStream.write("/user=".getBytes());
outputStream.write(savedUserID.getText().toString().getBytes());
outputStream.write("&password=".getBytes());
outputStream.write(savedUserPass.getText().toString().getBytes());
outputStream.write(System.getProperty("line.separator").getBytes());
outputStream.close();
Toast.makeText(getBaseContext(), "Address Saved !", Toast.LENGTH_SHORT).show();
savedName.setText("");
savedIP.setText("");
savedPort.setText("");
savedUserID.setText("");
savedUserPass.setText("");
savedChannel.setText("");
else{
Toast.makeText(getBaseContext(),"Apps does not support " + channelNumString + " channels",Toast.LENGTH_LONG).show();
}
}catch (Exception e){
e.printStackTrace();
}
LAYOUT
<EditText
android:layout_width="350dp"
android:layout_height="wrap_content"
android:id="#+id/editChannel"
android:background="#android:drawable/edit_text"
android:maxLines="1"
android:layout_gravity="center_horizontal"
android:inputType="number"
android:digits="0123456789."/>
This is the part I'm having problem at
#Fay Zan
Basically you don't want user to input more than 9 digits for your field,
This can be achieved using two ways programmatically or using layout views properties,
In you xml simple give this attribute to your EditText
android:maxLength="9"
OR programmatically by checking the length of your field. for example suppose the id of your field is #id+/portNo
then do validation like this
private EditText mportNo;
inside your onCreate()
mportNo = (EditText) findViewById(R.id.portNo);
String portValue = mportNo.getText().toString();
if(portValue.length() > 9) {
// throw error
}
I Assumed you are using EditText. so you need to use addTextChangedListener().
Try the following way,
YOUR_EDIT_TEXT.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,int count, int after){}
public void onTextChanged(CharSequence s, int start,int before, int count)
{
if(s.length() > 9)
{
//Do your stuff .
// You may show the intimation to user like don't try with more than 9 digits
}
else
{
//Do your stuff
}
}
});
This may helps you.

Android - Toast message for Items chosen

How can I display a Toast messages for the items I've chosen in my layout?
For example, I have 15 ImageViews that are selectable, for example I've selected ImageViews 1, 2 and 3. A toast will appear when I click a button, "You've chosen ImageViews 1, 2, 3."
By the way, I've used setTag to know when an ImageView is selected. I've setup setTag("1") for the views that is selected and setTag("0") for the rest.
Sample code that I've tried:
public void onClick(View v) {
String message = "You've chosen";
if (v.getTag().toString().equals("1")) {
message = message + " " + ivCircles[i].getId();
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
finish();
}
This line should be in onClick method of ImageView
message = message + " " + view.getId();
This line should be a global variable
public static String message = "You've chosen";
After toast displayed in onClick method of the button, the global varibale should be initiated again
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
message = "You've chosen";
set contentDescription for each image & after selecting one of the image get content discription
Toast.makeText(context,imageview.getContentDiscription(),Toast.LENGTH_SHORT).show();
You need to use the ActionMode class.
Try this way,hope this will help you to solve your problem.
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/lnrItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
MainActivity.java
public class MainActivity extends Activity {
private LinearLayout lnrItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrItems = (LinearLayout) findViewById(R.id.lnrItems);
for (int i=1;i<=15;i++){
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setTag(String.valueOf(i));
imageView.setImageResource(R.drawable.ic_launcher);
imageView.setAdjustViewBounds(true);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You've chosen ImageViews "+v.getTag().toString(),Toast.LENGTH_SHORT).show();
}
});
lnrItems.addView(imageView);
}
}
}

Text view if statement not working

Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);

Categories

Resources