Android Unfortunately app has stopped? [duplicate] - java

This question already has answers here:
java.lang.IllegalStateException : Could not find a method onClick handler with id_button
(4 answers)
Closed 8 years ago.
I have to make an app where the user inputs and then the AI responds but when I input some text and press send it gives me the message "Unfortunately, app has stopped".
Here is my code:
Here is the code for sending:
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Button"
android:id="#+id/Send_btn"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="Zdenka" />...
Here is the start of the .java file:
EditText Text, OdgBox;
String odg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
EditText Text = (EditText) findViewById(R.id.Txt); //User input
Button Btn = (Button) findViewById(R.id.Send_btn); //Send button
TextView Output = (TextView) findViewById(R.id.TextView); //AI output
}...
And the last part of the java file:
...
public void Zdenka (TextView Output, EditText Text, String odg) {
String Text1 = Text.toString().toLowerCase();
if (Text1 == "živjo") {
odg = "Živjo";
}
else if (Text1 == "zivjo") {
odg = "oj";
}
else{ odg = "Ne razumem."; }
Output.setText(odg);
Thanks for the help!

What I can see from your code is: You need to change your method of onClick:
You will need to replace
public void Zdenka (TextView Output, EditText Text, String odg) {...}
with
public void Zdenka (View v) {...}
Hope it helps.
And after you do this, make sure to use equals or equalsIgnoreCase for comparing String as Squonk said. == will compare objects, not the actual String.

Related

Firing an action to be executed when a button is pressed

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

my code in android studio (i think it is in (toString)) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have a problem in my code in android studio, I created it to say "Hello" when the person "abc" writes but that didn't work . can u plz help me. here is my codes
final Button butt=(Button)findViewById(R.id.butt);
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText frag =(EditText)findViewById(R.id.frag);
final TextView hello=(TextView)findViewById(R.id.hello);
String verb =frag.getText().toString();
if (verb=="abc"){
hello.setText("Hello");
Because the condition in if block returns false
Use this code instead.
final Button butt = (Button) findViewById(R.id.butt);
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText frag = (EditText) findViewById(R.id.frag);
final TextView hello = (TextView) findViewById(R.id.hello);
String verb = frag.getText().toString();
if ("abc".equals(verb)) {
hello.setText("Hello");
}
}
}
When comparing string, always use .equals method
Example:
String str1 = "yourstring1";
String str2 = "yourstring2";
if(str1.equals(str2))//return false
{...}

Android TextView with limited amount of items and special functionality

I want to have a multiline text view and adding text to it,
After adding five lines to the TextView I want to start to add to the beginning of the text view.
For example: (numbers as text), 1,2,3,4,5 -> 6,2,3,4,5 -> 6,7,3,4,5 and so on.
I thought about using StringBuilder but I don't see an efficient way to implement this.
The delimiter of each row is "\n\n" maybe it will help to solve the problem.
Or maybe should I just do 5 textView's and have some switch case between them?
Button xml:
<TextView
android:id="#+id/searchesInputTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollHorizontally="false"
android:width="300dp"
android:height="200dp"
android:background="#drawable/border_style"
android:maxLines="5"
android:layout_marginTop="24dp"
/>
in MainActivity.java:
public class MainActivity extends AppCompatActivity {
private TextView searchesTextView;
private ImageButton refreshCurrentLocationButton;
private String myText = "";
refreshCurrentLocationButton = (ImageButton) findViewById(R.id.currentLocationRefreshImageButton);
searchesTextView = (TextView) findViewById(R.id.searchesInputTextView);
refreshCurrentLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Actual code
myText += location.ToString() + "\n\n";
searchesTextView.setText(myText);
});
}

Why can't I make this TextView if the String isn't null? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'd like to create a TextView with the name of the person you've just tapped, but when I tap a name, it prints an error message to the console.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parentView, View childView, int position, long id) {
System.err.println("clicked " + position);
System.err.println("clicked " + friendsIO.getPresentationText(position));
try {
JSONObject friendInformations = new JSONObject(friendsIO.getPresentationText(position));
String friendNames = friendInformations.getString("name");
System.err.println(friendNames);
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
peopleName.setText(friendNames);
String friendEmails = friendInformations.getString("email");
System.err.println(friendEmails);
String friendNumbers = friendInformations.getString("phone number");
System.err.println(friendNumbers);
String friendEmailsNumbers = friendNames + "\n" + friendEmails;
// TextView peopleInformations = (TextView) findViewById(R.id.peopleInfo);
// peopleInformations.setText(friendEmailsNumbers);
} catch (Exception e) {
e.printStackTrace();
}
final LayoutInflater peopleInflater = LayoutInflater.from(MainActivity.this);
final View peopleView = peopleInflater.inflate(R.layout.popup2, null);
final PopupWindow peoplePopup = new PopupWindow(peopleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
peoplePopup.showAtLocation(peopleView, Gravity.CENTER, 0, 0);
final Button peopleBack = (Button) peopleView.findViewById(R.id.cancel_button);
peopleBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
peoplePopup.dismiss();
}
}
);
I print the name to the console first, to make sure that it actually exists and I get the name I tapped (as well as the email and number, obviously), but instead of printing the name to the screen in a TextView, it gives me the following error message:
10-01 17:39:55.505 4259-4259/com.logit.data.returntosender W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
10-01 17:39:55.506 4259-4259/com.logit.data.returntosender W/System.err﹕ at com.logit.data.returntosender.MainActivity$1.onItemClick(MainActivity.java:60)
It says the error is at the line
System.err.println(friendNames);
But the TextView is only actually given afterwards, in line 61. I have tried around a bit, and not found what the problem could be. It's technically exactly how it should be, at least that's what I've been able to gather from other StackOverflow questions and a thorough google search.
The XML file of the popup with the name (and email and phone number, but that's not part of the question):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#color/colorAroundPopups"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal">
<TextView android:id="#+id/peoplePerson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="bold"
android:text=""
android:textSize="52sp"/>
<TextView android:id="#+id/peopleInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="normal"
android:textSize="26sp"/>
<Button android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel_it" />
</LinearLayout>
Thanks in advance
-Léon
EDIT: I added the part of the code where the popup, containing the TextView, is created.
EDIT: I found the found the solution. I had to put the name of the view containing the TextView before findViewById
Also, Frank N. Stein, thank you for not helping at all by sending me a question I had already looked through :)
You are retrieving the view from the activity, if the TextView was on the list item view, you would change...
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
to...
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
instead of doing this:
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
do this:
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
as your textview is a child of the listview.

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!

Categories

Resources