I'm trying to make a simple number guessing game in android. A random number is generated when the app in launched and the user has to guess the number. The result is displayed in the form of a long toast. But when I run the app and try and enter a number the emulator says: "unfortunately High Low Game has stopped working". I have tried resetting the app and also clearing data from my emulators settings menu but it didn't make a difference. I sense something is wrong with my java code but haven't been able to figure out what is the problem so far.
Here is the java code:
package com.example.pooria.hilowgame;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Random;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int randomNum;
public void buttonClicked(View view){
EditText numField=(EditText) findViewById(R.id.numField);
int numFieldVal= Integer.parseInt(numField.toString());
String toastMessage= "";
if(numFieldVal>randomNum){
toastMessage= "Higher";
}else if(numFieldVal==randomNum){
toastMessage= "You made the right guess!!!";
}else{
toastMessage= "Lower";
}
Toast.makeText(getApplicationContext(),toastMessage,Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator= new Random();
int randomNum= randomGenerator.nextInt(101);
}
}
and the xml code:
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pooria.hilowgame.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Guess the random number"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Guess!!!"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="buttonClicked" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/numField"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp" />
</RelativeLayout>
Thanks
package com.example.pooria.hilowgame;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Random;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int randomNum; <--------
public void buttonClicked(View view){
EditText numField=(EditText) findViewById(R.id.numField);
int numFieldVal= Integer.parseInt(numField.getText().toString()); <-------
String toastMessage= "";
if(numFieldVal>randomNum){
toastMessage= "Higher";
}else if(numFieldVal==randomNum){
toastMessage= "You made the right guess!!!";
}else{
toastMessage= "Lower";
}
Toast.makeText(getApplicationContext(),toastMessage,Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator= new Random();
randomNum = randomGenerator.nextInt(101); <--------
}
}
See the marked lines. Code is changed to the correct, but I added text to explain what is wrong.
Change
int numFieldVal= Integer.parseInt(numField.toString());
to
int numFieldVal= Integer.parseInt(numField.getText().toString());
The unchanged line is the cause of the crash.
And for a game related problem:
This line:
int randomNum = randomGenerator.nextInt(101);
is wrong. You create a new local variable, meaning the global randomNum is 0 - always. The solution is simple - remove the int, so it references the main randomNum variable.
And by doing that, you have solved unwanted results and solved the crash.
Related
I was creating an app then a question come out:
how can i keep user in activity?
I've put two editTexts with input of int.
i want user be kept in activity until he/she puts valid numbers in edittexts.
any ideas?
The solution is very simple all you need to do is get the string values from the edit text box and have a condition in your setonclicklistener that checks the strings if they match to a certain value, if yes the intent from current activity will take you to next if not it will show an error on the edit text box (by using .setError()) and return.
Here is the Java Class Code:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
EditText editText1,editText2;
Button button;
editText1=findViewById(R.id.ed1);
editText2=findViewById(R.id.ed2);
button=findViewById(R.id.check_input);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText1.getText().toString().equals("Don"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText1.setError("Input Correct values");
return;
}
if(!editText1.getText().toString().equals("Tom"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText2.setError("Input Correct values");
return;
}
Intent intent=new Intent(ActivityA.this,MainActivity.class);
startActivity(intent);
}
});
}
}
XML Code:
<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=".ActivityA">
<EditText
android:layout_margin="10dp"
android:id="#+id/ed1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:layout_margin="10dp"
android:layout_below="#id/ed1"
android:id="#+id/ed2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ed2"
android:id="#+id/check_input"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Go to Next Activity"
/>
</RelativeLayout>
Output:
Java Code:-
package com.example.plannerv1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class DisplayNotes extends AppCompatActivity {
handledatabaseonhomescreen handle_db_notes = new handledatabaseonhomescreen();
private int key;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_notes);
Intent incomingintent = getIntent();
key = incomingintent.getIntExtra("key",-1);
displaydate(key);genanddisplay();
}
protected void addanote(View v)
{
Intent goback = new Intent();
goback.putExtra("returnkey",-100);
goback.putExtra("datewas",key);
setResult(RESULT_OK,goback);
finish();
}
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
genanddisplay();
}
}
XML code:-
<?xml version="1.0" encoding="utf-8"?>
<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:gravity="top|center"
android:layout_height="match_parent"
tools:context=".DisplayNotes"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20sp"
android:paddingBottom="20sp"
android:textStyle="bold"
android:gravity="center"
android:textSize="20dp"
android:id="#+id/dmy"/>
<ListView
android:layout_width="match_parent"
android:layout_height="0px"
android:paddingTop="20sp"
android:paddingBottom="20sp"
android:paddingLeft="5sp"
android:paddingRight="6sp"
android:layout_weight="10"
android:id="#+id/displaynote">
</ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20sp"
android:text="Add Note"
android:onClick="addanote"/>
</LinearLayout>
Error:-
java.lang.IllegalStateException: Could not find method addanote(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.AppCompatButton
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:424)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:381)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22298)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
I can't figure out why the onClick tag doesn't attach the button to the specified function.
I tried to Google the problem but nothing could help me. I tried changing the name and checking if the files are linked but nothing helps.
And I'm sorry about the ugly formatting on the error but stackoverflow wouldn't let me post.
AndroidStudio gives this warning:-
Method 'addanote' in 'DisplayNotes' has incorrect signature less... (Ctrl+F1)
Inspection info: Checks if the method specified in onClick XML attribute is declared in related activity
You addanote() function must be public, not protected:
public void addanote(View v)
Docs: https://developer.android.com/guide/topics/ui/controls/button#java
As #Marcin mentioned, you should use public instead of protected. Also, you can use a different but better approach, add a listener on the Button:
Add an id attribute to the Button, then define the listener in the onCreate() method.
XML:
<Button
android:id="addNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20sp"
android:text="Add Note"/>
Then Java:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Button addNote = findViewById(R.id.addNote);
addNote.setOnClickListner(new View.OnClickListener() {
#Override
public void onClick() {
//Your code to be implemented when button is clicked.
}
});
...
}
The 'MainActivity' activity had a function with the same name and parameters and changing 'addanote' to something else somehow solved the problem. I had no idea it would interfere with the 'DisplayNotes' Activity. Needs to be public though.
You need to make the method public as mentioned here
https://developer.android.com/guide/topics/ui/controls/button#java
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will be the View that was clicked)
the code is working fine after making it public
enter image description here
so I was working on some basics of android when I stumbled upon this. I am trying to implement a listview(having its layout stored in file eachrow.XML)and a button on my app such that when the user clicks one button "schoollife", the listview automatically imports layout stored from other file "eachrow2.XML".
the layout of eachrow.xml consists of buttons only, while the layout of eachrow2.xml consists of buttons.
Everything seems to work fine, the user clicking the button imports the other layout , but the problem starts when user tries to click buttons from the second layout. in the error logs, it is stating that the button 'subject' causing a null pointer exception
eachrow.xml:
eachrow2.xml:
===========codes========
eachrow2.xml
?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="horizontal">
<Button
android:id="#+id/subjectbutton"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:padding="1dp"
android:layout_margin="1dp"
android:textAllCaps="false"
android:background="#color/colorPrimary"
android:textColor="#color/white"
/>
<TextView
android:id="#+id/marksbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20dp"
android:text="click the button to show marks of each subject"
android:textAlignment="center"
/>
</LinearLayout>
mainactivity.java:
package com.example.ansh.reportcard;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ListView l;
private String[] d_myself;
private ArrayAdapter adp;
private HashMap<String,String> d_school;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l=(ListView)findViewById(R.id.a_list);
d_myself= new String[]{"something"
};
d_school=new HashMap<>();
d_school.put("A","B");
Button B_myself= (Button)findViewById(R.id.myself);
B_myself.setOnClickListener(this);
Button B_school=(Button)findViewById(R.id.school);
B_school.setOnClickListener(this);
Button subject=(Button)findViewById(R.id.subjectbutton);
subject.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.myself){
adp=new ArrayAdapter(MainActivity.this,R.layout.eachrow,R.id.textView,d_myself);
l.setAdapter(adp);
}
if (view.getId()==R.id.school){
adp=new ArrayAdapter(MainActivity.this,R.layout.eachrow2,R.id.subjectbutton,d_school.keySet().toArray());
l.setAdapter(adp);
}
if (view.getId()==R.id.subjectbutton){
Button tmp=(Button)view;
CharSequence x=tmp.getText();
TextView t= (TextView) findViewById(R.id.marksbox);
t.setText(d_school.get(x.toString()));
}
}
}
According to my understanding to your question, You declaring the Button from the xml file activity_main.xml, Instead you should find it from the eachrow2.xml file.
The subjectbutton is in the eachrow2.xml so you need to find the view from this file only instead activity_main.xml.
I surdenly noticed that My project starts throwing error anytime I try to access a resources that is a button. It underlines R.id.button. I dont understand why. I even deleted the last xml that I created but problem persist.
This is an example of my xml file
<?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:background="#drawable/layoutborder"
android:orientation="vertical" >
<TextView
android:id="#+id/chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/stepone"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/wine" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:src="#drawable/ai" />
<Button
android:id="#+id/drugdetails"
style="#style/smallButtonStyleBlackpearl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:text="#string/nextbut" />
</LinearLayout>
My Java code
package com.example.rhemahealthcare;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockActivity;
import com.example.rhemahealthcare.R;
public class SteponeActivity extends SherlockActivity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.steponeactivity);
final Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent intent = new Intent(SteponeActivity.this,SteptwoActivity.class);
startActivity(intent);
}
});
}
}
i think you change any button1 id buy clicking right click and choose edit id. this option changes all the ids with that name in all the layouts.
As #Aleks G gussed it right in the comment, you don't have any button with id as button1 in your xml file. You've mentioned it :
final Button button = (Button)findViewById(R.id.button1);
Use the appropriate ID or put one in your layout file.
I have figured out the problem. My button ids were automatically change to button1 so they did not reference their previous ids that I gave to them. Thanks alot
I have this code:
package com.problemio;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ProblemioActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button addProblemButton = (Button)findViewById(R.id.add_problem_button);
Button browseProblemsButton = (Button)findViewById(R.id.browse_problems_button);
Button searchProblemsButton = (Button)findViewById(R.id.search_problems_button);
Button myProblemsButton = (Button)findViewById(R.id.my_problems_button);
addProblemButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v) {
Intent myIntent = new Intent(ProblemioActivity.this, AddProblemActivity.class);
ProblemioActivity.this.startActivity(myIntent);
}
});
}
}
It compiles fine and displays the addProblemButton button, but when that button is clicked, the system gives a runtime exception.
Here is the AddProblemActivity class:
package com.problemio;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddProblemActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TextView text = (TextView) dialog.findViewById(R.id.addProblemText);
//text.setText(R.string.addProblemText);
TextView tv = new TextView(this);
tv.setText("Please Add a Problem");
setContentView(tv);
}
}
and here is the layout main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="First, add the problem you want to solve!"
/>
<TextView
android:id="#+id/add_problem_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add a Problem You Want To See Solved"
/>
<Button
android:id="#+id/add_problem_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add a Problem"
/>
<Button
android:id="#+id/browse_problems_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Browse Problems"
/>
<Button
android:id="#+id/search_problems_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Search Problems"
/>
<Button
android:id="#+id/my_problems_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="View My Problems"
/>
</LinearLayout>
any idea what might be going wrong? By the way, I can't seem to locate the stack trace of the exception. Where should I look for that in Eclipse? All it currently shows me is AndroidRuntimeException - dalvik.system.NativeStart.main
Thanks!!
The only problem I can think of is that your Activity "AddProblemActivity" is not register in the manifest.
See the logs under LogCat...you will find it in Window >Show View >Android > LogCat