Application Closing When Calling Intent - java

I have 2 classes. I am calling an intent from my menu class, and when I call the intent to go to my MainActivity class, it gives me an error that says, Unfortunately, app name has stopped. I need help figuring out what is happening. I know it is because there is an error somewhere in MainActivity. I just need help finding it.
Here is MainActivity.java's code:
package com.arborhillsvet.arborhillsveterinarianclinic;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ViewAnimator;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "parse information", "parse information");
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
WebView appointWeb = (WebView) findViewById(R.id.appointments);
appointWeb.loadUrl("https://www.google.com");
WebSettings webSettings = appointWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
appointWeb.setWebViewClient(new WebViewClient());
WebView promosWeb = (WebView) findViewById(R.id.promos);
promosWeb.loadUrl("https://www.yahoo.com");
WebSettings webSettings2 = promosWeb.getSettings();
webSettings2.setJavaScriptEnabled(true);
promosWeb.setWebViewClient(new WebViewClient());
WebView infoWeb = (WebView) findViewById(R.id.info);
infoWeb.loadUrl("https://www.bing.com");
WebSettings webSettings3 = infoWeb.getSettings();
webSettings3.setJavaScriptEnabled(true);
infoWeb.setWebViewClient(new WebViewClient());
WebView medsWeb = (WebView) findViewById(R.id.medicines);
medsWeb.loadUrl("https://www.aol.com");
WebSettings webSettings4 = medsWeb.getSettings();
webSettings4.setJavaScriptEnabled(true);
medsWeb.setWebViewClient(new WebViewClient());
Button next = (Button) findViewById(R.id.next);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewAnimator anim = (ViewAnimator) findViewById(R.id.views);
anim.showNext();
}
};
next.setOnClickListener(listener);
Button prev = (Button) findViewById(R.id.prev);
View.OnClickListener listener2 = new View.OnClickListener() {
public void onClick(View view) {
ViewAnimator anim = (ViewAnimator) findViewById(R.id.views);
anim.showPrevious();
}
};
prev.setOnClickListener(listener2);
ImageButton menu = (ImageButton) findViewById(R.id.menu);
View.OnClickListener listener3 = new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, menu.class);
startActivity(intent);
}
};
menu.setOnClickListener(listener3);
}
}
I also have edited this post and added the Logcat after somebody has requested it. I think I see the error and it appears as if it is something wrong with the Parse.initialize and Parse.enableLocalDatastore methods, although I do not see anything wrong with their location. I am wondering if I need to put the thread to sleep for a couple seconds so local datastore can load first. I'm not sure but here is the Logcat.
>08-17 19:39:03.018 4601-4601/com.arborhillsvet.arborhillsveterinarianclinic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.arborhillsvet.arborhillsveterinarianclinic, PID: 4601
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arborhillsvet.arborhillsveterinarianclinic/com.arborhillsvet.arborhillsveterinarianclinic.MainActivity}: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
at com.parse.Parse.enableLocalDatastore(Parse.java:58)
at com.arborhillsvet.arborhillsveterinarianclinic.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I need help! Please and thank you.

I guess you have to initialize in Application class may be problem arise because you initialize in MainActivity
do like this
public class ParseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ParseCrashReporting.enable(this);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "xxx", "xxx");
}
}

Related

Android Studio Emulator Crashing On Button Click

I am very new to Android Studio and am trying to create a log in screen which then opens an inventory screen. The problem I am having is when I click Submit to the username and password, the app completely crashes. Right now, I am just working out how to organize the layout portion of things, but need to figure out how to get this transition to work. Any help would be great!
This is the main activity code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText username, password;
Button buttonLogIn, buttonRegister;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.newPassword);
buttonLogIn = (Button) findViewById(R.id.buttonLogIn);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(username.getText().toString().trim().length() <1 || password.getText().toString().trim().length() <1){
username.setError("You must enter a valid username and password");
}
else {
openInventory();
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openRegisterScreen();
}
});
}
public void openRegisterScreen() {
Intent intent = new Intent(this, RegisterScreen.class);
startActivity(intent);
}
public void openInventory() {
Intent intent = new Intent(this, InventoryScreen.class);
startActivity(intent);
}
}
This is the inventory screen code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class InventoryScreen extends AppCompatActivity {
Button buttonSMS, buttonSignOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_screen);
buttonSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openSMSPermission();
}
});
}
public void openSMSPermission() {
Intent intent = new Intent(this, SMSPermissionScreen.class);
startActivity(intent);
}
}
This is the error from logcat when the button is pressed:
2022-08-03 16:54:09.037 8043-8043/com.example.cs360projectone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cs360projectone, PID: 8043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cs360projectone/com.example.cs360projectone.InventoryScreen}: 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:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
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.example.cs360projectone.InventoryScreen.onCreate(InventoryScreen.java:18)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
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:858) 
2022-08-03 16:54:09.062 8043-8043/com.example.cs360projectone I/Process: Sending signal. PID: 8043 SIG: 9
You need to get the SMS button in the InventoryScreen onCreate method the same way you did with the other buttons in MainActivity.
This means doing a
buttonSMS = (Button) findViewById(R.id.buttonSMS);
before setting up an onClickListener.

FragmentManager has not been attached to a host error while running an Activity

Im new to android and they(some people :) ) gave me an half developed app and im still confused about some things.
Im getting an error which i can't understand what it means. So the error is what i wrote in the title : java.lang.IllegalStateException: FragmentManager has not been attached to a host, and is hapening when this activity runs:
package com.example.loginregistodb;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class ClienteActivity extends AppCompatActivity {
Spinner tipo_intervencao;
Button bt_cliente_seguinte;
EditText et_inserir_cliente;
ImageView icon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente);
bt_cliente_seguinte = (Button) findViewById(R.id.bt_cliente_seguinte);
et_inserir_cliente = findViewById(R.id.et_inserir_cliente);
tipo_intervencao = findViewById(R.id.tipo_intervencao);
icon1 = findViewById(R.id.icon2);
bt_cliente_seguinte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cliente = et_inserir_cliente.getText().toString();
String tipoIntervencao = "" + tipo_intervencao.getSelectedItem().toString();
preencherExcel Excel = new preencherExcel();
Excel.entradaWhatsapp(cliente, tipoIntervencao);
if (cliente.equalsIgnoreCase("")) {
Toast.makeText(ClienteActivity.this, "Preencha o campo Cliente!", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(ClienteActivity.this, EmpresaActivity.class);
startActivity(i);
}
}
});
}
}
EDIT :
the error message i get is this :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginregistodb, PID: 15275
java.lang.IllegalStateException: FragmentManager has not been attached to a host.
at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1938)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1996)
at androidx.fragment.app.FragmentManager.executePendingTransactions(FragmentManager.java:600)
at com.google.firebase.firestore.core.ActivityScope.lambda$onFragmentActivityStopCallOnce$1(ActivityScope.java:180)
at com.google.firebase.firestore.core.ActivityScope$$ExternalSyntheticLambda1.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

MPAndroidChart keeps throwing null error

I'm just trying this library out to see if it fits my needs and so far I have not been able to get it to work. Here is the code
package com.example.user.bottomnavigationbar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
PieChart pc;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
// case R.id.navigation_overview:
// Intent intentOverview = new Intent(MainActivity.this, activity_test.class);
// intentOverview.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// MainActivity.this.finish();
// startActivity(intentOverview);
// return true;
case R.id.navigation_expenses:
return true;
case R.id.navigation_reminder:
return true;
case R.id.navigation_income:
return true;
case R.id.navigation_login:
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
intentLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.finish();
startActivity(intentLogin);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
pc = findViewById(R.id.chart);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
public void onBackPressed()
{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
And here is the error I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.bottomnavigationbar, PID: 4172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.bottomnavigationbar/com.example.user.bottomnavigationbar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at com.example.user.bottomnavigationbar.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I've searched for a bit and all I've found was that for others, they did not initialize the object hence it throws this error. Now someone did mention that it is possible to create the chart in code and then add it to the activity as the documentation's Getting Started page suggests but I have been unable to get it working. So what gives?
P.S Left in the code for navigation as I'm not sure if it might be the cause of the issue
You are first finding the view and then providing the content view to your activity replace with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pc = findViewById(R.id.chart);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}

SoundPool won't play a passed raw from an other Activity

I have this problem I want to pass a raw from Activity 1 to be played in Activity 2
Here is my code
Activity 1
package com.ze.zeggar.tewt;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
int ThePlayedSound= R.raw.waterdrop;
Intent MyIntent= new Intent(this, MainActivity.class);
MyIntent.putExtra("key",ThePlayedSound);
startActivity(MyIntent);
}
}
Activity 2
package com.ze.zeggar.tewt;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
SoundPool Sound_Pool_thing;
int Click;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent MyIntent=getIntent();
int ThePlayedSound= MyIntent.getIntExtra("key", 0);
Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);
Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sound_Pool_thing.play(Click,1,1,1,0,1);
}
});
}
}
and when I try to open the app I got "Unfortunately , My_App has stopped"
The app crashes
and here's the new crash Log after suggestions:
06-06 10:49:09.069 3424-3424/com.ze.zeggar.tewt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ze.zeggar.tewt, PID: 3424
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ze.zeggar.tewt/com.ze.zeggar.tewt.MainActivity}:
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:1269)
at android.content.res.Resources.openRawResourceFd(Resources.java:1227)
at android.media.SoundPool$SoundPoolImpl.load(SoundPool.java:566)
at android.media.SoundPool.load(SoundPool.java:229)
at com.ze.zeggar.tewt.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365) 
at android.app.ActivityThread.access$800(ActivityThread.java:148) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5272) 
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:909) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 
Any idea ?
Ur getting resource not found exception since your not opening the raw type Resources properly
Try getting the raw audio file from resources like this:
int ThePlayedSound = this.getResources().getIdentifier("waterdrop", "raw", getPackageName());
Intent MyIntent= new Intent(this, MainActivity.class);
MyIntent.putExtra("key",ThePlayedSound);
startActivity(MyIntent);
What about using the MediaPlayer class?
Check this code below:
MainActivity class (or whatever class you want to start the new activity from)
Intent intent = new Intent(this,Main2Activity.class);
intent.putExtra("key",R.raw.waterdrop);
startActivity(intent);
Main2Activity (class that will play the audio)
public class Main2Activity extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitiy_main2);
int soundId = getIntent().getIntExtra("key",0);
final MediaPlayer mPlayer =new MediaPlayer();
mPlayer.setAudioSessionId(soundId);
mPlayer.setLooping(true);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.start();
}
});
}
}
This code worked for me.
If it says that that specific constructor doesnt work try the below one:
final MediaPlayer mPlayer =new MediaPlayer(this,soundId);
Hope it helps you out!

Android- Null pointer exception from getStringExtra using intent send a value to another activity by button click

I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836

Categories