This is my layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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/postQues"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post A Question" />
<TextView
android:id="#+id/postAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Post Your Answer" />
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:clickable="true"
android:text="Submit" />
</RelativeLayout>
This is my activity:
package com.qstack.quizbox;
import roboguice.activity.RoboActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.app.main.R;
#ContentView(R.layout.q_box)
public class QuizBox extends RoboActivity {
#InjectView(R.id.postQues) TextView postQues;
#InjectView(R.id.postAnswer) EditText postAnswer;
//#InjectView(R.id.submit) Button submitA;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
PostQuestion postQuestion = new PostQuestion();
postQues.setText(postQuestion.postQuestion());
submitA.setOnClickListener(submitAnswerListener);
}
private OnClickListener submitAnswerListener = new OnClickListener() {
//onClick view
public void onClick(View v) {
String answer;
answer = postA.getText().toString();
CheckAnswer checkAnswer = new CheckAnswer();
if (answer == checkAnswer.checkAnswer()) {
postA.setText("Correct");
}
}
};
}
I am getting a null pointer exception at line number 48, caused because postQues = null. When I remove postAnswer from the code, there is no null pointer exception. I've cleaned my project and all that. Any help
I can't comment yet on your answers, but people miss the point: he, like me, is using RoboGuice to inject views and stuff.
The sole purpouse of this framework is to avoid the boiler-plate part on onCreate() where you won't need to use setContentView and findViewById() anymore !
As to why he gets a NullePointerException, I don't know. I happen to have the same issue on one of my activies although it works just fine on all the other...
[EDIT]
I found the solution : I mixed up the type of two views.
If you put setContentView() where it is supposed to be, you will get the error.
The application wil say it cannot assign. Because the type doesn't match.
Therefore you get a nice
java.lang.RuntimeException: Unable to start activity ComponentInfo
But if you use RoboGuice framework, you get such error (well in my case I did not). However, all you views will all be null.
Hope it will help someone someday.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxml); // you have missed this.....
PostQuestion postQuestion = new PostQuestion();
postQues.setText(postQuestion.postQuestion());
submitA.setOnClickListener(submitAnswerListener);
}
I had the same issue, and followed Mackovich's suggestions. He's right in pointing out that you don't need setContentView() with RoboGuice, as long as you annotate your activity with #ContentView.
In my case, the issue was caused by the fact that I had replaced an AutoCompleteTextView with an EditText, but forgot to make the same replacement in the activity with corresponding #InjectView. This was causing my NullPointerException.
Again, like Mackovich said, if I use setContentView() instead of #ContentView, the stacktrace gives me a more useful message:
Caused by: java.lang.IllegalArgumentException: Can't assign class android.support.v7.internal.widget.TintEditText value android.support.v7.internal.widget.TintEditText#426ce048 to class android.widget.AutoCompleteTextView field usernameTextView
I guess that's an argument against using Roboguice's #ContentView, at least until a fix is made in order to show the correct stacktrace.
You need to call setContentView(R.layout.the_xml) first (right after super.onCreate()). Otherwise RoboGuice doesn't know what to inject into your variables!
You forgot the following line in your code,
setContentView(R.layout.main);
which should be after this line of onCreate() method
super.onCreate(savedInstanceState);
you have missed that line
setContentView(R.layout.xml_filename);
Related
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
I am having an issue where my Button (id i_am_a_problem) which is declared in the fragment's layout XML, is generating an error when the button is clicked. Android tries to call the onClick method public void calculate(View v) but is unable to find it (despite it being declared in MainActivity). Details of my code are below, and the error is after that. Please help me determine why android is unable to find the onClick method. Thanks.
There is really not anything else going on in this code (fresh new project)
MainActivity.java
package supercali.FRAG.alistic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) { /*snip - irrelevance*/ }
#Override
public boolean onOptionsItemSelected(MenuItem item) { /*snip - irrelevance*/ }
public void calculcate(View v){
TextView tv = (TextView)findViewById(R.id.results);
tv.setText(calculate_value());
}
private String calculate_value(){
return "Abra Kadabra";
}
}
MainActivity's layout just contains a fragment
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="supercali.FRAG.alistic.MainActivityFragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
And the layout for that Fragment is:
<LinearLayout
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:onClick="calculate"
android:id="#+id/i_am_a_problem"/>
<TextView android:text="#string/results_pending" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/results"/>
</LinearLayout>
The problem Button is just there ^^ with id i_am_a_problem
LogCat:
06-18 09:49:41.280 31642-31642/supercali.FRAG.alistic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: supercali.FRAG.alistic, PID: 31642
java.lang.IllegalStateException: Could not find method calculate(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4441)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4405)
at android.view.View.performClick(View.java:5147)
at android.view.View$PerformClick.run(View.java:21069)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5401)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)
You misspelled the method.
the XML is looking for calculate but your method is calculcate
Your onCLick method is called "calculcate" in the Activity. In the XML it's "calculate".
I faced the same error but my onClick method was overridden from my base activity class and when I override it with editor help its signature became protected and hence was the problem.
Problem was resolved when I made it public.
Write the Method name correctly:
public void calculate(View v){
TextView tv = (TextView)findViewById(R.id.results);
tv.setText(calculate_value());
}
Just both spelling are different....
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:onClick="calculcate"
android:id="#+id/i_am_a_problem"/>
I just put android:onClick="calculcate"
While you used word "calculcate"
public void calculcate(View v){
.....
}
And you used android:onClick="calculate"
You misspelled calculate. And if that doesn't work, try View view instead of View v.
Actually, In AndroidManifest file to verify name correct or not. AndroidManifest shown read color line if xml file name and class file name not relate.
Base on the problem, onClickListener can't find your class files because of wrong name. Error will only show Onclick error. This problem could confuse that you may set wrong onClickListener but actual problem is you set wrong name in xml file and activity class.
Sometime, you will not see error in xml and activity files because of same android name. In this case you can verify easily what was wrong in AndroidManifest file.
eveything looks to be fine, but I still get error when I try to change the view by pressing the button.
Here is code:
package com.example.testy;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ViewFlipper;
public class MainActivity extends Activity {
ViewFlipper flipper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void clcik(View v) {
flipper.showNext();
}
}
And here is my XML:
<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:gravity="top" >
<ViewFlipper
android:id="#+id/viewFlipper1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="Button!!" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView!!" />
</ViewFlipper>
</RelativeLayout>
Anyone knows what can be wrong in this code?
Thank you for answers!
Perhaps you should fix the name of your method to click ?
public void **clcik**(View v) {
flipper.showNext();
}
Due the wrong spell (clcik) in our activity code, you may be getting a Exception because Android can't find the click method.
And thanks to #yugidroid's answer I spot one more error on your code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
setContentView(R.layout.activity_main);
}
You call findViewById before even you have any Views (a call to setContentView) . You will get a NullPointException because of that.
I would recommend you to make a call to super.onCreate the very first line of your onCreate() method. That is what Google does.
Regarding setting the click listener on layout or creating a listener and setting on the code. Well, there is not much difference, although the latter is certainly faster as the first uses reflection, what has a higher cost than just calling a method.
First of all, make sure you call setContentView(R.layout.activity_main); after the super, its a good practice.
Your problem is that you set android:onClick="click" but you are refering the wrong method in Java (clcik doesn't exists).
I advice you to declare and set listeners in the activity, not in the xml.
I'm trying to learn custom dialogs. I made one with a button in it and it comes up fine and I can hit breakpoints in the constructor and onCreate method, but when I click the button it crashes without ever getting to the button handler.
The dialog layout XML (my_dialog_layout.xml) is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/AButton"
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10px"
android:onClick="AButtonHandler"
android:text="Click Me"
/>
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toLeftOf="#id/AButton"
android:text="Click this button: "
/>
/>
... and the Dialog's java file is:
import android.os.Bundle;
import android.widget.Toast;
import android.view.View;
import android.content.Context;
import android.app.Dialog;
public class MyDialog extends Dialog {
public MyDialog(Context context) {
super(context);
setContentView(R.layout.my_dialog_layout);
}
public void AButtonHandler(View target) {
int i = 0; // just a placeholder to set a breakpoint at
i++; // " "
// Toast.makeText(this, "in AButtonHandler", Toast.LENGTH_LONG).show();
MyDialog.this.dismiss();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Toast.makeText(this, "Dialog onCreate", Toast.LENGTH_LONG).show();
}
}
When I click AButton it crashes in the debugger before getting to my breakpoint in AButtonHandler with "
Thread [<1> main] (Suspended (exception IllegalStateException))
View$1.onClick(View) line: 2059
Button(View).performClick() line: 2408
..."
Also notice the commented-out Toast's. I wanted to put Toasts in but thye compiler gives me: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (MyDialog,
String, int) What am I doing wrong?
Thanks in advance!
Second problem: A Dialog is not a Context. It has a Context. Use Toast.makeText(getContext(), ...).
First problem: Same thing. The method needs to be in the activity, not the dialog. (I should mention that I never tried onClick in a dialog. You may need to use a traditional OnClickListener.)
Side note: Function names should start with lower case.
After doing some more searching I discovered this:
Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogs
...exactly the same symptoms as I had! ... so apparently what I'm trying to do won't work. It's too bad - android:onClick - is very convenient.
I'll give eBoMike the answer credit on this because he straightened me out on the Toast and he at least alluded to the possibility that android:onClick was questionable.
I'm trying to get a simple onClick to fire from an ImageButton - it seems like a simple enough task, but I'm obviously missing something here.
Here is my java file:
package com.jlbeard.android.testapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class testapp extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//handle the button press
ImageButton mainButton = (ImageButton) findViewById(R.id.mainButton);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//show message
Toast.makeText(testapp.this, "Button Pressed", Toast.LENGTH_LONG);
}
});
}
}
Here is my layout file:
<?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"
>
<ImageView
android:id="#+id/whereToEat"
android:src="#drawable/where_to_eat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="8px"
/>
<ImageButton
android:id="#+id/mainButton"
android:src="#drawable/main_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#null"
android:clickable="true"
android:onClick="mainButtonClick"
/>
</RelativeLayout>
It seems to me that I'm missing something simple... but can't seem to figure it out. Thanks!
You didn't run show() method on Toast object. Very common mistake :-)
You also might have a problem due to the manifest setting onClick
android:onClick="mainButtonClick"
If mainButtonClick exists on post 1.5 devices it may be called instead, overriding the one you're setting in code
In my case, the imageButton was displayed behind a list. Because the list was empty, the ImageButton was seen but onClick was never fired.
Adding android:elevation="5dp" in the screen xml solve my problem
Note that if I use Button instead of ImageButton, elevation is not required.