i have this code in MainActivity.java:
String passName = new String(getString(R.string.name));
where name is a string in strings.xml:
<string name="name">My name</string>
it does not give me an error, but the app keeps crashing, how can i do this properly?
basically i want to save my name as a string variable in MainActivity.java, but store the actual text in strings.xml
i originally had:
String passName = new String("my name");
and i was able to successfully pass it to the second activity, but i want the text to be stored in strings.xml, not the .java file
edit: i have provided more of my code for context:
public class MainActivity extends AppCompatActivity {
Button button;
//code that will eventually point to my name in strings.xml
String passName = new String("my name");
//String passName = getResources().getString(R.string.name);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code that senses when the button is clicked
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code that executes when the button is clicked
Toast.makeText(getApplicationContext(),"Moving to second activity...",Toast.LENGTH_SHORT).show();
//code that passes my name to the second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", passName);
startActivity(intent);
}
});
}
}
as for a crash log, there doesn't seem to be one. when i launch the app it opens and then immediately closes again.
the message it gives me is this:
01/19 15:21:11: Launching 'app' on Pixel 4 XL API 30 (test).
Install successfully finished in 388 ms.
$ adb shell am start -n "my.name.n0000.lab_n0000/my.name.n0000.lab_n0000.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
edit: i have added the proper logcat dialogue:
2023-01-19 15:32:41.587 7562-7562/my.name.n00000.lab_n00000 E/AndroidRuntime: FATAL EXCEPTION: main
Process: my.name.n00000.lab_n00000, PID: 7562
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.name.n00000.lab_n00000/my.name.n00000.lab_n00000.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:97)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:134)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:128)
at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:612)
at my.name.n00000.lab_n00000.MainActivity.<init>(MainActivity.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
2023-01-19 15:32:41.615 7562-7562/my.name.n00000.lab_n00000 I/Process: Sending signal. PID: 7562 SIG: 9
There is a lifecycle involved when creating activities. Some things should not be accessed before the onCreate method is called. So you should be able to declare passName prior and then inside onCreate, you can initialise it.
public class MainActivity extends AppCompatActivity {
Button button;
String passName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code that senses when the button is clicked
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code that executes when the button is clicked
Toast.makeText(getApplicationContext(),"Moving to second activity...",Toast.LENGTH_SHORT).show();
//code that passes my name to the second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", passName);
startActivity(intent);
}
});
passName = getResources().getString(R.string.name);
}
}
You can read more about the activity lifecycle here
And in particular in this paragraph, it talks about instantiating class scope variables.
For example, your implementation of onCreate() might bind data to lists, associate the activity with a ViewModel, and instantiate some class-scope variables.
Related
I am trying to get an image into the ImageView but whenever I click a picture on the Gallery the app shows a blank screen and closes down.
This ImageView is in a fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_add, container, false);
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
dateTimeAction(v);
return v;
}
private void imageSelectAction(View v) {
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_image = v.findViewById(R.id.auction_add_imageView);
choosePicture();
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
if (data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
auction_add_image.setImageURI(selectedImageUri);
}
}
}
}
The Inital Declaration
public class auction_add extends Fragment {
private static final int SELECT_PICTURE = 10;
private static final int PERMISSION_CODE = 11;
ImageButton auction_add_imageViewButton;
//References to all Auction Add Page EditText
EditText auction_add_itemNameTxt;
EditText auction_add_descriptionTxt;
EditText auction_add_initialPriceTxt;
EditText auction_add_startTimeTxt;
EditText auction_add_endTimeTxt;
//Reference to ImageView
private ImageView auction_add_image;
final Calendar myCalendar = Calendar.getInstance();
Would Appreciate the help thanks!
Edit:
Followed is the error on the Run tab of Android Studio
W/System: A resource failed to call close.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.projectcrest, PID: 5618
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=242868079, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:377)
at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
I/Process: Sending signal. PID: 5618 SIG: 9
By looking into the exception it seems that the App is crashing in #onActivityResult function at line auction_add_image.setImageURI(selectedImageUri); due to NPE (Null Pointer Exception). This expection/crash is caused since the auction_add_image object has null value instead of an ImageView.
After taking an close look into your code, I think the issue has occured due to following code:
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
Note that in #onClick function you are passing view v on which you are going to perform the #findViewById operation. Here the passed view v refers to the auction_add_imageViewButton instead of the v you have captured above.
I would suggest to modify the code as below (just rename the v variable in #onClick function):
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
imageSelectAction(v);
}
});
This way the variable name collision could be avoided and the error would be resolved.
Also, in case this does not solve your problem, then please check whether the #findViewById is returning an ImageView instead of null. In case the Id provided to #findViewById is not present on the screen or in the child views of view (on which the #findViewById) is being performed then the #findViewById will return null value.
Also, check whether you have assigned null value to auction_add_image in anywhere your code.
In th below code, I am trying to pass instance of the activity to the GPSService and form weak reference between both contexts.
but at run time i receive the below error, which indicates that getApplicationContext() can not be casted to MainActivity
please let me know how should I pass instanceof the mainActivity to the service.
code:
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "GPS_READINGS", Toast.LENGTH_SHORT).show();
GPSService gpsService = new GPSService((MainActivity) getApplicationContext());
Intent intentStartGPSService = new Intent(getApplicationContext(), GPSService.class);
intentStartGPSService.setAction(ACTION_START_GPS_READING);
startService(intentStartGPSService);
}
});
service:
public GPSService(Context mainActivity) {
this.mWeakRefToMainActivity = new WeakReference<>((MainActivity) mainActivity);
}
//causes the same error
/*public GPSService(MainActivity mainActivity) {
this.mWeakRefToMainActivity = new WeakReference<>((MainActivity) mainActivity);
}*/
error:
2019-06-15 02:01:26.848 27745-27745/com.example.gps_v10 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.gps_v10, PID: 27745
java.lang.ClassCastException: android.app.Application cannot be cast to com.example.gps_v10.MainActivity
at com.example.gps_v10.MainActivity$1.onClick(MainActivity.java:49)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to pass an arraylist between two activities, but my app crashes at the second activity. Can someone help me solve in this problem...
Here,
I have two parts of my MainActivity from where sending arraylist to another Activity which is BankList Activity
Part 1:
Intent intent = new Intent(MainActivity.this, BankList.class);
intent.putStringArrayListExtra("BANKLIST",bankListArrayList);
startActivity(intent);
Part 2:
Result<ArrayList<Bank>> banklist = (Result<ArrayList<Bank>>)data;
if(banklist.getCode().equals("00")){
Toast.makeText(this,"list Banks success",Toast.LENGTH_SHORT).show();
bankListArrayList = new ArrayList<>();
for(Bank bank :banklist.getData()){
bank.getIin();
bank.getLogo();
bank.getName();
b
ankListArrayList.add(bank.toString());
}
Log.d("BANK_ARRAYLIST","BANK_ARRAYLIST"+bankListArrayList);
Toast.makeText(this,"BANK_ARRAYLIST"+bankListArrayList,Toast.LENGTH_SHORT).show();
}
My Second Activity (BankList)
public class BankList extends AppCompatActivity {
ListView bankList;
ArrayList<String> bankdataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_list);
bankList = (ListView)findViewById(R.id.bankList);
Intent intent = getIntent();
intent.getStringArrayListExtra("BANKLIST");
bankdataList.add(intent.toString());
Toast.makeText(BankList.this,"bank list"+bankdataList,Toast.LENGTH_SHORT).show();
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, bankdataList);
bankList.setAdapter(itemsAdapter);
}
}
And my Log is :-
11-09 12:58:01.548 1941-1941/com.example.rajdeeps.upi_integration E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rajdeeps.upi_integration, PID: 1941
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rajdeeps.upi_integration/com.example.rajdeeps.upi_integration.BankList}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.rajdeeps.upi_integration.BankList.onCreate(BankList.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
You forgot to initialize your bankdataList Arraylist just initialize it
ArrayList<String> bankdataList= new ArrayList();;
Sample code
public class BankList extends AppCompatActivity {
ListView bankList;
ArrayList<String> bankdataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_list);
bankdataList= new ArrayList();
bankList = (ListView)findViewById(R.id.bankList);
Intent intent = getIntent();
intent.getStringArrayListExtra("BANKLIST");
bankdataList.add(intent.toString());
Toast.makeText(BankList.this,"bank list"+bankdataList,Toast.LENGTH_SHORT).show();
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, bankdataList);
bankList.setAdapter(itemsAdapter);
}
}
You have not initialize bankdataList before add items.
bankdataList = new ArrayList<String>();
bankdataList.add(intent.getStringArrayListExtra("BANKLIST"));
Android 8. Start my app and immediate minimize. After few seconds I get error:
startActivity called from finishing ActivityRecord{7497c34 u0 com.myproject..dev/com.myproject.activity.SplashActivity t-1 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.myproject..dev/com.myproject.activity.RegistrationActivity }
Exception during pending activity launch pal=com.android.server.am.ActivityStackSupervisor$PendingActivityLaunch#a454565
java.lang.NullPointerException: Attempt to read from field 'android.content.Intent com.android.server.am.TaskRecord.intent' on a null object reference
at com.android.server.am.ActivityStarter.computeSourceStack(ActivityStarter.java:1425)
at com.android.server.am.ActivityStarter.startActivityUnchecked(ActivityStarter.java:983)
at com.android.server.am.ActivityStarter.startActivity(ActivityStarter.java:953)
at com.android.server.am.ActivityStarter.doPendingActivityLaunchesLocked(ActivityStarter.java:1964)
at com.android.server.am.ActivityManagerService$MainHandler.handleMessage(ActivityManagerService.java:2055)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.os.HandlerThread.run(HandlerThread.java:65)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
This error has only on Android 8. In another Android version has no this error.
In stacktrace no reference to specific row (as you can see). Only name of activity (SplashActivity).
Here my SplashActivity:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, RegistrationActivity.class));
}
}
I have implemented simple drill-down pattern with several activities that pass data to display. But when I go back (either android back button or toolbar's back button) my app crashes in onCreate because parameters are gone.
Ok, there are hundreds similar questions. Please read on. I did investigation and even senior developer reviewed my code and he did not understood.
This is a log how it was called:
TestItemsActivity.onCreate()
TestItemsActivity.onStart()
TestItemsActivity.onResume()
TestItemsActivity.onPause()
RunTestActivity.onCreate()
RunTestActivity.onStart()
RunTestActivity.onResume()
TestItemsActivity.onSaveInstanceState()
TestItemsActivity.onStop()
RunTestActivity.onPause()
TestItemsActivity.onCreate()
The last sentence is important - why is onCreate called again? Activity lifecycle says that onResume is expected.
Let's look at the source code. I use appcompat 7:25.1.
TestItemsActivity
public class TestItemsActivity extends AppCompatActivity {
TestScript script;
protected void onCreate(Bundle state) {
log.debug("onCreate()");
super.onCreate(state);
setContentView(R.layout.act_script_items);
if (state != null) {
script = (TestScript) state.getSerializable(ScriptListActivity.KEY_SCRIPT);
} else {
script = (TestScript) getIntent().getSerializableExtra(ScriptListActivity.KEY_SCRIPT);
}
...
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent(TestItemsActivity.this, RunTestActivity.class);
intent.putExtra(RunTestActivity.KEY_POSITION, position);
intent.putExtra(ScriptListActivity.KEY_SCRIPT, script);
TestItemsActivity.this.startActivity(intent);
}
});
}
protected void onSaveInstanceState(Bundle state) {
state.putSerializable(ScriptListActivity.KEY_SCRIPT, script);
super.onSaveInstanceState(state);
}
AppCompatActivity
public class RunTestActivity extends AppCompatActivity {
protected void onCreate(Bundle state) {
log.debug("onCreate()");
super.onCreate(state);
setContentView(R.layout.act_script_items);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarCalc);
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveTaskToBack(true);
}
});
}
Intent intent = getIntent();
script = (TestScript) intent.getSerializableExtra(ScriptListActivity.KEY_SCRIPT);
}
And now the most interesting source code is the manifest:
<activity
android:name=".activities.TestItemsActivity"
android:label="#string/action_academy"
android:parentActivityName=".activities.ScriptListActivity">
</activity>
<activity
android:name=".activities.RunTestActivity"
android:label="#string/action_academy"
android:parentActivityName=".activities.TestItemsActivity">
</activity>
Accidentally I found that if I remove parentActivityName than android's back button does not start new activity (onCreate) and my app does not crashes! Unfortunatelly toolbar's back button disappears.
Some SO questions I read:
Saving Android Activity state using Save Instance State
save the state when back button is pressed
How to save activity state after pressing back button?
Bundle savedInstanceState is always null
SavedInstantState created during onSaveInstanceState not restored in onCreate
Can somebody explains what is going there?
Complete stacktrace including parts that I removed from source code above. It fails in adapter because scripts instance is null. The activity failed to initialize it either from intent or bundle (which is null despite that onSaveInstanceState was called)
java.lang.RuntimeException: Unable to start activity ComponentInfo{lelisoft.com.lelimath.debug/lelisoft.com.lelimath.activities.TestItemsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List lelisoft.com.lelimath.data.TestScript.getItems()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List lelisoft.com.lelimath.data.TestScript.getItems()' on a null object reference
at lelisoft.com.lelimath.adapter.TestItemAdapter.<init>(TestItemAdapter.java:97)
at lelisoft.com.lelimath.activities.TestItemsActivity.onCreate(TestItemsActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
Update:
Workaround for this problem is to use a theme without a toolbar:
<activity
android:name=".activities.CampaignActivity"
android:label="#string/action_academy"
android:theme="#style/AppTheme.NoActionBar">
</activity>
Unfortunatelly I need the toolbar for one activity.
As you can see from the trace you provided, the activity was stopped and state was saved. Therefore later when activity is to be restored it will call onCreate().
TestItemsActivity.onSaveInstanceState()
TestItemsActivity.onStop()