Android - Attempt to invoke method '...' on a null object reference - java

I'm getting the error 'Attempt to invoke method '...' on a null object reference' on Android when trying to access a field which was set previously.
I check upon setting it that it's not null, but when it's accessed in a different activity, it 'null'.
This field is created along with multiple others' and for some reason, it's the only one which appear to old a null reference.
Object in question
public enum Locations {
Meeting_Room,Office_245,Lobby,NOC,VPsoffice
}
Class declaration:
public class Task implements Serializable {
private long taskId;
private String description;
private Boolean completed = false;
private Category task_catg;
private Task_Status task_sts;
private Locations tsk_location;
}
public Locations getTsk_location() {
return tsk_location;
}
public void setTsk_location(Locations tsk_location) {
this.tsk_location = tsk_location;
}
Please note that Task_Status & Category are also enums, and I do not encounter any issues with them.
This is where the object is initialized, I've added prints here and saw that the value returned from the activity is not null.
New Task activity
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK) {
switch (requestCode) {
case ACTIVITY_SELECT_LOCATION:
{
/*returned_selc_loc = (Locations) data.getSerializableExtra("location");
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);*/
switch(Globals.temp)
{
case 0:
returned_selc_loc=Locations.Meeting_Room;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 1:
returned_selc_loc=Locations.Office_245;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 2:
returned_selc_loc=Locations.Lobby;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 3:
returned_selc_loc=Locations.NOC;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 4:
returned_selc_loc=Locations.VPsoffice;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
}
break;
}
default:
break;
}
}
}
This is where the Task object is created and the Location is set:
New Task activity
public void addTaskBtn (View view)
{
boolean state=true;
EditText desc = (EditText)findViewById(R.id.newTaskDesc);
EditText date = (EditText)findViewById(R.id.taskDateEdit);
EditText time = (EditText)findViewById(R.id.taskTimeEdit);
loc = (EditText)findViewById(R.id.taskLocation);
Date myDate = null;
RadioButton rb;
String emp_name;
t = new Task(desc.getText().toString());
t.setTask_sts(Task_Status.WAITING);
int position = spin.getSelectedItemPosition();
switch(position)
{
case 0:
t.setTask_catg(Category.GENERAL);
break;
case 1:
t.setTask_catg(Category.CLEANING);
break;
case 2:
t.setTask_catg(Category.ELECTRICITY);
break;
case 3:
t.setTask_catg(Category.COMPUTERS);
break;
case 4:
t.setTask_catg(Category.OTHER);
break;
}
//Added prints here and value is set correctly, definitely not NULL.
t.setTsk_location(returned_selc_loc);
t.setTaskId(task_id);
task_id++;
Intent returnIntent = new Intent();
dbm = DBManager.getInstance(this);
long seq_tsk_id = dbm.addTask(t);
t.setTaskId(seq_tsk_id);
returnIntent.putExtra("task", t);
setResult(RESULT_OK, returnIntent);
finish();
}
This is the call to the Edit Task activity, the call is from the MainActivity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbM = DBManager.getInstance(context);
itemList = dbM.getAllTasks();
list.setAdapter(new TaskItemAdapter(context, itemList));
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long arg3) {
//get item instance from list
Task tt = (Task) ((TaskItemAdapter) parent.getAdapter()).getItem(position);
if(true)
{
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), EditTaskActivity.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_UPDATE_TASK);
}
return false;
}
});
}
Edit Task activity
This is I get the error (left only relevant part, as other variables in the object are successfully,
public void deleteTaskBtn(View view)
{
Intent returnIntent = new Intent(this,MainActivity.class);
Intent i = getIntent();
tastToEdit = (Task)i.getSerializableExtra("task");
tastToEdit.setToDelete(true);
ParseObject parse_task = new ParseObject("Task");
parse_task.put("Description",tastToEdit.getDescription());
parse_task.put("DueDate",tastToEdit.getDueDate());
parse_task.put("Priority",tastToEdit.getPriority().ordinal());
int com_state = (tastToEdit.getCompleted()) ? 1 : 0;
parse_task.put("IsCompleted",com_state);
parse_task.put("Location", tastToEdit.getTsk_location().ordinal());
parse_task.put("Category",tastToEdit.getTask_catg().ordinal());
parse_task.put("Status", tastToEdit.getTask_sts().ordinal());
parse_task.put("TeamName",Globals.team_name);
parse_task.put("Employee",tastToEdit.getEmp_name());
parse_task.deleteInBackground(new DeleteCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d("msg","deleted");
} else {
Log.d("msg", "not deleted");
e.printStackTrace();
}
}
});
returnIntent.putExtra("task",tastToEdit);
setResult(RESULT_OK, returnIntent);
finish();
}
This line returns that NULL reference:
Location selected_loc = tastToEdit.getTsk_location();
Full error stack
03-09 21:28:20.192 10425-10425/? I/art: Late-enabling -Xcheck:jni
03-09 21:28:20.229 10425-10433/? I/art: Debugger is no longer active
03-09 21:28:20.240 10425-10425/? W/System: ClassLoader referenced unknown path: /data/app/il.ac.shenkar.david.todolistex2-1/lib/arm
03-09 21:28:20.446 10425-10456/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-09 21:28:20.508 10425-10456/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
03-09 21:28:20.511 10425-10456/? I/OpenGLRenderer: Initialized EGL, version 1.4
03-09 21:28:27.832 10425-10425/il.ac.shenkar.david.todolistex2 I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
03-09 21:28:28.397 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb38ccf80 (RippleDrawable) with handle 0xaef7fe30
03-09 21:28:29.620 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb39ba400 (RippleDrawable) with handle 0xaef7f9e0
03-09 21:28:30.360 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb397f900 (RippleDrawable) with handle 0xb3b29370
03-09 21:28:32.921 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0x9f2cbb80 (ListPopupWindow$DropDownListView) with handle 0xb3b29530
03-09 21:28:33.437 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0x9f2cad80 (RippleDrawable) with handle 0xb3b295d0
03-09 21:28:40.866 10425-10456/il.ac.shenkar.david.todolistex2 V/RenderScript: 0x9dca9000 Launching thread(s), CPUs 4
03-09 21:28:40.907 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb3947700 (RippleDrawable) with handle 0xb3b29910
03-09 21:28:44.971 10425-10425/il.ac.shenkar.david.todolistex2 W/sdas: null
03-09 21:28:45.143 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb39b5380 (ListView) with handle 0xaef7f510
03-09 21:28:48.110 10425-10425/il.ac.shenkar.david.todolistex2 D/AndroidRuntime: Shutting down VM
03-09 21:28:48.111 10425-10425/il.ac.shenkar.david.todolistex2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: il.ac.shenkar.david.todolistex2, PID: 10425
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:278)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
at android.view.View.performClick(View.java:5204) 
at android.view.View$PerformClick.run(View.java:21153) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int il.ac.shenkar.david.todolistex2.Location.ordinal()' on a null object reference
at il.ac.shenkar.david.todolistex2.EditTaskActivity.deleteTaskBtn(EditTaskActivity.java:372)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273) 
at android.view.View.performClick(View.java:5204) 
at android.view.View$PerformClick.run(View.java:21153) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
But as you can see, this field is set successfully previously, in another activity.
What can be the cause?

It looks to me that it's not about whether or not the field has been set, but rather the object you are trying to pull off the intent isn't there on this line in the onCreate:
tastToEdit = (Task)i.getSerializableExtra("task");
Add a check after this to see whether tastToEdit is null, and if so investigate why it hasn't been properly added to the intent if this is the case.

It looks like you're mistaken about what happens to the intent that you populated in one Activity's onActivityResult(). That method is responsible for handling the result of the next activity which was invoked with startActivityForResult(). That next activity can set a result for the prior activity using setResult(), which becomes available in onActivityResult() when the invoked activity finish.
However it looks like you're expecting getIntent() in "a different activity" to be able to see that Intent you created in onActivityResult(). That's simply not the case. getIntent() returns the activity that was used to start the current activity that you're working with. It's completely unrelated the intent from an activity result. So you'll need to change your strategy for passing data around between these activities.

Related

Night mode to SharedPreferences is only causing errors

I theoretically have 2 related questions.
1) I tried to make a night mode for my app. That works so far pretty good. Then I wanted to put the setting the User chooses to SharedPreferences. In my first try, It just didn't work. All I did was getting red and causing errors. After a lot of research on the Internet, I found another idea. Now the app is starting but crashing immediately again. The error has to be in the SharedPreferences because as soon as I delete this part it is working again. I just can't find the error and it doesn't show me a red area or so either.
2) Just to check if my research are right. Is it true that it is not possible anymore to make a time-related Night mode? Means dark at night, light at day? I found out that MODE_NIGHT_AUTO_TIME was supposed to do that but is deprecated and they suggest to use MODE_NIGHT_AUTO_BATTERY which is kinda something really different.
btw. here is my code if it helps from the Setting:
public class Settings extends AppCompatActivity {
private static final String TAG = "SettingsActivity";
private RelativeLayout layout;
private SharedPreferences preferences;
private Bundle savedInstanceState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Spinner spinner = findViewById(DarkMode);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "onItemSelected: " + position);
handleNightMode(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.e(TAG, "onNothingSelected: ");
}
});
}
private void handleNightMode(int position) {
switch (position) {
case 0:
Log.e(TAG, "Nothing Selected");
break;
case 1:
Log.e(TAG, "FOLLLOW_SYSTEM");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
getDelegate().applyDayNight();
break;
case 2:
Log.e(TAG, "YES");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getDelegate().applyDayNight();
break;
case 3:
Log.e(TAG, "NO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
getDelegate().applyDayNight();
break;
case 4:
Log.e(TAG, "AUTO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
getDelegate().applyDayNight();
break;
default:
Log.e(TAG, "FOLLLOW_SYSTEM");
break;
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String NightMode = preferences.getString("prefTheme", "NO");
if (NightMode.equals("YES"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
if (NightMode.equals("NO"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
else if (NightMode.equals("AUTO"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
the MainActivity:
public class MainActivity extends AppCompatActivity {
int currentDayNight;
private Button settings;
private RelativeLayout layout;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = findViewById(R.id.layout);
settings = findViewById(R.id.btn_settings);
currentDayNight = AppCompatDelegate.getDefaultNightMode();
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSettings();
}
});
}
private void openSettings() {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
}
logcat:
04-16 21:31:59.861 11136-11136/? I/art: Not late-enabling -Xcheck:jni (already on)
04-16 21:32:00.033 11136-11136/com.goldenegg.darkmode W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-16 21:32:00.086 11136-11136/com.goldenegg.darkmode I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-16 21:32:00.087 11136-11136/com.goldenegg.darkmode I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-16 21:32:00.168 11136-11149/com.goldenegg.darkmode I/art: Background partial concurrent mark sweep GC freed 523(79KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 1007KB/2031KB, paused 6.320ms total 27.683ms
04-16 21:32:00.204 11136-11136/com.goldenegg.darkmode D/AndroidRuntime: Shutting down VM
--------- beginning of crash
04-16 21:32:00.205 11136-11136/com.goldenegg.darkmode E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.goldenegg.darkmode, PID: 11136
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.goldenegg.darkmode/com.goldenegg.darkmode.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: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 android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.goldenegg.darkmode.MainActivity.onCreate(MainActivity.java:34)
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) 
Thanks for your Help.
have a great day

App crashes when I call a constructor in an Activity

I am new to android studio and I am trying to build a Notepad app.
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String title = findViewById(R.id.textView3).toString();
String note_content = findViewById(R.id.textView).toString();
FileOutputStream outputStream;
try
{
outputStream = openFileOutput(title, Context.MODE_PRIVATE);
outputStream.write(note_content.getBytes());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
MainActivity mainActivity = new MainActivity(title);
}
});
This is the button a user clicks to save the note. Once the code saves the note, it should send the Title to MainActivity so that it can be sent to Recycleview Adapter - this will display it in viewholder as a text.
Presently, when I run the code, it crashes - however, when I remove the constructor, the app works fine.
( MainActivity mainActivity = new MainActivity(title);)
Error:
10-02 02:39:13.822 27279-27279/? D/AndroidRuntime: Shutting down VM
10-02 02:39:13.824 27279-27279/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quicknote, PID: 27279
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.quicknote/com.example.quicknote.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2337)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
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.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
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) 
10-02 02:39:20.081 27279-27279/com.example.quicknote I/Process: Sending signal. PID: 27279 SIG: 9
As per the error message:
java.lang.InstantiationException: java.lang.Class has no zero argument constructor
A zero argument constructor is required for the Android system to instantiate an Activity. You should never be manually calling an Activity constructor yourself since only the system can properly create an Activity.
The Parcelables and Bundles documentation details the correct way of sending information to an Activity using the extras Bundle.
Unable to instantiate activity. Because you can't start an activity like this. You have to use intent to start activity. To sent "title" use intent extra.
Intent intent=new Intent(CurrentActivity.this, NewActivty.this);
intent.putExtra("title", title);
startActivty(intent);
Is your Activity in your AndroidManifest.xml?
If it is, you have to retrieve the title from your extras from onCreate() of MainActivity instead from the constructor.
Something like that:
//that code instead of your MainActivity mainActivity = new MainActivity(title); line
Intent intent = new Intent(YourActualActivity.this, MainActivity.class);
intent.putExtra("title", title);
startActivity(intent);
//That code in the onCreate method of your MainActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString("title");
}

App crashes when file is shared in Fragment

I have a Fragment which is attached to MainActivity. It displays an image. User has to share the image but the app crashes when clicking the share button.
This is the Fragment code:
Context mcontext = getActivity();
case R.id.item_share: {
final Uri uri = FileProvider.getUriForFile(mcontext, "com.whats.insta", file);
final Intent intent = ShareCompat.IntentBuilder
.from((Activity)mcontext)
.setType("image/jpg")
.setStream(uri)
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mcontext.startActivity(intent);*/
break;
}
Crash log
09-05 10:41:05.410 26011-26011/com.whats.insta E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.whats.insta, PID: 26011
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.app.Activity.getPackageName()' on a null object reference
at android.support.v4.app.ShareCompat$IntentBuilder.<init>(ShareCompat.java:216)
at android.support.v4.app.ShareCompat$IntentBuilder.from(ShareCompat.java:210)
at com.whats.insta.ui.imageslider.imagedetails.ImageDetailsFragment.onOptionsItemSelected(ImageDetailsFragment.java:267)
at android.support.v4.app.Fragment.performOptionsItemSelected(Fragment.java:2476)
at android.support.v4.app.FragmentManagerImpl.dispatchOptionsItemSelected(FragmentManager.java:3343)
at android.support.v4.app.FragmentController.dispatchOptionsItemSelected(FragmentController.java:347)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:413)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
at android.view.View.performClick(View.java:6261)
at android.widget.TextView.performClick(TextView.java:11185)
at android.view.View$PerformClick.run(View.java:23752)
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:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
You must check if the implicit intent resolves to at least one activity otherwise application crashes.
// Verify the intent will resolve to at least one activity
if (mContext != null && intent.resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
}

"java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState" on fragmentTransaction.commit()

I couldn't seem to get my head around this one. I have already gone through possible solutions Stack Overflow has to offer.
I have 2 activities, say, A and B; when I go back to A from B and then selecting an image come back to B, none of the fragment transaction works and throws error as shown below.
Code:
MainMenuFragment.java
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.menu_filter:
activity.changeMode(EditImageActivity.MODE_FILTERS);
activity.sliderFragment.resetBitmaps();
activity.changeMiddleFragment(EditImageActivity.MODE_FILTERS);
break;
case R.id.menu_enhance:
activity.changeMode(EditImageActivity.MODE_ENHANCE);
activity.sliderFragment.resetBitmaps();
activity.changeMiddleFragment(EditImageActivity.MODE_ENHANCE);
break;
case R.id.menu_adjust:
activity.changeMode(EditImageActivity.MODE_ADJUST);
activity.changeMiddleFragment(EditImageActivity.MODE_ADJUST);
break;
case R.id.menu_sticker:
activity.changeMode(EditImageActivity.MODE_STICKER_TYPES);
activity.changeMiddleFragment(EditImageActivity.MODE_STICKER_TYPES);
break;
case R.id.menu_write:
activity.changeMode(EditImageActivity.MODE_WRITE);
activity.changeMiddleFragment(EditImageActivity.MODE_WRITE);
break;
}
}
EditImageActivity.java
public void changeMiddleFragment(int index) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.slide_up, R.anim.slide_down);
transaction.replace(R.id.preview_container, getFragment(index, this));
transaction.commit();
}
Error:
FATAL EXCEPTION: main
Process: org.ArtIQ.Rex, PID: 9739
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
at org.ArtIQ.Rex.editor.EditImageActivity.changeMiddleFragment(EditImageActivity.java:392)
at org.ArtIQ.Rex.editor.fragment.MainMenuFragment.onClick(MainMenuFragment.java:82)
at android.view.View.performClick(View.java:5637)
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)
Changing transaction.commit() to transaction.commitAllowingStateLoss() should resolve this.

Error free build but crashes on click in music player in android studio

I'm new to programming and have been assigned to code a simple music player, there were slides to help guide and I have slightly altered them (can't use the exact same variables).
So now it's error free but when I click on the play button it crashes, no idea why. Here's my code for the page where I select the library:
package sg.edu.tp.project1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import sg.edu.tp.project1.util.AppUtil;
public class myMusic extends AppCompatActivity {
private String[] Musicsong = new String[6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_music);
//store values in array of the first song
Musicsong[0] = "s1001";
Musicsong[1] = "The Way You Look Tonight";
Musicsong[2] = "ed sheeran";
Musicsong[3] = "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null";
Musicsong[4] = "4.39";
Musicsong[5] = "music to play";
}
public void sendDataToActiviy(String[] song)
{
//1.create intent and specify destination
Intent intent = new Intent(this, PlayMusicActivity.class);
//2.store song info in intent to send to destination
intent.putExtra("id", song[0]);
intent.putExtra("title",song[1]);
intent.putExtra("artist",song[2]);
intent.putExtra("fileLink",song[3]);
intent.putExtra("coverArt",song[5]);
//3. launch desntination activiy
startActivity(intent);
}
public void handleSelection(View view)
{
// 1. get id of selected song
String resourceId = AppUtil.getResourceId(this, view);
//2. Search for the selected song based on the ID so that
// all infomation of the song can be retreived
String[] selectedSong =searchById(resourceId);
//3.popup to show tittle of song
AppUtil.popMessage(this, "Streaming song:" + selectedSong[1]);
//4. send song data to player screen
sendDataToActiviy(selectedSong);
}
private Object[] songs = {Musicsong};
public String[] searchById(String id) {
//temporary empty array
String[] song = null;
//for loop to get song
for (int index = 0; index < songs.length; index++) {
//3. store each song item to song array.
song = (String[]) songs[index];
//4. match song id to see if its the one i want
if (song[0].equals(id)) {
return song;
}
}
//if song not found in array empty array will be returned
return song;
}
}
This part where the player is:
package sg.edu.tp.project1;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import sg.edu.tp.project1.util.AppUtil;
public class PlayMusicActivity extends AppCompatActivity
{
//streaming website
private static final String BASE_URL = "https://p.scdn.co/mp3-preview/";
private String songId ="";
private String title = "";
private String artist = "";
private String fileLink = "";
private String coverArt = "";
private String url = "";
//builtin media player
private MediaPlayer player = null;
//position of song in playback
private int musicPosition = 0;
//button variable to link to play btn
private Button btnPlayPause = null;
private String[] Musicsong = {
"s1001",
"The Way You Look Tonight",
"ed sheeran",
"a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",
"4.39",
"music to play"};
private Object[] songs = {Musicsong};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_music);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
retrieveData();
displaySong(title,artist,coverArt);
}
private void retrieveData() {
Bundle songData = this.getIntent().getExtras();
songId = songData.getString("id");
title = songData.getString("title");
artist = songData.getString("artist");
fileLink = songData.getString("fileLink");
coverArt = songData.getString("coverArt");
url = BASE_URL + fileLink;
}
private void displaySong(String title, String artist, String coverArt)
{
//retrieve song title
TextView txtTitle = (TextView) findViewById(R.id.txtSongTitle);
//set text of song title
txtTitle.setText(title);
//retrieve artist
TextView txtArtist = (TextView) findViewById(R.id.txtArtist);
//set text of artist
txtArtist.setText(artist);
//get id of coverart
int imageId = AppUtil.getImageIdFromDrawable(this,coverArt);
//retrieve coverart
ImageView ivCoverArt = (ImageView) findViewById(R.id.imgCoverArt);
ivCoverArt.setImageResource(imageId);
}
public void playOrPauseMusic(View view)
{// start player
player.start();
//2.
btnPlayPause.setText("PAUSE");
//3.set the heading title of played song
setTitle("Now Playing:" + title + "-" + artist);
}
private void preparePlayer() { //create a new player
player = new MediaPlayer();
try {
//set stream type to music
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set source of music
player.setDataSource(url);
//prepare player for playback
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}}
Logs:
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 I/art: Not late-enabling -Xcheck:jni (already on)
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 W/art: Unexpected CPU variant for X86 using defaults: x86
08-10 16:04:02.535 2567-2567/sg.edu.tp.project1 W/System: ClassLoader referenced unknown path: /data/app/sg.edu.tp.project1-2/lib/x86
08-10 16:04:02.539 2567-2567/sg.edu.tp.project1 I/InstantRun: Starting Instant Run Server for sg.edu.tp.project1
08-10 16:04:02.913 2567-2567/sg.edu.tp.project1 W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-10 16:04:03.399 2567-2632/sg.edu.tp.project1 I/OpenGLRenderer: Initialized EGL, version 1.4
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 1
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 0
08-10 16:04:03.490 2567-2567/sg.edu.tp.project1 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-10 16:04:14.759 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8d2e9b00 (RippleDrawable) with handle 0x8d2ff830
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Do partial code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: After code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Increasing code cache capacity to 128KB
08-10 16:04:27.463 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8c313a00 (RippleDrawable) with handle 0x8d2ff420
08-10 16:04:29.695 2567-2567/sg.edu.tp.project1 D/AndroidRuntime: Shutting down VM
Beginning of crash:
08-10 16:04:29.696 2567-2567/sg.edu.tp.project1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.project1, PID: 2567
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637) 
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) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5637) 
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) 
The exception message is very clear:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
So your player field is null because you've never called PlayMusicActivity's preparePlayer() before.

Categories