Cannot load a java class/ layout file in android studio - java

After successfully passing the login screen, I have called the AddJournalActivity.java class.. However, it crashes, as shown in the video.. What do I do? This is the code for AddJournalActivity.java
package com.project.journeyjournal;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.StorageReference;
public class AddJournalActivity extends AppCompatActivity implements View.OnClickListener {
private static final int GALLERY_CODE = 1;
private Button saveButton;
private ImageView addPhotoButton;
private EditText titleEditText;
private EditText thoughtsEditText;
private ImageView imageView;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
//connection to firestore
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private StorageReference storageReference;
private CollectionReference collectionReference = db.collection("Journal");
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_journal);
firebaseAuth = FirebaseAuth.getInstance();
titleEditText = findViewById(R.id.post_title_et);
thoughtsEditText = findViewById(R.id.post_description_et);
imageView = findViewById(R.id.post_imageView);
saveButton = findViewById(R.id.post_save_journal_button);
saveButton.setOnClickListener(this);
addPhotoButton = findViewById(R.id.postCameraButton);
addPhotoButton.setOnClickListener(this);
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null){
} else{
}
}
};
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.post_save_journal_button:
//save Journal
break;
case R.id.postCameraButton:
//get image from camera or gallery
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK ){
if (data != null){
imageUri = data.getData();
imageView.setImageURI(imageUri);//show image
}
}
}
#Override
protected void onStart() {
super.onStart();
user = firebaseAuth.getCurrentUser();
firebaseAuth.addAuthStateListener((authStateListener));
}
#Override
protected void onStop() {
super.onStop();
if (firebaseAuth!= null){
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
}
I tried opening other pages instead of AddJournalActivity after the login activity, and it was working fine. If I delete all the code in the .java file, then the layout file opens just fine. So I assume that the problem is with AddJournalActivity.java. But I am unable to find it.
I have added the Logcat if it helps.2022-04-06 11:19:46.326 15573-15573/com.project.journeyjournal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.project.journeyjournal, PID: 15573 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457) 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:2044) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:224) at android.app.ActivityThread.main(ActivityThread.java:7560) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Caused by: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at com.project.journeyjournal.AddJournalActivity.onCreate(AddJournalActivity.java:51) at android.app.Activity.performCreate(Activity.java:7893) at android.app.Activity.performCreate(Activity.java:7880) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)  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:2044)  at android.os.Handler.dispatchMessage(Handler.java:107)  at android.os.Looper.loop(Looper.java:224)  at android.app.ActivityThread.main(ActivityThread.java:7560)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

I watched your video. Your app crashes after logging in.
By observing your logcat, I can see an error causing with CardView and ImageView. You didn't provide your XML Code, so I'm not sure what exactly is the cause.
Here check this line-
ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}:
java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView
Solution
Possibly you have a CardView in XML which has an ID post_imageView or postCameraButton and you're binding this ID to ImageView by calling
imageView = findViewById(R.id.post_imageView);
or
addPhotoButton = findViewById(R.id.postCameraButton);
Check your IDs in XML and let me know the update.

Related

how to fix android app crashing on startup? [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 months ago.
i'm a begginner developer and the app in question is a test app for an api, from jkutner's tutorial on github. it is crashing as soon as it opens, which is weird, because i've used this exact same code at least thrice and it used to work. i'll leave the code and the logcat below, thank you in advance for your help!
MainActivity
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity
{
final EditText isbnInput = (EditText) findViewById(R.id.isbnInput);
final TextView textView = (TextView) findViewById(R.id.textView);
final Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://venusdove.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
final BookService service = retrofit.create(BookService.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Book book = new Book(isbnInput.getText().toString());
Call<Book> createCall = service.create(book);
createCall.enqueue(new Callback<Book>() {
#Override
public void onResponse(Call<Book> _, Response<Book> resp) {
Book newBook = resp.body();
textView.setText("Created Book with ISBN: " + newBook.isbn);
}
#Override
public void onFailure(Call<Book> _, Throwable t) {
t.printStackTrace();
textView.setText(t.getMessage());
}
});
}
});
}
}
Book class
package com.example.myapplication;
import com.google.gson.annotations.SerializedName;
public class Book
{
#SerializedName("id")
int id;
#SerializedName("isbn")
String isbn;
public Book(int id, String isbn) {
this.id = id;
this.isbn = isbn;
}
public Book(String isbn) {
this.isbn = isbn;
}
}
BookService class
package com.example.myapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface BookService
{
#GET("books")
Call<List<Book>> all();
#GET("books/{isbn}")
Call<Book> get(#Path("isbn") String isbn);
#POST("books/new")
Call<Book> create(#Body Book book);
}
logcat
2022-10-19 08:56:03.651 8041-8041/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 8041
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' 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.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:655)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261)
at com.example.myapplication.MainActivity.<init>(MainActivity.java:22)
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)
You need to "find" view after they are created.
EditText isbnInput;
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isbnInput = (EditText) findViewById(R.id.isbnInput);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
}
It is because of findViewById. You should call it inside OnCreate. Because it needs View that it is being called from to be initialized.
private EditText isbnInput;
private TextView textView;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState)
{
isbnInput = (EditText) findViewById(R.id.isbnInput);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);

App crashing after trying to enter fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Hello my question is about my app is crash after I am trying to hit next fragment.
Code is compiling but i don't know how to solve this problem.
Something with onclicklistner.
I tried some solutions but didn't succeed.
This is my code:
ProfileFragment.java
package com.statusionew.statusio.fragments;
import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.statusionew.statusio.ForgetchangePasswordActivity; import com.statusionew.statusio.LoginActivity; import com.statusionew.statusio.R; import com.statusionew.statusio.MainActivity;
import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
public class ProfileFragment extends BaseFragment implements View.OnClickListener{
FirebaseAuth auth;
FirebaseUser user;
ProgressDialog PD;
#BindView(R.id.sign_out_button) Button btnSignOut;
#BindView(R.id.change_password_button) Button btnChangePass;
#BindView(R.id.change_email_button) Button btnChangeEmail;
#BindView(R.id.delete_user_button) Button btnDeleteUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_setting, container, false);
ButterKnife.bind(getActivity(), view);
((MainActivity) getActivity()).updateToolbarTitle("Profile");
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
PD = new ProgressDialog(getActivity());
PD.setMessage("Loading...");
PD.setCancelable(true);
PD.setCanceledOnTouchOutside(false);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.sign_out_button)
public void onClick(View view) {
auth.signOut();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
}
};
}
});
btnChangePass.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_password_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 1));
}
});
btnChangeEmail.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_email_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 2));
}
});
btnDeleteUser.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.delete_user_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 3));
}
});
}
#Override
public void onClick(View v) {
if (auth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
super.onResume();
} }
this the log that say 'Attempt to invoke virtual method'-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.statusionew.statusio, PID: 9206
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.statusionew.statusio.fragments.ProfileFragment.onCreate(ProfileFragment.java:65)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2339)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1109)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:996)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:99)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2364)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:781)
at com.statusionew.statusio.views.FragNavController.executePendingTransactions(FragNavController.java:631)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:142)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:158)
at com.statusionew.statusio.MainActivity.switchTab(MainActivity.java:149)
at com.statusionew.statusio.MainActivity.access$100(MainActivity.java:30)
at com.statusionew.statusio.MainActivity$1.onTabSelected(MainActivity.java:87)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Connected to process 10580 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.statusionew.statusio-1/lib/x86
D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
V/FA: Registered activity lifecycle callback
I/FirebaseInitProvider: FirebaseApp initialization successful
I/InstantRun: starting instant run server: is main process
E/InstantRun: IO Error creating local socket at com.statusionew.statusio
java.io.IOException: Address already in use
at android.net.LocalSocketImpl.bindLocal(Native Method)
at android.net.LocalSocketImpl.bind(LocalSocketImpl.java:308)
at android.net.LocalServerSocket.<init>(LocalServerSocket.java:48)
at com.android.tools.ir.server.Server.<init>(Server.java:91)
at com.android.tools.ir.server.Server.create(Server.java:85)
at com.android.tools.ir.server.InstantRunContentProvider.onCreate(InstantRunContentProvider.java:49)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
It seems like you've got some misunderstandings about how Fragments and ButterKnife work.
OnCreate is called BEFORE onCreateView in a Fragment. So all your views are null when you're trying to access them in onCreate.
See Fragment Lifecycle:
https://www.tutorialspoint.com/android/images/fragment.jpg
OnCreate is not used that much in Fragments, onCreateView is used more.
Your ButterKnife bind code is also wrong. You're trying to bind the Activity to the views in the Fragment.
See ButterKnife documentation for correct usage: http://jakewharton.github.io/butterknife/

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!

Photo by Camera Upload Exception (Firebase Storage)

I'm trying to upload an image taken by the camera in an android application to Firebase storage. The problem is that after I take the picture, in the confirmation activity, I pressed the confirm button and it says that "Unfortunately the application stopped".
This is the image when I press the check button, and the app crashes...
This is my code, the application has the option to upload pictures using the gallery and the camera.
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private Button selectImage;
private Button selectImageByCamera;
private ImageView imageView;
private StorageReference storageReference;
private ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int GALLERY_INTENT= 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
storageReference=FirebaseStorage.getInstance().getReference();
/*
* Code section to upload an image using the Gallery.
*/
selectImage=(Button)findViewById(R.id.btn_uploadImg);
progressDialog = new ProgressDialog(this);
selectImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
/*
* Code section to upload an image using the Camera.
*/
selectImageByCamera=(Button)findViewById(R.id.btn_uploadImgCamera);
imageView=(ImageView)findViewById(R.id.imageView);
selectImageByCamera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//Upload the image to Firebase Update
if(requestCode==GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
//Code to upload image taken by the camera to firebase storage
if(requestCode==CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri2 = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri2.getLastPathSegment());
filepath.putFile(uri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
{
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have this USER PERMISSIONS in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
I have this Firebase dependencies in app/build.gradle
compile 'com.google.firebase:firebase-core:9.8.0'
compile 'com.google.firebase:firebase-database:9.8.0'
compile 'com.google.firebase:firebase-storage:9.8.0'
compile 'com.google.firebase:firebase-auth:9.8.0'
And finally this is the exception thrown when I run the app in my Moto G4 6.0.1 (The app has permissions to use Camera and Gallery)
FATAL EXCEPTION: main
Process: mx.com.jamba.jamba, PID: 16543
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {mx.com.jamba.jamba/mx.com.jamba.jamba.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at mx.com.jamba.jamba.MainActivity.onActivityResult(MainActivity.java:186)
at android.app.Activity.dispatchActivityResult(Activity.java:6470)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763) 
at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
I don't know what to do, it would be great if you guys to help me :)
Thank you!
The exception occurs because the Uri in onActivityResult() is null:
Uri uri = data.getData();
The documentation for capturing a camera image explains:
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Follow the example in the documentation to create a file Uri and add it to the intent for the camera app.
Please try this
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
select.setImageBitmap(mImageUri);
}
then start posting

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