Android Buttons: getting a text back - java

I'll go over this as quick as posible. I'm developing an app that needs a comprobation from the text of a button. Let me explain it in a code-way. If my button has "This text", then do that. I've been trying for the past two days several diferent things, and I'm on a dead end, so I'm asking. Here is my code:
XML:
<Button
android:id="#+id/bHiddenL1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_margin="18dp"
android:text="#string/NotUsed"
android:maxLength="10" />
Java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newnotebookbutton);
initializeNotebookNewSubject();
}
public void initializeNotebookNewSubject() {
NewTextInput = (EditText) findViewById(R.id.etNewNotebookButtonCreateSubjectButton);
OKButton = (Button) findViewById(R.id.bOkButton);
Button1L = (Button) findViewById(R.id.bHiddenL1);
Button2L = (Button) findViewById(R.id.bHiddenL2);
Button3L = (Button) findViewById(R.id.bHiddenL3);
Button4L = (Button) findViewById(R.id.bHiddenL4);
Button5L = (Button) findViewById(R.id.bHiddenL5);
Button1R = (Button) findViewById(R.id.bHiddenR1);
Button2R = (Button) findViewById(R.id.bHiddenR2);
Button3R = (Button) findViewById(R.id.bHiddenR3);
Button4R = (Button) findViewById(R.id.bHiddenR4);
Button5R = (Button) findViewById(R.id.bHiddenR5);
OKButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String b1L = Button1L.getText().toString();
String b2L = Button2L.getText().toString();
String b3L = Button3L.getText().toString();
String b4L = Button4L.getText().toString();
String b5L = Button5L.getText().toString();
String b1R = Button1R.getText().toString();
String b2R = Button2R.getText().toString();
String b3R = Button3R.getText().toString();
String b4R = Button4R.getText().toString();
String b5R = Button5R.getText().toString();
if(b1L == "Not Used" && NewTextInput.getText().toString() != null){
NewSubjectBundle.putString("title1L", NewTextInput.getText().toString());
NewSubjectBundle.putInt("int", 1);
mIntent.putExtras(NewSubjectBundle);
setResult(RESULT_OK, mIntent);
finish();
Let me specify better my problem. Whenever I'm trying to do the "String b1L = Button1L.getText().toString();", I get an error in the logcat saying that the pointer is Null. How should that be fixed?

Don't compare content of Strings using ==.
b1L == "Not Used"
should be
b1L.equals("Not Used")
or even better
"Not Used".equals(b1L)
How do I compare strings in Java ?

ZouZou is right. But in your case, even better is:
b1L.equals(getResources().getString(R.string.NotUsed));

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.

EditText to Integer (Android)

I am attempting to convert an EditText, which is of type number in xml, to an Integer in order to calculate the value in seconds.
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
When I comment the lines where inHr and inMin are initialized I get no error in runtime, however when I leave the code as it is above I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{dit.assignment3/dit.assignment3.Timer}: java.lang.NumberFormatException: Invalid int: ""
I have also attempted this while getting the same error starting at the same line of code:
final CounterClass timer = new CounterClass(totalTime, 1000);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (hoursIn != null)
{
inHr = Integer.parseInt(hoursIn.getText().toString());
hoursMs = hrsToMs(inHr);
}
if (minIn != null)
{
inMin = Integer.parseInt(minIn.getText().toString());
minMs = minToMs(inMin);
}
else
{
textViewTime.setText("PLEASE GIVE A TIME");
}
totalTime = hoursMs + minMs;
timer.start();
}
});
Thanks in advance :)
I'm certain that this codes blocks are exactly same as you've shown here. That means You are directly initializing EditText and immediately calling getText() method which causes Exception.
There wont be any value immediately after initialization so that you are getting NumberFormatException when calling Integer.parseInt to empty value.
So I suggest you to put these codes inside some event like buttonClicked like here, so that you can be sure that you've entered some texts. And It's better checking if empty as well,
public void buttonClicked(View v){
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
}
You will get an java.lang.NumberFormatException: Invalid int: "" whenever you try to parse an empty string to Integer. Thus you need to check whether the EditText is empty or not.
You could easily do that as below
if (hoursIn.getText().toString().matches("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
OR
you can simply do a check as below
if (hoursIn.getText().toString().equals("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
First you have to put the lines where you are reading from edittext inside some event like click of a button. Then check whether anything is entered in the edittext or not, then use try/catch clause to convert it into number.
Try this code.
Add a button to your activity xml file:
<Button
android:height="wrap_content"
android:width="wrap_content"
android:onClick="myClickHandler" />
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
public void myClickHandler(View v){
if (hoursIn.getText().toString().matches("") || minIn.getText().toString().matches("")){
Toast.makeText(this, "You did not enter a text",Toast.LENGTH_SHORT).show();
return;
} else {
try {
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
Log.i("success");
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter number only",Toast.LENGTH_SHORT).show();
return;
}
}
}

Setting defaults when .getIntent().getExtras() is null

I'm attempting to pull user input from a couple EditText fields into another activity. In particular, I'd like to utilize team names input by the user in another activity of the app.
So, taking input from here:
and using it here:
As seen in the photo above, I've been successful in implementing this when the user enters in a couple team names, which I'm handling with getIntent().getExtras().
However, if the user clicks the "Start Scorekeeper" button without entering in any team names, I get the following:
However, I'd like to set default team names of "Team A" and "Team B".
I've tried to accomplish this with the following (which hasn't worked):
TeamSelector.java:
public void onClick(View view) {
Intent i = new Intent(this, ScoreKeeper.class);
final EditText teamAInput = (EditText) findViewById(R.id.team_a_input);
String teamAName = teamAInput.getText().toString();
i.putExtra("teamA", teamAName);
final EditText teamBInput = (EditText) findViewById(R.id.team_b_input);
String teamBName = teamBInput.getText().toString();
i.putExtra("teamB", teamBName);
startActivity(i);
}
Then creating a conditional as I pick up the intent.
ScoreKeeper.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_keeper);
Bundle teamNames = getIntent().getExtras();
if(teamNames==null){
final TextView teamAText = (TextView) findViewById(R.id.teamAText);
teamAText.setText(getString(R.string.team_a_name));
final TextView teamBText = (TextView) findViewById(R.id.teamBText);
teamBText.setText(getString(R.string.team_b_name));
}
else {
String teamA = teamNames.getString("teamA");
final TextView teamAText = (TextView) findViewById(R.id.teamAText);
teamAText.setText(teamA);
String teamB = teamNames.getString("teamB");
final TextView teamBText = (TextView) findViewById(R.id.teamBText);
teamBText.setText(teamB);
}
}
I've also tried coding default strings in the XML, which hasn't been effective (only one team included for brevity):
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:padding="16dp"
android:text="#string/team_a_name"
android:id="#+id/teamAText"
android:textColor="#android:color/black"
android:textSize="14sp" />
Is there a way to effectively set a default when .getIntent().getExtras() is null?
A String from EditText is never null. It can be empty but not null.
A simple check like this would work
teamAText.setText(!teamA.isEmpty() ? teamA : "Team A");
Try this:
public void onClick(View view) {
Intent i = new Intent(this, ScoreKeeper.class);
final EditText teamAInput = (EditText) findViewById(R.id.team_a_input);
String teamAName = teamAInput.getText().toString();
if(teamAName.trim().equals("")) teamAName="Team A";
i.putExtra("teamA", teamAName);
final EditText teamBInput = (EditText) findViewById(R.id.team_b_input);
String teamBName = teamBInput.getText().toString();
if(teamBName.trim().equals("")) teamBName="Team B";
i.putExtra("teamB", teamBName);
startActivity(i);
}
The strings will not be null, nor will the intent necessarily. The strings will be zero length strings, which you can use String.isEmpty() to test against.
Try to change this:
teamAText.setText(getString(R.string.team_a_name));
teamBText.setText(getString(R.string.team_b_name));
to this:
teamAText.setText(R.string.team_a_name);
teamBText.setText(R.string.team_b_name);
It is because getString needs an int as parameter and your R.string.team_a_name and R.string.team_b_name are Strings so you don't have to convert it again (Further that they are not ints).
I expect it will be helpful for you!

Android EditText Value Error?

I'm testing out some stuff on android as a beginner and was trying to grab value entered in a EditText when a button was clicked , then compare it to a string value that I defined inside the class, then use if (EditText == stringDefined) else () , but my code always jumps on the else part even if the correct text is entered, any help is appreciated. Here is the code :
Button mButton;
EditText mEdit1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final String user = "admin";
mButton = (Button)findViewById(R.id.BTN_login);
mEdit1 = (EditText)findViewById(R.id.editText1);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
String userEntered = mEdit1.getText().toString().trim();
Intent intent = new Intent(Login.this, Success.class);
if(userEntered == user){
startActivity(intent);
}
else{
AlertDialog.Builder errAlert = new AlertDialog.Builder(Login.this);
errAlert.setTitle("Wrong Credentials");
errAlert.setMessage("Wrong username");
errAlert.setCancelable(true);
errAlert.show();
}
}
});
}
Use equals method :
if(userEntered.equals(user)){
startActivity(intent);
}
== is used to compare primitive types and equals() method of java.lang.String class compares contents.

Categories

Resources