This question already has answers here:
java.lang.InstantiationException: class com.e has no zero argument constructor
(5 answers)
Closed 1 year ago.
This a error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginappaplication, PID: 20994
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.loginappaplication/com.example.loginappaplication.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.loginappaplication.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2216)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.loginappaplication.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2216)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
public class MainActivity extends AppCompatActivity {
private EditText eName;
private EditText ePassword;
private Button eLogin;
private TextView eAttemptsInfo;
private String Username = "Azahracaca";
private String Password = "Caca12345";
boolean isvalid = false;
private int counter = 3;
public MainActivity(Button eLogin) {
this.eLogin = eLogin;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eName = findViewById(R.id.IdName);
ePassword = findViewById(R.id.etPassword);
eAttemptsInfo = findViewById(R.id.tvAttemptsInfo);
eLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputName = eName.getText().toString();
String inputPassword = ePassword.getText().toString();
if (inputName.isEmpty() || inputPassword.isEmpty())
{
Toast.makeText(MainActivity.this, "Pastikan Semuanya Benar !", Toast.LENGTH_SHORT).show();
}else{
isvalid = valited(inputName, inputPassword);
if(!isvalid){
counter--;
Toast.makeText(MainActivity.this, "Salah Memasukkan Data !", Toast.LENGTH_SHORT).show();
eAttemptsInfo.setText("Jumlah Login Tersisa : 3 Kali" + counter);
if(counter == 0){
eLogin.setEnabled(false);
}
}else {
Toast.makeText(MainActivity.this, "Login Sukses !", Toast.LENGTH_SHORT).show(); //ke menu selanjutnya
Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}
}
});
}
private boolean valited(String name, String password){
if(name.equals(Username) && password.equals(Password)){
return true;
}
return false;
}
}
public MainActivity(Button eLogin) {
this.eLogin = eLogin;
}
make this constructor empty, and initialize eLogin button using findViewById as you are doing for eName.
you should initialize all of your views in/after onCreate(). can not initialize view in class constructor.
Why constructor Activity you passing Param?
Edit:
public class MainActivity extends AppcompatActivity
And
Button button = findViewById(R.id....)
The structure should like that
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I am making an app music player in Android Studio. After the installation was finished, an app on opening asks for media permission. The problem occurs after permission is granted, the app automatically closes.
I don't know why, but I found in logcat following message NullPointerException : Attempt to get length of null array
My class is :
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySong();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
assert files != null;
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
arrayList.add(singleFile);
}
}
}
return arrayList;
}
void displaySong()
{
final ArrayList<File> mySongs = findSong(Environment.getStorageDirectory());
items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++)
{
items[i] = mySongs.get(i).getName().toString().replace(".mp3","").replace(".wav","");
}
customAdapter customAdapter = new customAdapter();
listView.setAdapter(customAdapter);
}
class customAdapter extends BaseAdapter
{
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.id.list_item,null);
TextView txtSong = view.findViewById(R.id.txtSong);
txtSong.setSelected(true);
txtSong.setText(items[position]);
return view;
}
}
}
Where I can found issue?
here is logcat
2021-08-05 22:17:03.244 22457-22457/com.devilteched.rexplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.devilteched.rexplayer, PID: 22457
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devilteched.rexplayer/com.devilteched.rexplayer.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3550)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3710)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2139)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8047)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:600)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.devilteched.rexplayer.MainActivity.findSong(MainActivity.java:66)
at com.devilteched.rexplayer.MainActivity.findSong(MainActivity.java:68)
at com.devilteched.rexplayer.MainActivity.findSong(MainActivity.java:68)
at com.devilteched.rexplayer.MainActivity.displaySong(MainActivity.java:79)
at com.devilteched.rexplayer.MainActivity$1.onPermissionGranted(MainActivity.java:46)
at com.karumi.dexter.MultiplePermissionsListenerToPermissionListenerAdapter.onPermissionsChecked(Unknown Source:35)
at com.karumi.dexter.DexterInstance$1.run(Unknown Source:43)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.DexterInstance.checkMultiplePermissions(Unknown Source:71)
at com.karumi.dexter.DexterInstance.checkPermissions(Unknown Source:0)
at com.karumi.dexter.Dexter.check(Unknown Source:10)
at com.devilteched.rexplayer.MainActivity.runtimePermission(MainActivity.java:58)
at com.devilteched.rexplayer.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:8126)
at android.app.Activity.performCreate(Activity.java:8098)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3523)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3710)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2139)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8047)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:600)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
2021-08-05 22:17:03.248 22457-22457/com.devilteched.rexplayer D/OOMEventManagerFK: checkEventAndDumpForJE: 0
2021-08-05 22:17:03.276 22457-22457/com.devilteched.rexplayer I/Process: Sending signal. PID: 22457 SIG: 9
You dont have check for this line of code:
final ArrayList<File> mySongs = findSong(Environment.getStorageDirectory());
Your method findSong() returns null or empty List.
Can you please add folloing block:
final ArrayList<File> mySongs = findSong(Environment.getStorageDirectory());
if(!mySongs.isEmpty())
{
items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++)
{
items[i] = mySongs.get(i).getName().toString().replace(".mp3","").replace(".wav","");
}
}
I have problem with my music app. I have made a MediaPlayer and application is crashing on this:
2021-08-03 22:54:09.621 6494-6494/com.example.musiclistenerremake E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.musiclistenerremake, PID: 6494
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musiclistenerremake/com.example.musiclistenerremake.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.musiclistenerremake.PlayerActivity.getIntentMethod(PlayerActivity.java:106)
at com.example.musiclistenerremake.PlayerActivity.onCreate(PlayerActivity.java:36)
...
Full logcat log:
2021-08-03 22:54:09.621 6494-6494/com.example.musiclistenerremake E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.musiclistenerremake, PID: 6494
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musiclistenerremake/com.example.musiclistenerremake.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.musiclistenerremake.PlayerActivity.getIntentMethod(PlayerActivity.java:106)
at com.example.musiclistenerremake.PlayerActivity.onCreate(PlayerActivity.java:36)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2021-08-03 22:54:15.300 6494-6509/com.example.musiclistenerremake W/MediaPlayer-JNI: MediaPlayer finalized without being released
In my opinion I did initialize MediaPlayer correctly, I tried to move mediaPlayer before if statement (I don't know why I thought it will help) only, don't have idea what is wrong here.
Im using Android API 29.
private void getIntentMethod() {
position = getIntent().getIntExtra("position", -1);
listSongs = musicFiles;
if (listSongs != null)
{
playPauseBtn.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(listSongs.get(position).getPath());
}
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
else
{
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
Here is full code of this activity (PlayerActivity):
package com.example.musiclistenerremake;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import static com.example.musiclistenerremake.MainActivity.musicFiles;
public class PlayerActivity extends AppCompatActivity {
TextView song_name, artist_name, duration_played, duration_total;
ImageView cover_art, nextBtn, prevBtn, backBtn, shuffleBtn, repeatBtn;
FloatingActionButton playPauseBtn;
SeekBar seekBar;
int position = -1;
static ArrayList<MusicFiles> listSongs = new ArrayList<>();
static Uri uri;
static MediaPlayer mediaPlayer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initViews();
getIntentMethod();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser)
{
mediaPlayer.seekTo(progress * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
PlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mediaPlayer != null)
{
int mCurrentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
duration_played.setText(formattedTime(mCurrentPosition));
}
handler.postDelayed(this, 1000);
}
});
}
private String formattedTime(int mCurrentPosition) {
String totalOut = "";
String totalNew = "";
String seconds = String.valueOf(mCurrentPosition % 60);
String minutes = String.valueOf(mCurrentPosition / 60);
totalOut = minutes + ":" + seconds;
totalNew = minutes + ":" + "0" + seconds;
if (seconds.length() == 1)
{
return totalNew;
}
else
{
return totalOut;
}
}
private void getIntentMethod() {
position = getIntent().getIntExtra("position", -1);
listSongs = musicFiles;
if (listSongs != null)
{
playPauseBtn.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(listSongs.get(position).getPath());
}
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
else
{
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
private void initViews() {
song_name = findViewById(R.id.song_name);
artist_name = findViewById(R.id.song_artist);
duration_played = findViewById(R.id.durationPlayed);
duration_total = findViewById(R.id.durationTotal);
cover_art = findViewById(R.id.cover_art);
nextBtn = findViewById(R.id.id_next);
prevBtn = findViewById(R.id.id_prev);
backBtn = findViewById(R.id.back_btn);
shuffleBtn = findViewById(R.id.shuffle);
repeatBtn = findViewById(R.id.id_repeat);
playPauseBtn = findViewById(R.id.play_pause);
seekBar = findViewById(R.id.seekBar);
}
}
Don't use mediaplayer.release()
because after resetting player after mediaplayer.reset() is uninitialized state and if the player is not initialized then it will throw an exception
i have trouble with my app please i can't fix it. I know the problem at the price = getIntent().getIntExtra("price", -1); line but I don't know how to fix it. i have asked my friend but he sent me here. Please help me this is for my coursework.
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
init();
sqLiteHelper = new SQLiteHelper(this, "DrinDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS CART(ID INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, " +
"quantity INTEGER, price INTEGER)");
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (item < 1) {
Toast.makeText(DrinkDetailActivity.this, "Maaf Pesanan Minimal 1 cup", Toast.LENGTH_SHORT).show();
return;
}
try {
Log.i("TXT PRICE", txtName.getText().toString());
sqLiteHelper.insertData(txtName.getText().toString().trim(),
txtQuantity.getText().toString().trim(),
txtPrice.getText().toString().trim());
Toast.makeText(getApplicationContext(), "Masuk Keranjang!", Toast.LENGTH_SHORT).show();
txtQuantity.setText("0");
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DrinkDetailActivity.this, CartListActivity.class);
startActivity(intent);
}
});
String name = getIntent().getStringExtra("name");
String type = getIntent().getStringExtra("type");
int image;
image = getIntent().getIntExtra("image", -1);
price = getIntent().getIntExtra("price", -1);
Log.e("SECOND ACTIVITY", name);
TextView nameTV = (TextView) findViewById(R.id.drink_name_text_view);
nameTV.setText(name);
TextView typeTV = (TextView) findViewById(R.id.type);
typeTV.setText(type);
ImageView imageV = (ImageView) findViewById(R.id.drink_image);
imageV.setImageResource(image);
imageV.setVisibility(View.VISIBLE);
TextView priceTV = (TextView) findViewById(R.id.harga_detail_text_view);
priceTV.setText(Integer.toString(price));
sumTextView = (TextView) findViewById(R.id.sum_text_view);
priceTotalTextView =(TextView) findViewById(R.id.harga_total_text_view);
Button incrementBtn = (Button) findViewById(R.id.increment_btn);
incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
increment();
}
});
Button decrementBtn = (Button) findViewById(R.id.decrement_btn);
decrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
decrement();
}
});
}
private void init(){
txtName = findViewById(R.id.drink_name_text_view);
txtQuantity = findViewById(R.id.sum_text_view);
txtPrice = findViewById(R.id.harga_total_text_view);
btnAdd = findViewById(R.id.pesan_btn);
btnCart = findViewById(R.id.cart_btn);
}
private void increment(){
item++;
sumTextView.setText(Integer.toString(item));
priceTotalTextView.setText(Integer.toString(sumOfProduct(price)));
}
private void decrement(){
if(item<1){
Toast.makeText(this, "maaf Anda tidak dapat memesan kurang dari 1", Toast.LENGTH_SHORT).show();
return;
}
item =item-1;
sumTextView.setText(Integer.toString(item));
priceTotalTextView.setText(Integer.toString(sumOfProduct(price)));
}
private int sumOfProduct(int price){
return item * price;
}
}
`
and the error message is here [ at com.dicoding.picodiploma.kedaikopi.Models.DrinkDetailActivity.onCreate(DrinkDetailActivity.java:69)]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2760)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2821)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:181)
at android.app.ActivityThread.main(ActivityThread.java:6295)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793)
Caused by: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.e(Log.java:236)
at com.dicoding.picodiploma.kedaikopi.Models.DrinkDetailActivity.onCreate(DrinkDetailActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6834)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2713)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2821)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:181)
at android.app.ActivityThread.main(ActivityThread.java:6295)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793)
When using Intent.putExtra, you need to specify a name (first argument) and a value (second argument). The name is always a String and MUST have the package name as prefix.
From the documentation:
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
In your example, when you create the Intent to start an Activity, use intent.putExtra(getPackageName() + ".name", "my name"). And when you want to extract the extra, use String name = getIntent().getStringExtra(getPackageName() + ".name").
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to get lists from a db and suddenly this error appear.
Errors are from here:
TinyDB tinydb = new TinyDB(MyApp.getContext());
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Here's the MyApp's class
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
#Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
I have no idea how to fix this right now.
EDIT:
Process: com.example.pangelyn, PID: 7750
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.pangelyn/com.example.pangelyn.SwipeLeft}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Context.getPackageName()' on a null
object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String
android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
at android.app.Activity.getLocalClassName(Activity.java:5854)
at android.app.Activity.getPreferences(Activity.java:5897)
at com.example.pangelyn.SwipeLeft.(SwipeLeft.java:28)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
EDIT 2:
public class SwipeLeft extends AppCompatActivity {
float x1,x2,y1,y2;
List<GroupModel> lisSiswaModel = new ArrayList<>();
TinyDB tinydb = new TinyDB(MyApp.getContext());
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
RecyclerView recyclerView = findViewById(R.id.recyclerView_group);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
GroupModel groupModel1 = new GroupModel();
groupModel1.setName("School");
String json1 = gson.toJson(groupModel1);
prefsEditor.putString("groups", json1);
prefsEditor.commit();
List<String> json2 = tinydb.getListString("groups");
for (String string : json2) {
GroupModel groupModel2 = gson.fromJson(string, GroupModel.class);
lisSiswaModel.add(groupModel2);
}
recyclerView.setLayoutManager(new LinearLayoutManager(this));
GroupAdapter adapter = new GroupAdapter(this, lisSiswaModel);
recyclerView.setAdapter(adapter);
}
public boolean onTouchEvent(MotionEvent touchEvent){
switch(touchEvent.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
if(x1 > x2 + 250){
Intent i = new Intent(SwipeLeft.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
break;
}
return false;
}
}
The fix is to move this inside the onCreate of the activity(as it says, context is null):
public class SwipeLeft extends AppCompatActivity {
float x1,x2,y1,y2;
List<GroupModel> lisSiswaModel = new ArrayList<>();
TinyDB tinydb = new TinyDB(MyApp.getContext());
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
mPrefs = getPreferences(MODE_PRIVATE);
...more code
}
...more code
}
I guess is crashing because of this TinyDB tinydb = new TinyDB(MyApp.getContext()); initialize your objects inside of your onCreate()?
public class SwipeLeft extends AppCompatActivity {
float x1,x2,y1,y2;
List<GroupModel> lisSiswaModel = new ArrayList<>();
TinyDB tinydb;
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
tinydb = new TinyDB(MyApp.getContext());
mPrefs = getPreferences(MODE_PRIVATE);
Also I'd change your MyApp class to this one :
public class MyApp extends Application {
private static MyApp mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static MyApp getContext() {
return mContext;
}
}
Do not put the mContext = instance before super.onCreate()
Whenever I open the activity Testme in the emulator, it encounters a RuntimeException. The logcat has been posted below:
FATAL EXCEPTION: main
Process: com.learn.earn.earnlearnapp, PID: 6622
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.learn.earn.earnlearnapp/com.learn.earn.earnlearnapp.Testme}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Nothing seems anything wrong with the code. I have spent hours trying to fix this problem. It would be great if you could help me solve this problem. Part of my activity code has been attached below:
public class Testme extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testme);
readQuestions();
}
int qnum = 0;
private List<TopicQuestion> questionsList = new ArrayList<>();
private TextView txtquestion = findViewById(R.id.txtquestion);
private Button answer1 = findViewById(R.id.btnans1);
private Button answer2 = findViewById(R.id.btnans2);
private Button answer3 = findViewById(R.id.btnans3);
private Button answer4 = findViewById(R.id.btnans4);
private boolean correct = false;
private void readQuestions() {
InputStream is = getResources().openRawResource(R.raw.questions);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while (
(line = reader.readLine()) != null) {
//Split the data
String[] tokens = line.split(",");
//Read the data
TopicQuestion question = new TopicQuestion();
question.setTopic(tokens[0]);
question.setQuestion(tokens[1]);
question.setAns1(tokens[2]);
question.setAns2(tokens[3]);
question.setAns3(tokens[4]);
question.setAns4(tokens[5]);
questionsList.add(question);
}
} catch (IOException e) {
Log.wtf("MyActivity","Error reading question file on line" + line, e);
e.printStackTrace();
}
{
}
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer1.getText().toString());
}
});
answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns2()).equals(answer2.getText().toString());
}
});
answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer3.getText().toString());
}
});
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer4.getText().toString());
}
});
if (correct)
{
qnum +=1;
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
}
else
{
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
}
}
}
You have to assign the values of the view in OnCreate after the setContentView.
Declare the fields outside:
private TextView ;
private Button; etc..
Place the below lines in OnCreate
txtquestion = findViewById(R.id.txtquestion);
answer1 = findViewById(R.id.btnans1);
answer2 = findViewById(R.id.btnans2);
answer3 = findViewById(R.id.btnans3);
answer4 = findViewById(R.id.btnans4);
Hope it helps!