TextView attribute in android for displaying intergers? - java

public void onClick(View v) {
if (v == button1){
counter++;
textView2.setText(Integer.toString(counter));
textView2.setText(counter);
}
}
I have tried to create a program that counts the number of clicks on a button, but for some reason it is not displaying it. Here is my textview component.
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="180dp"
android:layout_alignParentTop="true"
android:layout_above="#+id/button1"
android:layout_toRightOf="#+id/textView1"
android:layout_centerHorizontal="true"
android:textColor="#000000"/>
I can't seem to find an attribute for display the number of clicks. Is this because it interprets it as an interger instead of a string?

textView2.setText(String.valueOf(counter));
This takes your Integer and converts it to its String value, and sets it to your TextView.

try casting your counter variable to string variable and then try assigning it to button text as:
public void onClick(View v) {
if (v == button1){
counter++;
String s=counter.toString();
textView2.setText(S);
}
}
what your code might be doing as of what you have posted you are trying to pass an integer which is creating problem here..

Related

EditText Crashes App When It Set to Empty ( Android )

I have an EditText and when I set it to Empty and Click on my Button, my App crashes.
When I view it in Android Monitor it points to the line:
final int addTm = Integer.parseInt(Teaching);
Here is my code:
LinearLayout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="2dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:text="" />
<EditText
android:id="#+id/tM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginRight="50dp"
android:ems="1"
android:inputType="number"
android:maxLength="1"
android:text="0" />
<Button
android:id="#+id/submitBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
And my Java Code:
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Teaching = Tm.getText().toString();
final int addTm = Integer.parseInt(Teaching);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("sub").child("TM");
myRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer currentValue = mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(0);
} else {
mutableData.setValue(currentValue + addTm);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
System.out.println("Transaction completed");
}
});
}
});
The other answers are good, but I'd recommend wrapping with a try/catch for the NumberFormatException. I know you have the input set to accept numbers only, but always better safe than sorry.
Lowercase the String variable Teaching. In Java we only upper case Type names. (classes, interfaces, etc.) Notice how StackOverflow is highlighting the variable Teaching blue, a bit disorienting no?
Do this for your member fields as well Tm and Submit. They should be written tm and submit. Also, Tm is not a very descriptive name for a variable either. Imagine another programmer coming in and looking at your code, and wondering what a tm is. What is the context of this tm, where does it come from... what does it do? Is it a Teenage Mutant?
Regardless when using Integer.parseInt wrap it in a try/catch:
#Override
public void onClick(View view){
final int addTm;
try {
String teaching = Tm.getText().toString();
addTm = Integer.parseInt(teaching);
} catch (NumberFormatException e) {
addTm = 0;
}
// ...
}
Why should you do this? What if I enter a decimal number into your number input?
Using your accepted answer you will still crash. Integer.parseInt does not parse decimal numbers.
Or how about, if I switch the locale of the device and enter a number with odd characters that Integer.parseInt won't expect.
Gotta catch that exception to be full proof.
When executing Integer.parseInt() on an empty string it throws an NumberFormatException.
First, check the value of Teaching, and verify it's not empty string, or - try/catch for NumberFormatException, and set the value you want for Teaching in that case.

Android: Linking Edit Text field to button

I am creating a times tables app, in which one of the activities allows the user to enter which times tables they would like to view, then the app will bring up that times tables.(e.g. 6x5=30) etc.
Below is the xml layout I have created for the activity:
<?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:padding="15dp">
<TextView
android:id="#+id/tvTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I want to see the: "
android:textSize="25dp" />
<EditText
android:id="#+id/etEnterNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Number..."
>
</EditText>
<TextView
android:id="#+id/tvBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Times tables!"
android:textSize="25dp" />
<Button
android:id="#+id/btnGo"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="Go"
android:layout_gravity="center"/>r
</LinearLayout>
And this it the java class I have created thus far for the classes functionalitiy:
public class ViewTimesTables extends Activity implements View.OnClickListener {
// Declaring Vars
Button go;
EditText enterNumber;
TextView top;
TextView bottom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting equal to text layout View
setContentView(R.layout.view);
// calling method to intialise vars
initialiseVars();
}// on create end
/**
* method to initialise all of the buttons, textviews etc used to clean up
* the onCreate.
*/
private void initialiseVars() {
// Setting up (initialising) all the buttons text views etc from the xml
// (vid 25)
go = (Button) findViewById(R.id.btnGo);
enterNumber = (EditText) findViewById(R.id.etEnterNumber);
top = (TextView) findViewById(R.id.tvTop);
bottom = (TextView) findViewById(R.id.tvBottom);
}
/**
* Method with on click listener that adds functionality for all of the
* buttons, text views etc
*
* #param v
*/
public void onClick(View view) {
// switch statement which determines what is clicked
switch ((view).getId()) {
case R.id.etEnterNumber:
// code to read user number (i.e. between 1 and 12)
//And possibly link to go button
break;
case R.id.btnGo:
// code to bring up new activity/screen with times table
// of the number that was entered in edit text
break;
}
}
}
I am unsure how to add the correct functionality (probably within switch statement) so that when e.g. "6" is entered in the edit text box and the "go" button is pressed then the 6 times tables will be brought up in a new activity?
I would begin by looking at Intents to start a new activity and pass data to it.
A relevant tutorial is this Android Intents Tutorial
Getting the text from a edit text is a simple as enterNumber.getText().getString()
You could then use a conditional statement to call the designated class.
Something like this would allow you to pass two values to the SixTimesTables class with the values 5 and 6 passed in.
if(enterNumber.getText().getString().equals("6")){
Intent i = new Intent(this, SixTimesTables.class);
i.putExtra("Value1", 5);
i.putExtra("Value2", 6);
// set the request code to any code you like,
// you can identify the callback via this code
startActivityForResult(i, REQUEST_CODE);
}
You probably want a dynamic layout for next activity.
It may help you.
http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/
Then you can switch between activities as AndyGable mentioned.
Hopefully it'll help you.
You really dont need the onClick for the editText you can handle if data is entered in the editText or not from the button click only like this:
public void onClick(View view) {
// switch statement which determines what is clicked
switch ((view).getId()) {
case R.id.btnGo:
// code to bring up new activity/screen with times table
// of the number that was entered in edit text
// check if editText has values or not
if(TextUtils.isEmpty(mEditText.getText().toString())) {
mEditText.setError("Please enter a number");
}else {
int number = Integer.parseInt(mEditText.getText().toString());
Intent intent = new Intent(YourCurrentActivity.this, NextActivity.class);
intent.putExtra("value", number);
startActivity(intent);
// it is always good to check if the value entered is a number only or not
// add inputType tag in the xml
// android:inputType="number" for the editText.
}
break;
}
}
Now, in order to get value in the next activity do this:
// write this inside the onCreate of the Activity.
int number;
if(getIntent().getExtras() != null) {
number = getIntent().getIntExtra("value");
}
// use the number then to display the tables

Android Hangman game - User input

I am currently creating a Hangman android application and I am having trouble registering inputted letters and updating the game. I input a letter with the onscreen keyboard into the EditText created, and nothing happens.
Below is the code I am using:
// Setting up user input
input = (EditText) findViewById(R.id.inputguess);
input.setFocusable(true);
input.setFocusableInTouchMode(true);
//Getting user input
input.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String temp;
String newLetter;
newLetter = input.getText().toString();
temp = (String)enteredText.getText();
if (temp.indexOf(newLetter.toUpperCase(Locale.ENGLISH)) >= 0) {
input.setText("");
return true;
}
input.setText(""); // clearing input
entered += newLetter.toUpperCase(Locale.ENGLISH); // adding inputted letter to the entered string
enteredText.setText(temp + newLetter.toUpperCase(Locale.ENGLISH));
word.setText(hideString(text, newLetter.toUpperCase(Locale.ENGLISH)));
The XML code of my EditText is the following:
<EditText
android:id="#+id/inputguess"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/guessedwords"
android:layout_alignLeft="#+id/button1"
android:layout_marginBottom="24dp"
android:ems="10"
android:hint="#string/guessletter"
android:inputType="text"
android:maxLength="1"
android:singleLine="true"
android:imeOptions="actionDone">
</EditText>
After researching, the only reason I can think of is the type of listener being used, but I am not entirely sure. Any help would be greatly appreciated (Let me know if I should add more of my code).
Actually, the OnKeyListener only works with hardware keyboards. To make use of the software (onscreen) keyboard, you must add a TextWatcher
editText.addTextChangedListener(new TextWatcher() { ... })

Android Application Closing upon Button Click (on custom registration page)

Need some help debugging my code. I am very new to the Android SDK and am working on learning it. From what I can glean from several posts on SO and other google search results... I formulated this code.
public class MainMenu extends Activity {
private int str = 8, dex = 8, inte = 8, luk = 8, stats = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.activity_main_menu);
}
As you can see, I have created a few private variables my app is going to use to store data. In order to interact with these values, I will redraw the TextView each time they are modified. *Feel free to correct me here if this is not an ideal strategy.
public void strup(View view) {
if(stats > 0) {
TextView tv = (TextView)findViewById(R.id.textView4);
TextView st = (TextView)findViewById(R.id.textView18);
str++;
stats--;
tv.setText(str);
st.setText(stats);
} else {
Toast.makeText(this, "Out of stats!", Toast.LENGTH_SHORT).show();
}
I use a button with the following format.
Str [X] [+1]
Where Str [X] is TextView with X a dynamic value.
Also where [+1] is a button with an Onclick function preset by the XML file.
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Str [" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="]" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="strup"
android:text="+1" />
Now for simplicity, I have altered the "android:text="" " lines to reflect their actual values instead of linking to #string/... I don't think this makes of much difference but I wanted to acknowledge it.
So my question is why does my Application crash when I click the "+1" button? All my app is trying to do is to redraw the TextView with a higher value (under str) and a lower value (under stats).
Thanks for any and all help!
You are passing integer value in settext. Either cast integer to string or you can try changing settext like this:
tv.setText(""+str);
st.setText(""+stats);
You tried to create this object:
TextView st = (TextView)findViewById(R.id.textView18);
where is textView18 in the xml?
u can caste using toString method like this:
tv.setText(str.toString());
st.setText(stats.toString());
Try this change the position of your setContentView(R.layout.activity_main_menu);
public class MainMenu extends Activity {
private int str = 8, dex = 8, inte = 8, luk = 8, stats = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
}

editText only writes on one line, scrolls right?

I have an editText that fills half the screens width, and all of it's height. When I append text to it the text always starts halfway down the edit text height and when it gets to the edge to the editText it keeps writing, scrolling to the right. I want it to go to a new line, why isn't it? and why does it start half way down? At the moment the text on the left should be replicated on the right. AppendToEMulator writes to the terminal fine, but when i'm ssetting the text in the editText on the right there are no newlines from either the bytes received, probably as I convert it to a string and also none from when the end of the editText is reached, just keeps going right.
<jackpal.androidterm.emulatorview.EmulatorView
android:id="#+id/emulatorView"
android:layout_width="500dp"
android:layout_height="wrap_content"
android:layout_above="#+id/term_entry"
android:layout_below="#+id/deviceConnect"
android:layout_toRightOf="#+id/scrllyout"
android:focusable="true"
android:focusableInTouchMode="true" />
<EditText android:id="#+id/outputBox"
android:layout_toRightOf="#+id/emulatorView"
android:layout_alignParentRight="true"
android:layout_width="200dp"
android:layout_height="fill_parent"
android:background="#ffffff"
android:textColor="#FF043241"
android:inputType="text|textImeMultiLine" />
In Java:
public void onDataReceived(int id, byte[] data) {
dataReceived = new String(data);
dataReceivedByte = dataReceived.getBytes();
statusBool = true;
((MyBAIsWrapper) bis).renew(data);
runOnUiThread(new Runnable(){
#Override
public void run() {
mSession.appendToEmulator(dataReceivedByte, 0, dataReceivedByte.length);
}});
final String ReceivedText = mReceiveBox.getText().toString() + " "
+ new String(data);
runOnUiThread(new Runnable() {
public void run() {
mReceiveBox.setText(ReceivedText);
mReceiveBox.setSelection(ReceivedText.length());
}
});
viewHandler.post(updateView);
}
Answer was that setting an inputType disables wordwrap via:
android:singleLine="true"
Even if I specify
android:singleLine="false"
it was still getting overridden.
As I do not need to type in the editText I simply removed the input type.

Categories

Resources