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");
}
});
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am using a WebView within a CardView with Recyclerview.
I implemented them correctly, but the problem is that when I run application it crashes and shows a nullpointer exception,
Log crash report:
java.lang.RuntimeException: Unable to start activity ComponentInfo{andro.petrochemical/andro.petrochemical.webViewNews}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebViewClient(android.webkit.WebViewClient)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
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 'void android.webkit.WebView.setWebViewClient(android.webkit.WebViewClient)' on a null object reference
at andro.petrochemical.webViewNews.onCreate(webViewNews.java:33)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
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)
WebView CardView xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView_news"/>
</LinearLayout>
</android.support.v7.widget.CardView>
RecyclerView xml:
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
android:id="#+id/resycleWeb"/>
</LinearLayout>
WebView java class file:
public class webViewNews extends AppCompatActivity {
private WebView webviewthis;
private RecyclerView webVieRes;
private DatabaseReference mdataRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_page);
webVieRes = (RecyclerView) findViewById(R.id.resycleWeb);
mdataRef = FirebaseDatabase.getInstance().getReference().child("weber");
webviewthis = (WebView)findViewById(R.id.webView_news);
webviewthis.setWebViewClient(new WebViewClient());
webviewthis.getSettings().setJavaScriptEnabled(true);
webviewthis.getSettings().setLoadsImagesAutomatically(true);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2web,post2webViewHolder> firebaseRecyclerAdapte = new FirebaseRecyclerAdapter<post2web,post2webViewHolder>(
post2web.class,
R.layout.web_card,
post2webViewHolder.class,
mdataRef
) {
#Override
protected void populateViewHolder(post2webViewHolder viewHolder, post2web model, int position) {
viewHolder.setWebViewPost(model.getWebViewPost());
}
};
webVieRes.setAdapter(firebaseRecyclerAdapte);
}
public static class post2webViewHolder extends RecyclerView.ViewHolder {
View mVie;
public post2webViewHolder(View itemView) {
super(itemView);
mVie = itemView;
}
public void setWebViewPost(String webViewPost) {
WebView post_web = (WebView) mVie.findViewById(R.id.webView_news);
post_web.loadUrl(webViewPost);
}
}
}
Remove webview initialization from onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_page);
webVieRes = (RecyclerView) findViewById(R.id.resycleWeb);
mdataRef = FirebaseDatabase.getInstance().getReference().child("weber");
}
And update in post2webViewHolder
public void setWebViewPost(String webViewPost) {
WebView post_web = (WebView) mVie.findViewById(R.id.webView_news);
post_web.loadUrl(webViewPost);
post_web.setWebViewClient(new WebViewClient());
post_web.getSettings().setJavaScriptEnabled(true);
post_web.getSettings().setLoadsImagesAutomatically(true);
}
You need to only find the WebView from the post2webViewHolder
It's not part of the Activity, therefore it's null
Remove webviewthis
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();
}
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.
I'm working on an application for android in Android Studio and I'm attempting to make an on-click listener like so:
Button menu_button = (Button)findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
However, when I start genymotion it tells me that the app has stopped working. If I remove this code:
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
The application runs fine. I'm very confused and was hoping maybe someone could point something out I'm not understanding.
Here's the full code of the main activity I'm working on, and I should note that the button is inside a ViewPager.
public class MainActivity extends FragmentActivity {
private ViewPager m_BackgroundViewPager;
private ViewPager m_PanelViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature((int) Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
m_BackgroundViewPager = (ViewPager)(findViewById(R.id.mainViewPager));
m_PanelViewPager = (ViewPager)(findViewById(R.id.bottomViewPager));
m_BackgroundViewPager.setAdapter
(new BackgroundPagerAdapter(getSupportFragmentManager(), this));
m_PanelViewPager.setAdapter
(new PanelPagerAdapter(getSupportFragmentManager(), this));
Button menu_button = (Button)findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
LogCat Results:
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 eqlogic.annswingsandthings.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#998822">
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/menu_button"
android:text="Menu"
android:textSize="12dp" />
</FrameLayout>
Create a global variable for your Button as follows :
Button menu_button;
Then in your onCreate() you add this line :
menu_button = (Button)findViewById(R.id.menu_button);
And now whenever you want to make a setOnClickListener() you can do it like you were doing :
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your click stuff
}
});
EDIT
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Make sure that in your activity_main.xml your button has this :
android:id="#+id/menu_button"
Problem is that the button is inside the view pager.
So in order to display the button either remove it out of the view pager or add it to the xml of the fragment which forms part of the view pager and inflate it in that fragment.
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.