Accept user input from Activity - java

I have some experience with Java, but I am now trying to create an Android app and I do not know how to accept user input. The id of my Edit Text is enterRequestMessage and the name of my XML file is activity_score_entry.xml. Here is the beginning of my Java file.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ScoreEntry extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
}
}

You need to get access to the controls in the xml
public class ScoreEntry extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
String value = editText.getText().toString();
// use the value here
Log.d(ScoreEntry.class.getCanonicalName(), "The value is: " + value);
}
}
}
And in the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_score_entry"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
You can adjust the code according to your needs.

Related

My android app stopping when I touch the button

This is my code guys when I touch the "saldir" button or another button my app
crashes and this is my app's image https://ibb.co/ce3ATm
This is my error (https://ibb.co/jBxb16):
Dergilik APP has stopped
package com.example.rg.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener
{
int sayac =0;
TextView tv;
**//kind of turkish words don't focus the variables**
TextView tvkarekterOzellikleri;
Button byemekye;
#Override
**//THIS IS MY MAIN_Activity.Java**
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.Answer);
//I'm trying very basic app when I touch button this layout'll changed
tvkarekterOzellikleri = (TextView) findViewById(R.id.Question);
Button bsaldir = (Button) findViewById(R.id.saldir);
//comment/i have 3 buttons as you can see on link at top
Button buyu = (Button) findViewById(R.id.uyu);
Button byemekye = (Button) findViewById(R.id.yemekYe);
bsaldir.setOnClickListener(this);
buyu.setOnClickListener(this);
byemekye.setOnClickListener(this);*
//This part useless now because I didn't added this part later I'll add this part
//Character k = new Character();
//k.Movementnum = 10;
//k.Kilos = 10;
//k.FightPower = 10;
//}
#Override
//This part is PROBLEM WHEN I DELETE THIS PART MY CODE IS WORKING
public void onClick(View v){
if (v.getId()==byemekye.getId())
tv.setText("yemek yenildi");
else
tv.setText("Nar" + (sayac++));
}
}
When I delete if.(v.getId....) app is running normal.
This side is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.rg.myapplication.MainActivity">
<Button
android:id="#+id/saldir"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:elevation="0dp"
android:text="saldir" />
<TextView
android:id="#+id/Question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|bottom|center"
android:padding="3dp"
android:text="#string/Dilektasi"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:layout_above="#+id/saldir"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="75dp" />
<TextView
**android:id="#+id/Answer**"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/saldir"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:text="" />
//I have 3 button for my app as you can see on image
<Button
android:id="#+id/yemekYe"
**im saying twice pls dont focus on variables**
**next time i'll make this variables english**
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/saldir"
android:layout_toLeftOf="#+id/saldir"
android:layout_toStartOf="#+id/saldir"
android:text="yemek ye" />
smth smth smth smth
<Button
android:id="#+id/uyu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/saldir"
android:layout_toEndOf="#+id/saldir"
android:layout_toRightOf="#+id/saldir"
android:text="Uyu" />
//dont focus the variable names
</RelativeLayout>
I think your problem is this:
Define Buttons:
private Button bt;
Set id of the button on xml, than on onCrate()
bt= (Button) findViewById(R.id.button1); //button1 is the id of the button
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do actions
}
});
code:
public class YourActivity extends AppCompatActivity {
private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_details);
parent_view = findViewById(android.R.id.content);
btn1= (Button) findViewById(R.id.button1); //button1 is the id of the button
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do actions
}
});
}
on xml
<Button
android:id="#+id/butto1" <!-- the id -->
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />

Android Studio: Boolean function crashes my app

Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.
Code:
MainActivity.java
package com.leuchtstein.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView) ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void triggerlight(View view) {
if (stat == false) {
text.setText("ON");
stat = true;
} else {
text.setText("OFF");
stat = false;
}
}
}
activity_main.xml
<?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.leuchtstein.flashlight.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/desc_textview"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
app:layout_constraintHorizontal_bias="0.95"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="triggerlight"
android:text="Turn on/off"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.387" />
Well, thanks in advance.
Don't call
TextView text = (TextView) findViewById(R.id.textView) ;
in initialisation, rather call it in onCreate() method.
This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.
Put
text = (TextView) findViewById(R.id.textView);
in onCreate() and put
TextView text;
in initialisation instead.
Try this :
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :
TextView text = (TextView) findViewById(R.id.textView);
Change your code to look like this :
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.

How i can compare the value of an id with java

I have a simple xml with a question and two buttons. When one of buttons is pushed i will compare if the id of the pushed button is equal to "Blanco" or "Negro".
The XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/pregunta" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Blanco"
android:onClick="respuesta"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Negro"
android:onClick="respuesta"/>
</LinearLayout>
</LinearLayout>
This is de java code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void respuesta(){
//The doubt.
//Here the if/else to compare ID with the button text
}
}
Don't do it like that. Create an onClickListener for each Button, so you know exactly which one is being pressed. For example:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener{
public void onClick(View v) {
// call code here, knowing that button1 was pressed
}
});
button2.setOnClickListener(new View.OnClickListener{
public void onClick(View v) {
// call code here, knowing that button2 was pressed
}
});
}
}
implement onClickListener into your Activity.
public class MainActivity extends ActionBarActivity implements OnClickListener
Declare the Button variables inside your class
Button btblanco, btnegro;
Implement the clickListener event on onCreate
btblanco = (Button) findViewById(R.id.button1);
btnegro = (Button) findViewById(R.id.button2);
btblanco.setOnClickListener(this);
btnegro.setOnClickListener(this);
And put this inside onClickListener method.
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
Toast.makeText(getApplicationContext(), "Blanco", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Negro", Toast.LENGTH_SHORT).show();
break;
}}
if you are interested in just knowing which button was clicked, then add a onclicklistener to the button objects. Google for it a bit and the samples you find will show you how to use a switch case structure to d actions based on which button was clicked.

Android, set text for an EditText on startup

So I have a simple android app where I take text from a text file (that part is working) and I want to set that text to EditText.setText(). The problem I'm having is that I cannot do this in the onCreate() method because the EditText field and the UI hasn't been created yet(from what it seems).
My question is where would be a good place to do this? Is there a function that is called right after the GUI elements are created?
public class MainActivity extends ActionBarActivity
{
private final String FILE_NAME = "awayReply";
private EditText myEditMessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
protected void onStart()
{
String message = readMessage();
myEditMessage = (EditText)findViewById(R.id.edit_message);
if(myEditMessage != null)
{
myEditMessage.setText(message, TextView.BufferType.EDITABLE);
}
}
XML Layout:
<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:orientation="horizontal"
android:paddingBottom="16dp"
android:paddingTop="16dp" >
<EditText
android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/lbl_message"
android:inputType="textImeMultiLine" />
<Button
android:id="#+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/edit_message"
android:onClick="updateMessage"
android:text="#string/lbl_update" />
<ToggleButton
android:id="#+id/toggle_away"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/lbl_enable"
android:layout_alignBottom="#+id/lbl_enable"
android:layout_toRightOf="#+id/edit_message"
android:textOff="Disabled"
android:textOn="Enabled"
android:onClick="toggleEnabled" />
</RelativeLayout>
You can't set your text in a TextView until you inflate your layout with
setContentView(R.layout.main_activity);
in the Activity's OnCreate
Once that happens you can do:
EditText editText = (EditText)findViewById(R.id.myEditText)
Full Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // this needs to happen first
EditText editText = (EditText)findViewById(R.id.myEditText)
editText.setText("my text", TextView.BufferType.EDITABLE); // <-- needs that second parameter
}
Edit: updated for EditText instead of TextView
I think I figured out my problem. I need to do this work in the PlaceholderFragment where onCreateView is defined. When I call findviewbyid here it dosen't return null.

"Unfortunately, <App Name> has stopped." Common unexplained Error

I am having a problem when debugging apps that respond to user input. An ordinary app that just displays text works fine, but when I give a button an event handler I get a generic message "Unfortunately, 'App Name' has stopped.". I have tried many solutions, but to no avail. I am using IntelliJ IDEA 12.0.4 (Community Edition).
Sorry for asking a very common question but it seems the solution is different for everyone.
Edit - new working code
Source Code:
package com.example.Android_Test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static com.example.Android_Test.R.*;
public class MyActivity extends Activity {
EditText editText;
TextView textView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare all widget controls.
editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
textView = (TextView) findViewById(R.id.lblText);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText());
}
};
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtEdit" android:layout_gravity="left|center_vertical"
android:layout_alignParentLeft="true" android:layout_marginLeft="0dp" android:layout_alignParentTop="true"
android:layout_marginTop="0dp" android:layout_alignParentRight="true" android:hint="Type here change text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChange"
android:layout_alignLeft="#+id/txtEdit" android:layout_below="#+id/txtEdit"
android:layout_alignRight="#+id/txtEdit"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change this text"
android:id="#+id/lblText"
android:layout_alignLeft="#+id/txtEdit" android:layout_below="#+id/btnChange"
android:layout_alignRight="#+id/txtEdit" android:textSize="18dp"/>
</RelativeLayout>
Logcat is very long so I pasted it here: http://pastebin.com/2qaY8ZJj.
Everyone's Logcat is so much shorter i don't know why
Move this code
// Declare all widget controls.
EditText editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
TextView textView = (TextView) findViewById(R.id.lblText);
inside onCreate() and use R.id... .
Edit
I edited youre code
public class MyActivity extends Activity {
EditText editText;
TextView textView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare all widget controls.
editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
textView = (TextView) findViewById(R.id.lblText);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText().toString);
}
};
}

Categories