This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here's MediaPlayer1.class
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MediaPlayer1 extends AppCompatActivity {
MediaPlayer mpAudio;
Boolean play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
play = false;
mpAudio = MediaPlayer.create(this, R.raw.youngagain);
mpAudio.setLooping(true);
Button bPlay = (Button) findViewById(R.id.playBtn);
bPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (play == false)
mpAudio.start();
else
mpAudio.pause();
play = !play;
}
});
}
}
and the layout file activity_media_player.xml
<FrameLayout 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:id="#+id/base_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_material_dark"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/zmountain"
android:scaleType="centerCrop"
android:foreground="#e1000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hardwell on Air"
android:textColor="#fafafa"
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginTop="60dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Hardwell on Air"
android:textColor="#fafafa"
android:layout_marginBottom="20dp"
android:id="#+id/textView" />
<sas.unplug.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/zghost" />
<com.wnafee.vector.MorphButton
android:id="#+id/playBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#null"
app:vc_endDrawable="#drawable/ic_pause_to_play"
app:vc_foregroundTint="#color/colorAccent"
app:vc_startDrawable="#drawable/ic_play_to_pause" />
</LinearLayout>
</FrameLayout>
I am getting the following error on my activity above which I've called through my adapter, like this:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final PodcastData item = items.get(position);
holder.ptitle.setText(item.getPTitle());
holder.plikes.setText(""+item.getPLikes());
//Converting image into a bitmap
Bitmap bitmap = item.getAlbum();
//usig the generate method
Palette palette = Palette.generate(bitmap, 16);
Palette.generateAsync(bitmap, 16, new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant = palette.getVibrantSwatch();
if (vibrant != null) {
// If we have a vibrant color
// update the title TextView
holder.ptitle.setTextColor(vibrant.getTitleTextColor());
holder.ptitle.setBackgroundColor(vibrant.getRgb());
}
}
});
holder.album.setImageBitmap(item.getAlbum());
holder.bLike.setOnClickListener(new View.OnClickListener() {
int likes = item.getPLikes();
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Likes selected " + items.get(position).getPLikes(), Toast.LENGTH_SHORT).show();
if(item.liked) {
holder.bLike.setColorFilter(Color.argb(255, 255, 255, 255));
likes-=1;
}
else {
holder.bLike.setColorFilter(Color.argb(255, 255, 38, 38));
likes+=1;
}
item.liked = !item.liked;
items.get(position).setPlikes(likes);
item.setPlikes(likes);
holder.plikes.setText("" + item.getPLikes());
ParseQuery<ParseObject> query = ParseQuery.getQuery("Podcast");
query.whereEqualTo("name", item.getPTitle());
query.getInBackground(item.objectId, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
object.put("likes", likes);
object.saveInBackground();
}
}
});
}
});
holder.album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MediaPlayer1.class); // Start MediaPlayer1 activity here
context.startActivity(intent);
}
});
}
activity is started in the last function - holder.album.setOnClickListener()
FATAL EXCEPTION: main
Process: sas.unplug, PID: 1715
java.lang.RuntimeException: Unable to start activity ComponentInfo{sas.unplug/sas.unplug.MediaPlayer1}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setLooping(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setLooping(boolean)' on a null object reference
at sas.unplug.MediaPlayer1.onCreate(MediaPlayer1.java:21)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
I am running the same exact code individually as a seperate project and the player works fine there but as soon as I start this activity in my main project my app crashes. Please help me I am in need of help desperately as I have my minor project submission tomorrow.
mpAudio = MediaPlayer.create(this, R.raw.youngagain)
MediaPlayer.create() return a MediaPlayer object, or null if creation failed.
MediaPlayer.create() failed and mpAudio = null .
So when you mpAudio.setLoop, you get nullpointer error.
Related
I've created an App where a user clicks on get Coins Buton, 10 Coins are added in the Texview. User has separate Login Interface. But when I integrated Firebase Realtime Saving Data, It gets Crash.
I want that whenever a User Clicks on getCoins button, Coins should be added in Text Field and these coins should also reflect in my Firebase Data.
Activity_Main Layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar_id"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/btn"
android:layout_width="200dp"
android:layout_height="66dp"
android:layout_gravity="center"
android:gravity="center"
android:text="GET COINS"
android:textSize="20sp"
android:textStyle="bold"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
<TextView
android:id="#+id/edittext"
android:layout_width="317dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginTop="124dp"
android:gravity="center"
android:text="COINS: 0"
android:textSize="40sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Main Activity Class
public class MainActivity extends AppCompatActivity {
int CoinAmount = 0;
private Toolbar mainToolbar;
private FirebaseAuth mAuth;
String myStringData;
Firebase myFirebase;
TextView myEditText;
Button btngetcoin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myStringData = myEditText.getText().toString();
Firebase.setAndroidContext(this);
myFirebase = new Firebase("https://xpensive-b5178.firebaseio.com");
btngetcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase myNewChild= myFirebase.child("PresentCoin");
}
});
btngetcoin= (Button)findViewById(R.id.btn);
myEditText = (TextView)findViewById(R.id.edittext);
final RewardedVideoAd RewardAd = MobileAds.getRewardedVideoAdInstance(this);
RewardAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
MobileAds.initialize(this);
btngetcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(RewardAd.isLoaded()){
RewardAd.show();
}else{
RewardAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
});
RewardAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
CoinAmount= CoinAmount +10;
myEditText.setText("COINS: "+ CoinAmount);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
});
Logcat Errors-
06-30 20:20:24.988 6074-6074/com.vikramgehlot.xpensive E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vikramgehlot.xpensive, PID: 6074
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vikramgehlot.xpensive/com.vikramgehlot.xpensive.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2687)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2753)
at android.app.ActivityThread.access$1100(ActivityThread.java:186)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:238)
at android.app.ActivityThread.main(ActivityThread.java:6016)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:937)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:798)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.vikramgehlot.xpensive.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2640)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2753)
at android.app.ActivityThread.access$1100(ActivityThread.java:186)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:238)
at android.app.ActivityThread.main(ActivityThread.java:6016)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:937)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:798)
If you want to save your data in firebase realtime database then you just need to do something like this
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
Take the reference of your database and then just save it like this
mDatabase.child("Key").setValue(value);
or you can take a reference from this link https://firebase.google.com/docs/database/android/read-and-write
The variable btngetcoin is not initialized with a reference to the button object you have. Move the following findViewById() code above your set setOnClickListener,
myFirebase = new Firebase("https://xpensive-b5178.firebaseio.com");
// you need to initialize this before attaching listener!!
btngetcoin= (Button)findViewById(R.id.btn);
btngetcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase myNewChild= myFirebase.child("PresentCoin");
}
});
Android compare 2 images to use Bitmap code and tell to fruit category to is fruit (apple/banana) or not fruit.
I have problem to compare with Bitmap and BitmapFactory to have runtime error , I have solution to problem.
activity_main.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"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/buttonIntent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Gallery" />
<Button
android:text="OK to Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/buttonIntent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button" />
</RelativeLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Have fruit as Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/textView"
android:textSize="20sp"
android:textColor="#android:color/black" />
</RelativeLayout>
MainActivity.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends Activity {
public static final int REQUEST_GALLERY = 1;
// Code to compare picture.
Bitmap bitmap; // Picture with select file in gallery.
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.a1); // Picture to compare.
// Code to compare picture.
ImageView imageView1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = (ImageView)findViewById(R.id.imageView);
Button buttonIntent = (Button)findViewById(R.id.buttonIntent);
buttonIntent.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent
, "Select Picture"), REQUEST_GALLERY);
}
});
Button buttonIntent2 = (Button)findViewById(R.id.button);
buttonIntent2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(bitmap == b) { // Have to error.
Intent newActivity = new Intent(MainActivity.this, ActivityForm2.class);
startActivity(newActivity);
}
}
});
}
public void onActivityResult(int requestCode, int resultCode
, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
imageView1.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ActivityForm2.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by sumate on 10/30/2016 AD.
*/
public class ActivityForm2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
Image example
5.1 Image to Bitmap bitmap;
5.2 Image to Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
Runtime Error
11-13 21:08:42.244 26248-26248/com.spv.babaimile.fruitsearchwithpic E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.spv.babaimile.fruitsearchwithpic, PID: 26248
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.spv.babaimile.fruitsearchwithpic/com.spv.babaimile.fruitsearchwithpic.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at com.spv.babaimile.fruitsearchwithpic.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I have answered to compare fruit with OpenCV color blob detection for Android complete.
Source : https://github.com/doanga2007/FruitSearch
Tutorial : https://docs.google.com/presentation/d/1s0KvqZm0kmPYRdjQNgKFPan0RjNWBCjkem23UkXh2GE/edit#slide=id.g2e200109_1_0
i am creating a single screen app of grocery but while checking total price if a user doesnt type anything it should by default be equal to 0 but instead my app crashes
Below is the code for same
Activity.xml
<?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.ashis.singlescreenapp.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/headline"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView2" />
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/grocery_logo"
android:id="#+id/imageView"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/qty_heading"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView_qty"
android:layout_below="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_qty"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_apples"
android:layout_weight="1"
android:hint="Apples ($2 per piece)" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_orange"
android:layout_weight="1"
android:hint="Orange($3 per piece)" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout2">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_mango"
android:layout_weight="1"
android:hint="Mango($4 per piece)" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_banana"
android:layout_weight="1"
android:hint="Banana($1 per piece)" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_confirm"
android:text="#string/btn_confirm"
android:onClick="onbuttonClicked"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView_result"
android:minWidth="300dp"
android:layout_below="#+id/linearLayout2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/button"
android:layout_above="#+id/button_confirm"
android:layout_centerHorizontal="true"
android:onClick="checkPrice" />
</RelativeLayout>
MainActivity.java
package com.example.ashis.singlescreenapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText_apples,editText_orange,editText_mango,editText_banana;
int apples,orange,mango,banana;
TextView textView_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkPrice(View view)
{
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
apples=Integer.parseInt(editText_apples.getText().toString());
orange=Integer.parseInt(editText_orange.getText().toString());
mango=Integer.parseInt(editText_mango.getText().toString());
banana=Integer.parseInt(editText_banana.getText().toString());
if (editText_apples.getText().toString().equals(""))
{
apples=0;
}
else if (editText_banana.getText().toString().equals(""))
{
banana=0;
}
else if (editText_orange.getText().toString().equals(""))
{
orange=0;
}
else if (editText_mango.getText().toString().equals(""))
{
mango=0;
}
else {
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
}
private int getPrice(int apples, int orange, int mango, int banana) {
int result= (apples*2) + (orange*3) + (mango*4) + (banana);
return result;
}
/*
public void onbuttonClicked(View view)
{
String email_body = "Dear Grocery Store, \n" + "Send all the following ";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL,"ashish.choudhary#groceryStore.com");
intent.putExtra(Intent.EXTRA_SUBJECT," Send All these Product");
intent.putExtra(Intent.EXTRA_TEXT,"");
}
*/
}
Here is the logCat when i click on Confirm Button
FATAL EXCEPTION: main
Process: com.example.ashis.singlescreenapp, PID: 22748
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21350)
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:5571)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21350)
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:5571)
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)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.ashis.singlescreenapp.MainActivity.checkPrice(MainActivity.java:36)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21350)
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:5571)
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)
The problem is you are trying to format an empty String. Just check
if(!edittext.getText().toString().equals("")) {
apples = Integer.parseInt(edittext.getText().toString());
} else {
apples = 0;
}
Or you could use the short form:
apples = edittext.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
You are calling parseInt before you check for empty string. parseInt on empty string will throw exception. You should in any case surround parseInt with a try catch.
You can debug your code and you see - you are trying to parse int before checking text.
You need something like this for each edit text:
if (editText_apples.getText().toString().equals("")) {
apples=0;
} else {
apples=Integer.parseInt(editText_apples.getText().toString());
}
or short variant:
apples = editText_apples.getText().toString().isEmpty() ? 0
: Integer.parseInt(editText_apples.getText().toString());
To be sure, that in edit text will be only numbers, you can add inputType for edit text:
<EditText
...
android:inputType="number"/>
You have some issues trying to parse for integers from empty strings. Try replace this piece of code:
apples=Integer.parseInt(editText_apples.getText().toString());
orange=Integer.parseInt(editText_orange.getText().toString());
mango=Integer.parseInt(editText_mango.getText().toString());
banana=Integer.parseInt(editText_banana.getText().toString());
if (editText_apples.getText().toString().equals(""))
{
apples=0;
}
else if (editText_banana.getText().toString().equals(""))
{
banana=0;
}
else if (editText_orange.getText().toString().equals(""))
{
orange=0;
}
else if (editText_mango.getText().toString().equals(""))
{
mango=0;
}
else {
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
with this:
String txt1 = editText_apples.getText().toString();
apples=Integer.parseInt("".equals(txt1.trim()) ? "0" : txt1);
String txt2 = editText_orange.getText().toString();
orange=Integer.parseInt("".equals(txt2.trim()) ? "0" : txt2);
String txt3 = editText_mango.getText().toString();
mango=Integer.parseInt("".equals(txt3.trim()) ? "0" : txt3);
String txt4 = editText_banana.getText().toString();
banana=Integer.parseInt("".equals(txt4.trim()) ? "0" : txt4);
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
Initialise view while setting content
public class MainActivity extends AppCompatActivity {
EditText editText_apples,editText_orange,editText_mango,editText_banana;
int apples,orange,mango,banana;
TextView textView_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
}
public void checkPrice(View view)
{
if(TextUtils.isDigitOnly(editText_apples.getText().toString()){
apples=Integer.parseInt(editText_apples.getText().toString());
}else{
apples=0;
}
if(TextUtils.isDigitOnly(editText_orange.getText().toString()){
orange=Integer.parseInt(editText_orange.getText().toString());
}else{
orange=0;
}
if(TextUtils.isDigitOnly(editText_mango.getText().toString()){
mango=Integer.parseInt(editText_mango.getText().toString());
}else{
mango=0;
}
if(TextUtils.isDigitOnly(editText_banana.getText().toString()){
banana=Integer.parseInt(editText_banana.getText().toString());
}else{
banana=0;
}
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
private int getPrice(int apples, int orange, int mango, int banana) {
int result= (apples*2) + (orange*3) + (mango*4) + (banana);
return result;
}
}
in your code at the time of button clicks views are getting initialized and then u will be able to use them and the values are null in edit text so casting them in integer generates null pointer exception.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
checkPrice();
}
public void checkPrice()
{
apples = edittext_apples.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
orange=editText_orange..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
mango=editText_mango..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
banana=editText_banana.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
...............
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to add an onClickListener to a button, but log cat outputs an error
Here is the log cat
FATAL EXCEPTION: main
Process: com.pk.a_loner, PID: 10539
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pk.a_loner/com.pk.a_loner.main.gui.Connect}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879)
at android.app.ActivityThread.access$900(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.pk.a_loner.main.gui.Connect.init(Connect.java:20)
at com.pk.a_loner.main.gui.Connect.onCreate(Connect.java:53)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879)
at android.app.ActivityThread.access$900(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6141)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
The code below, should be fine?
package com.pk.a_loner.main.gui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.pk.a_loner.R;
import com.pk.a_loner.main.networking.Broadcast;
import com.pk.a_loner.main.networking.Listen;
public class Connect extends AppCompatActivity {
private Button button_toggleBroadcast;
private Button button_listen;
private void init() {
this.button_toggleBroadcast = (Button) (findViewById(R.id.button));
this.button_toggleBroadcast.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (!Broadcast.isInBroadcast()) {
if (!Broadcast.isHasInit()) {
Broadcast.init();
}
Broadcast.broadcast();
} else {
Broadcast.halt();
}
}
});
this.button_listen = (Button) (findViewById(R.id.button2));
this.button_listen.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (!Listen.isInScan()) {
if (!Listen.isHasInit()) {
Listen.init();
}
Listen.scan();
} else {
Listen.halt();
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hello world", "this is a hello");
this.init();
setContentView(R.layout.activity_launcher);
}
}
and here is the xml
<?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=".main.gui.Connect">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle broadcast"
android:id="#+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Listen 10 secs"
android:id="#+id/button2" />
</LinearLayout>
</RelativeLayout>
I checked the code, I did initialize the buttons before I add the listener, shouldn't be null? buttons also declared in xml.
The app currently crashes on startup.
Any help appreciated, many thanks.
Use this in your onCreate() instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hello world", "this is a hello");
setContentView(R.layout.activity_launcher);
this.init();
}
You need to initialise your views AFTER your layout has been inflated by setContentView()
call setContentView(R.layout.activity_launcher); before init();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("hello world", "this is a hello");
setContentView(R.layout.activity_launcher);
this.init();
}
I’m working on a simple Quiz app where the user is presented a question and can select either True or False to answer the question. I added a “Show Answer” button, but when I click on that button I’m getting the following NullPointerException. I think I'm missing something in my activity_cheat.xml but I can't figure out what.
05-31 19:30:59.238 5978-5978/com.bignerdranch.android.geoquiz.geoquiz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bignerdranch.android.geoquiz.geoquiz, PID: 5978
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
at com.bignerdranch.android.geoquiz.geoquiz.CheatActivity$1.onClick(CheatActivity.java:33)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
CheatActivity.java
package com.bignerdranch.android.geoquiz.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity {
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
}
});
}
}
activity_cheat.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:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="#string/warning_text_view" />
<TextView
android:id="#+id/answerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<Button
android:id="#+id/showAnswerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_answer_button" />
</LinearLayout>
You forgot to bind mAnswerTextView with the UI:
Add
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
after the line
setContentView(R.layout.activity_cheat);
mAnswerTextView is never initialized. That's why you get the NPE.
add
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
before
if (mAnswerIsTrue)
mAnswerTextView is null.
Add,
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
before your onClickListener.