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();
}
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");
}
});
I constantly have this message when I launch my app !!!SORRY YOUR APP unfortunately stopped or can't launch. I don't really know how it came about. Can some help me out with this error please. Equally I don't get any error message after launching only when app has to launch.
here is the logcat error message:
and its layout activity
my main activity code
01-02 12:52:57.694 5065-5065/com.logo.tm.logodrive001 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.logo.tm.logodrive001, PID: 5065
java.lang.NoSuchMethodError: No static method getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)Landroid/graphics/Typeface; in class Landroid/support/v4/content/res/ResourcesCompat; or its super classes (declaration of 'android.support.v4.content.res.ResourcesCompat' appears in /data/app/com.logo.tm.logodrive001-1/split_lib_dependencies_apk.apk)
at android.support.v7.widget.TintTypedArray.getFont(TintTypedArray.java:119)
at android.support.v7.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:208)
at android.support.v7.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:110)
at android.support.v7.widget.AppCompatTextHelperV17.loadFromAttributes(AppCompatTextHelperV17.java:38)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:81)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:67)
at android.support.v7.widget.Toolbar.setTitle(Toolbar.java:753)
at android.support.v7.widget.ToolbarWidgetWrapper.setTitleInt(ToolbarWidgetWrapper.java:261)
at android.support.v7.widget.ToolbarWidgetWrapper.setWindowTitle(ToolbarWidgetWrapper.java:243)
at android.support.v7.widget.ActionBarOverlayLayout.setWindowTitle(ActionBarOverlayLayout.java:621)
at android.support.v7.app.AppCompatDelegateImplV9.onTitleChanged(AppCompatDelegateImplV9.java:631)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.logo.tm.logodrive001.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java:6092)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
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:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button mDriver, mCustomer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDriver = (Button) findViewById(R.id.driver);
mCustomer = (Button) findViewById(R.id.customer);
startService(new Intent(MainActivity.this, onAppKilled.class));
mDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DriverLoginActivity.class);
startActivity(intent);
finish();
return;
}
});
mCustomer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CustomerLoginActivity.class);
startActivity(intent);
finish();
return;
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context="com.logo.tm.logodrive001.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="log in 1"
android:id="#+id/driver"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="log in 2"
android:id="#+id/customer"/>
</LinearLayout>
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to add data to sqlite, but when I clicked Add Button error appear and my app closed. I don't understand, so many wasted hours for looking the solution by myself..
here is my java code, AddSampleActivity.java
package com.example.mangan;
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.Toast;
public class AddSampleActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editNama, editJarak, editRating , editHarga;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sample);
editNama = (EditText) findViewById(R.id.nama);
editJarak = (EditText) findViewById(R.id.jarak);
editRating = (EditText) findViewById(R.id.rating);
editHarga = (EditText) findViewById(R.id.harga);
myDb = new DatabaseHelper(this);
}
public void addData(View view) {
boolean isInserted = myDb.insertData(editNama.getText().toString(),
editJarak.getText().toString(),
editRating.getText().toString(),
editHarga.getText().toString() );
if(isInserted)
Toast.makeText(AddSampleActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(AddSampleActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
my layout, activity_add_sample.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.example.mangan.AddSampleActivity">
<EditText
android:id="#+id/jarak_editText"
android:hint="Jarak"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/rating_editText"
android:hint="Rating"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/harga_editText"
android:hint="Harga"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addData"
android:text="Add"/>
</LinearLayout>
This is fullstack trace
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:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
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:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.mangan.AddSampleActivity.addData(AddSampleActivity.java:30)
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:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
It seem that some content on addData method is the problem. I read another question, Getting IllegalStateException on button click, but the problem is little bit different..
Your edittext ids aren't correct. change them like below
editJarak = (EditText) findViewById(R.id.jarak_editText);
editRating = (EditText) findViewById(R.id.rating_editText);
editHarga = (EditText) findViewById(R.id.harga_editText);
Your edit text ids are wrong. Try this,
editNama = (EditText) findViewById(R.id.nama_editText);
editJarak = (EditText) findViewById(R.id.jarak_editText);
editRating = (EditText) findViewById(R.id.rating_editText);
editHarga = (EditText) findViewById(R.id.harga_editText);
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 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.