Android onClick function not working - java

content_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/beer_btn"
android:id="#+id/button"
android:layout_below="#+id/color"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickFindBeer"/>
JAVA FILE
public class FindBeerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
}
public void onClickFindBeer(View view){
TextView brands=(TextView)findViewById(R.id.brands);
Spinner color=(Spinner)findViewById(R.id.color);
String beerType=String.valueOf(color.getSelectedItem());
brands.setText(beerType);
}
Hello there. While running this code The Button action is not working..
The app crashes. I cant find any error. I got this code from Head First android development tutorial.
Somebody please find the error and help me
here is the error log
05-26 09:34:30.929 19451-19451/com.example.devan.layouttut E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.devan.layouttut, PID: 19451
java.lang.IllegalStateException: Could not find method onClickFindBeer(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
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:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Your question is not very ideal for SO and there are a lot of tutorials here and there regarding how to work with button click in Android.
But anyway, here's how you can implement the onClick on a button.
In your FindBeerActivity remove the onClickFindBeer function.
public class FindBeerActivity extends Activity {
// Get the Button variable first
private Button myButton;
private TextView brands;
private Spinner color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
myButton = (Button) findViewById(R.id.my_button);
brands = (TextView) findViewById(R.id.brands);
color = (Spinner) findViewById(R.id.color);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String beerType=String.valueOf(color.getSelectedItem());
brands.setText(beerType);
Toast.makeText(this,"Clicked", Toast.LENGTH_LONG).show();
}
});
}
}
From your content_main.xml remove the onClick="onClickFindBeer" too.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/beer_btn"
android:id="#+id/my_button"
android:layout_below="#+id/color"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
There are of course other ways to implement onClick of a button, but I think this is the simplest.

Related

no errors but still app force closes in android studio [duplicate]

This question already has answers here:
Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
(2 answers)
Closed 4 years ago.
I am trying to make an app to take an image when the button is clicked and then take that image and place it in the image view field.
The given code is fine with no errors, i have checked many times. Still i get this error of runtime exception even when i have instanciated the activity in the manifest file.
here is xml code:
<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:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
tools:context="com.example.android.tryingcamera.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="9"/>
<Button
android:id="#+id/btnCamera"
android:layout_weight="1"
android:text="Tap To Open Camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btncameraClicked"/>
here is java code:
public class MainActivity extends AppCompatActivity {
private ImageView imageview=(ImageView)findViewById(R.id.imageView);
private Button btncamera = (Button) findViewById(R.id.btnCamera);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btncameraClicked(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data ){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
}
The logcat show this:
Process: com.example.android.tryingcamera, PID: 27769
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.tryingcamera/com.example.android.tryingcamera.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.android.tryingcamera.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Check your code You need to
Do findViewById() inside your onCreate() method after setContentView()
Try this Change your code like below code
public class MainActivity extends AppCompatActivity {
private ImageView;
private Button ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview=(ImageView)findViewById(R.id.imageView);
btncamera = (Button) findViewById(R.id.btnCamera);
}
public void btncameraClicked(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data ){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
}
When you declare imageview and btnamera as class variables and assign it all using findViewById, the findViewById method called when the instance of MainActivity class created, but the view not ready.
you can assign the variables after the view already set.
private ImageView imageview;
private Button btncamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview=(ImageView)findViewById(R.id.imageView);
btncamera = (Button) findViewById(R.id.btnCamera);
}

Android Studio App Crash, Related To OnClick and startActivityForResult

I am learning how to make a simple camera app on Android Studio at the moment. When I click the 'camera' button, the app crashes. I can't seem to pinpoint what is causing the app to crash. In logcat, it states that 'startActivityForResult' might be the cause...but it looks normal to me.
I made sure that the camera button id matches the java file. Any help is greatly appreciated!
Here is my code so far.
Main_Activity.java:
public class MainActivity extends AppCompatActivity {
Button cam_button;
ImageView imageView;
static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cam_button = (Button) findViewById(R.id.cam_button);
imageView = (ImageView) findViewById(R.id.imageV);
cam_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFile();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
});
}
private File getFile() {
File folder = new File("sdcard/camera_app");
if(folder.exists())
folder.mkdir();
File imageFile = new File("cameraImage.jpg");
return imageFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String path = "sdcard/camera_app/cameraImage.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}}
activity_main.xml:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera"
android:id="#+id/cam_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageV"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
This is what I copied from the logcat:
06-24 21:30:45.769 21481-21481/com.sugarcoder.cameraapp
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sugarcoder.cameraapp, PID: 21481
java.lang.SecurityException: Permission Denial: starting Intent {
act=android.media.action.IMAGE_CAPTURE flg=0x3
cmp=com.motorola.camera/.Camera clip={text/uri-list
U:file:///cameraImage.jpg} (has extras) } from ProcessRecord{b5b85f2
21481:com.sugarcoder.cameraapp/u0a121} (pid=21481, uid=10121) with
revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at
android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2696)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1574)
at android.app.Activity.startActivityForResult(Activity.java:3921)
at
android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:3881)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
at
com.sugarcoder.cameraapp.MainActivity$1.onClick(MainActivity.java:40)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Solved! I found out the issue is that I had to actually go into the app info for the app on the phone, and turn on the permission. Thanks for all your help, folks! :)

java android crash setOnClickListener

i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_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.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.

How setText to custom dialog from one class in others?

I have created a dialog class that i would like to use in several other classes and depending in what class they should display different info. I have no problem displaying the dialog itself with working button and an already set text from the xml. But when i try to set my own text with setText the app crashes and give me java.lang.NullPointerException. What can be the problem ?
Here is my custom dialog class
public class CustomDialogInfoClass extends Dialog implements View.OnClickListener {
Button ok;
TextView myTextView;
Typeface myFont;
public CustomDialogInfoClass(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog_not_demo);
CustomDialogInfoClass c = new CustomDialogInfoClass(getContext());
ok = (Button)findViewById(R.id.btnOk);
myTextView = (TextView) c.findViewById(R.id.textViewDialog);
ok.setOnClickListener(this);
myFont = Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
ok.setTypeface(myFont);
myTextView.setTypeface(myFont);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnOk:
dismiss();
break;
default:
}
dismiss();
}
}
And here is my main where I try to call it;
public class MainActivity extends ActionBarActivity {
TextView myTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomDialogInfoClass dialogInfo = new CustomDialogInfoClass(this);
myTextview = (TextView) findViewById(R.id.textViewDialog);
myTextview.setText("Lorem ipsum dolor sit amet"); <----Null.pointer error
dialogInfo.show();
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:orientation="vertical"
android:background="#drawable/diabox"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textViewDialog"
android:layout_margin="15dp"
android:textColor="#android:color/white"
android:text="Test text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ok"
android:id="#+id/btnOk"
android:layout_gravity="center_horizontal" />
and logcat if that helps?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.name.appname/com.example.name.appname.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2221)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.access$800(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5064)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.name.appnamne.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:6084)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
            at android.app.ActivityThread.access$800(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5064)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
            at dalvik.system.NativeStart.main(Native Method)
you shouldn't access your text view from activity
in your dialog you have this constructor
public CustomDialogInfoClass(Context context) {
super(context);
}
so make this one too:
public CustomDialogInfoClass(Context context,String text) {
CustomDialogInfoClass(context);
this.text = text;
}
and make a String field in your dialog class
String text;
and setup your TextView in the dialog
myTextView = (TextView) c.findViewById(R.id.textViewDialog);
myTextView.setText(text);
and in your activity pass your text here:
CustomDialogInfoClass c = new CustomDialogInfoClass(getContext(), "MY TEXT");
You need to set the value of the TextView from inside your dialog during onCreate method.
To pass parameters to the dialog the proper way would be to have a static method in you Dialog class that return a new instance of the Object.
This method can accept paramaters and put them in a Bundle. Now you can set this bundle as argument to the created Dialog
public static YourDialog getInstance(String par1, int par2) {
YourDialog dialog = new YourDialog()
Bundle bundle = new Bundle();
bundle.putString(TAG, par1);
bundle.putInt(TAG2, par2);
dialog.setArguments(bundle);
return dialog;
}
At this point in the OnCreate method of your dialog you can get the Bundle using getArguments() using the tag you provided before and set your TextView
Once you have done in your MainActivity get an Instance of the dialog and call show() to show it
Hope it helps

android java onClick Could not execute method of the activity

This is my first time working with the recyclerview and I am getting some errors about android:onClick="addItem" here is what I get when I try to add a line of text to my recyclerview. I usually use my phone to test my apps.
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4012)
at android.view.View.performClick(View.java:4761)
at android.view.View$PerformClick.run(View.java:19767)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4007)
            at android.view.View.performClick(View.java:4761)
            at android.view.View$PerformClick.run(View.java:19767)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.sapps.app.testapp2.MainActivity.addItem(MainActivity.java:53)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4007)
            at android.view.View.performClick(View.java:4761)
            at android.view.View$PerformClick.run(View.java:19767)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Here is my code where I think is the error, but I don't know exactly:
public class MainActivity extends ActionBarActivity {
private EditText mText;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView recyclerView;
private Button btn;
private CustomRecyclerAdapter mAdapter;
private List<Data> mData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing views.
mText = (EditText) findViewById(R.id.textEt);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
// If the size of views will not change as the data changes.
recyclerView.setHasFixedSize(true);
// Setting the LayoutManager.
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
// Setting the adapter.
CustomRecyclerAdapter mAdapter = new CustomRecyclerAdapter();
recyclerView.setAdapter(mAdapter);
}
// Called when add button is clicked.
public void addItem(View v) {
if(mText!=null) {
Data dataToAdd = new Data(mText.getText().toString()); mData.add(dataToAdd);
}
}
}
And here is my recyclerview adapter to know for sure:
public class CustomRecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
CustomRecyclerAdapter mAdapter;
private List<Data> mData = Collections.emptyList();
public CustomRecyclerAdapter() {
// Pass context or other static stuff that will be needed.
}
public void updateList(List<Data> data) {
mData = data;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mData.size();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View itemView = inflater.inflate(R.layout.list_item, viewGroup, false);
return new RecyclerViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int position) {
viewHolder.title.setText(mData.get(position).text);
}
public void addItemInRec(int position, Data data) {
mData.add(data);
notifyItemInserted(position);
}
public void removeItem(int position) {
mData.remove(position);
notifyItemRemoved(position);
}
}
My MainActivity xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/textEt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addItem"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
</LinearLayout>
Maybe it is my ViewHolder:
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public RecyclerViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
Or Data.java class:
public class Data {
public String text;
public Data(String text) {
this.text = text;
}
}
The key is in your error message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.sapps.app.testapp2.MainActivity.addItem(MainActivity.java:53)
A good tip for learning from your error output is to look at each "Caused by" statement, and scan through the log until you find one of your own files referenced. Then that part of the error log will even tell you what line your code was failing on ( in this case it is line 53 on MainActivity.java).
A Null Pointer Exception in Java is when you attempt to call a method on some object 'A', but that object 'A' is currently null.
So this error message means:
"On line 53 of MainActivity.java, you tried to call a method on some object which doesn't exist yet, so I crashed."
The method that is failing is EditText mText = (EditText) findViewById(R.id.textEt);
Usually this type of failure means that you aren't finding the right ID from your layout. Double check that textEt is the correct ID for this layout element.
EDIT:
Still not sure why your views aren't getting populated, but I did notice an error with your adapter. You are redefining mAdapter, so you have 2 copies, one in local scope and one as a member to MainActivity. This will definitely mess things up.
Right here:
// Setting the adapter.
CustomRecyclerAdapter mAdapter = new CustomRecyclerAdapter();
recyclerView.setAdapter(mAdapter)
You are redefining mAdapter locally. Do this instead:
// Setting the adapter.
mAdapter = new CustomRecyclerAdapter();
recyclerView.setAdapter(mAdapter)
You are getting a null pointer on the getText() call
It means the following line:
EditText mText = (EditText) findViewById(R.id.textEt);
returns null, solution is to check and correct the layout so that textEt is on it.
Edit:
If you are sure that it's in the layout remove EditText declaration.
Declare as private EditText mText; on the class scope
setContentView(R.layout.name_of_layout_here);
mText = (EditText) findViewById(R.id.textEt);
The view in addItem(View v) is referring to the button only.
The EditText object that you want is not in the button, it is in the button's parent view.
If you try to access the object from the button view it will be null, because the button does not have it.
Instead you need to access the object from the button's parent view.
// Solution:
public void addItem(View v) {
View parentView = (View) v.getParent();
EditText mText = (EditText) parentView.findViewById(R.id.textEt);
Log.d("LOG", mText.getText().toString()));
}
I know that technically this does not solve the code in the question. But the code in the question has been changed from what produced the error so this would solve the original buggy code that actually produced the question.
I am guessing that the original buggy code looked like this:
// My guess this was the original buggy code
// MainActivity.java
public void addItem(View v) {
EditText mText = (EditText) v.findViewById(R.id.textEt);
Data dataToAdd = new Data(mText.getText().toString());
mData.add(dataToAdd);
}
// MainActivity.xml
<LinearLayout>
<EditText
android:id="#+id/textEt"
/>
<Button
android:text="Add"
android:onClick="addItem"/>
</LinearLayout>
Change public void addItemInRec to public void addItem. There is no method for onClick in mainActivity.

Categories