0

I am trying to get my app up and running but I am facing with the problem so I am trying to save screen state when Android orientation changes but the app is always keeping crashing all the time and I am getting the following error above otherwise the app is working fine. I think that the last 2 methodes (onSaveInstanceState and onRestoreInstanceState) are causing the problem.

I appreciate any help.

03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3924)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.ActivityThread.access$1000(ActivityThread.java:161)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1271)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.os.Handler.dispatchMessage(Handler.java:102)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.os.Looper.loop(Looper.java:157)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.ActivityThread.main(ActivityThread.java:5356)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at java.lang.reflect.Method.invokeNative(Native Method)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at java.lang.reflect.Method.invoke(Method.java:515)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at dalvik.system.NativeStart.main(Native Method)
03-30 15:14:40.199: E/AndroidRuntime(18902): Caused by: java.lang.NullPointerException
03-30 15:14:40.199: E/AndroidRuntime(18902):  at com.planetplace.GPSAPlanetActivity.onRestoreInstanceState(GPSAPlanetActivity.java:212)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.Activity.performRestoreInstanceState(Activity.java:949)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1156)
03-30 15:14:40.199: E/AndroidRuntime(18902):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
03-30 15:14:40.199: E/AndroidRuntime(18902):  ... 12 more

GPSAPlanetActivity:

package com.planetplace;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.plant.abc.Plant;

public class GPSAPlanetActivity extends Activity implements LocationListener {

 private static final String PLANT2 = "PLANT";
 private static final String LONGITUDE2 = "Longitude";
 private static final String LATITUDE2 = "Latitude";
 EditText description;
 TextView txtSelectedPlant;
 public final static int CAREA_RESULT = 5;
 public Bitmap plantImage;
 private ImageView imgPlant;
 private LocationManager LocationManager;
 private Plant plant;
 private double latitude;
 private double longitude;
 private TextView lblLatitudeValue;
 private TextView lblLongitudevalue;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_gps_plants);
  description = (EditText) findViewById(R.id.etDescription);
  txtSelectedPlant = (TextView) findViewById(R.id.tvSelectedPlant);

  // get a references to the image view that will display a plant photot.
  imgPlant = (ImageView) findViewById(R.id.imgPlant);

  // get the LocationManager as a system service. Save it into a field
  LocationManager = (android.location.LocationManager) getSystemService(LOCATION_SERVICE);

  lblLatitudeValue = (TextView) findViewById(R.id.tvLatt);
  lblLongitudevalue = (TextView) findViewById(R.id.tvLong);

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @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();
  if (id == R.id.action_settings) {
   return true;
  }
  return super.onOptionsItemSelected(item);
 }

 public void searchClicked(View v) {
  Intent searchIntent = new Intent(this, AdvancedSearchActivity.class);

  startActivityForResult(searchIntent,
    AdvancedSearchActivity.PLANT_RESULTS);

 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
  if (resultCode == RESULT_OK) {

   if (requestCode == AdvancedSearchActivity.PLANT_RESULTS) {
    // change the label of the text view to be the plant that was
    // passed
    // in

    // store the plant as an attribute
    Plant plant = (Plant) data
      .getSerializableExtra(PlantResultActivity.PLANT_RESULT);

    // set this plant in the TextView on the UI
    txtSelectedPlant.setText(plant.toString());
   } else if (requestCode == CAREA_RESULT) {
    // we are here because we received result from the camera
    plantImage = (Bitmap) data.getExtras().get("data");

    imgPlant.setImageBitmap(plantImage);
   }
  }
 }

 public void onTakePhotoClicked(View v) {
  // use an implicit intent to invoke the camera
  Intent cameraIntent = new Intent(
    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

  // start this intent, and antipcipate a result.
  startActivityForResult(cameraIntent, CAREA_RESULT);

 }

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  requestLocation();
 }

 private void requestLocation() {
  // TODO Auto-generated method stub
  if (LocationManager != null) {
   // the variable locationManger has an object assigned to it if we
   // have gotten inside this
   // if test. we want to do a null check like this first, because we
   // want to avoid a NullPointerException.

   // request location update
   LocationManager.requestLocationUpdates(
     LocationManager.GPS_PROVIDER, 60000, 0, this);

  }
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
 }

 @Override
 protected void onStart() {
  // TODO Auto-generated method stub
  super.onStart();
 }

 // this method will be invoked when the GPS service informs us that us that
 // our Location has changed.
 // Anything that we want to do that should be updated when the GPS position
 // of our phone as moved
 // we must do in this method
 @Override
 public void onLocationChanged(Location location) {
  // TODO Auto-generated method stub
  latitude = location.getLatitude();
  longitude = location.getLongitude();

  updateUIForLocation();

 }

 private void updateUIForLocation() {
  // update our user interface.
  lblLatitudeValue.setText("" + latitude);
  lblLongitudevalue.setText("" + longitude);
 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onProviderEnabled(String provider) {
  // TODO Auto-generated method stub

 }

 @Override
 public void onProviderDisabled(String provider) {
  // TODO Auto-generated method stub

 }
 //This method is called right before we change orientation, so that we can preserve values when the screen is redrawn
 @Override
 protected void onSaveInstanceState(Bundle outState) {
  // TODO Auto-generated method stub
  super.onSaveInstanceState(outState);
  outState.putDouble(LATITUDE2, latitude);
  outState.putDouble(LONGITUDE2, longitude);
  outState.putSerializable(PLANT2, plant);
  

 }
 /**
  * Dispaly values in the UI that were saved right before orientation changed.
  */
 @Override
 protected void onRestoreInstanceState(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onRestoreInstanceState(savedInstanceState);
  //repopulate values from the bundle we created in onSaveInstanceState method.
  latitude  = savedInstanceState.getDouble(LATITUDE2);
  longitude  = savedInstanceState.getDouble(LONGITUDE2);
  updateUIForLocation();
  plant = (Plant) savedInstanceState.getSerializable(PLANT2);
  txtSelectedPlant.setText(plant.toString());
 }

}

Plant class:

package com.plant.abc;

import java.io.Serializable;

public class Plant implements Serializable {

 private String genus;
 private String species;
 private String cultivar;
 private String common;
 private int id;
 private int guid;

 public String getGenus() {
  return genus;
 }

 public void setGenus(String genus) {
  this.genus = genus;
 }

 public String getSpecies() {
  return species;
 }

 public void setSpecies(String species) {
  this.species = species;
 }

 public String getCultivar() {
  return cultivar;
 }

 public void setCultivar(String cultivar) {
  this.cultivar = cultivar;
 }

 public String getCommon() {
  return common;
 }

 public void setCommon(String common) {
  this.common = common;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public int getGuid() {
  return guid;
 }

 public void setGuid(int guid) {
  this.guid = guid;
 }

 @Override
 public String toString() {
  // TODO Auto-generated method stub
  return genus + " " + species + " " + common;
 }

}

XML file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.plantplaces.GPSAPlanetActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="GPS A Planet" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:text="Description of the Plant" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/bntSearchPlant"
        android:layout_below="@+id/bntSearchPlant"
        android:layout_marginTop="52dp"
        android:text="Lattitude" />

    <TextView
        android:id="@+id/tvLatt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView3"
        android:layout_toRightOf="@+id/etDescription"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:text="Longitude" />

    <TextView
        android:id="@+id/tvLong"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView4"
        android:layout_alignBottom="@+id/textView4"
        android:layout_alignLeft="@+id/tvLatt"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:text="Selected Plant" />

    <TextView
        android:id="@+id/tvSelectedPlant"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvLong"
        android:layout_below="@+id/tvLong"
        android:text="TextView" />

    <Button
        android:id="@+id/btnCaptureImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView5"
        android:layout_alignRight="@+id/bntSearchPlant"
        android:layout_below="@+id/textView5"
        android:layout_marginTop="14dp"
        android:onClick="onTakePhotoClicked"
        android:text="Take Photo" />

    <EditText
        android:id="@+id/etDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="15dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/bntSearchPlant"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView2"
        android:layout_below="@+id/etDescription"
        android:onClick="searchClicked"
        android:text="select a Planet" />

    <ImageView
        android:id="@+id/imgPlant"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/btnCaptureImage"
        android:src="@drawable/abc_ab_share_pack_holo_dark" />

</RelativeLayout>
Mr Asker
  • 2,300
  • 11
  • 31
  • 56
  • can you point out the line of error. – keshav kowshik Mar 30 '15 at 13:42
  • There is no error in eclipse the crashing is just occuring if I try to turn the S4 device. – Mr Asker Mar 30 '15 at 13:46
  • no error in log cat? when the application is run by means of AVD? – keshav kowshik Mar 30 '15 at 13:47
  • `GPSAPlanetActivity.onRestoreInstanceState(GPSAPlanetActivity.java:212)` – Blackbelt Mar 30 '15 at 13:47
  • I think you might be having different layouts file for different orientation but you will be using different 'id' for view inside it.Please post your xml code – Karthika PB Mar 30 '15 at 13:48
  • Please post which line of your `onRestoreInstanceState()` method is at line number 212. This is where the `NullPointerException` is occurring. – bwegs Mar 30 '15 at 13:55
  • @Kesh1234 I have already posted the error in the logcat file that is the error, I am getting when the app crashes. Karthika PB I added my xml file – Mr Asker Mar 30 '15 at 13:55
  • @bwegs this line "txtSelectedPlant.setText(plant.toString());" the last line in the class. – Mr Asker Mar 30 '15 at 13:56
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Budius Mar 30 '15 at 15:31
  • @MrAsker If my solution helped solve your problem could you mark it as the correct answer? Thanks. – bwegs Mar 30 '15 at 21:46

1 Answers1

0

Your problem is that plant is null when onRestoreInstanceState() is called because plant is initialized in your onActivityResult() method (not in your onCreate() method). Change your code to check to see if plant is null before trying to retrieve it and set the text of your EditText:

plant = (Plant) savedInstanceState.getSerializable(PLANT2);

if(plant != null)  // plant may have been null when it was saved in onSaveInstanceState
    txtSelectedPlant.setText(plant.toString());
bwegs
  • 3,769
  • 2
  • 30
  • 33
  • this is line 211. Should I change line 211"plant = (Plant) savedInstanceState.getSerializable(PLANT2);" to "Plant plant = (Plant) savedInstanceState.getSerializable(PLANT2);" what should I do with this line "txtSelectedPlant.setText(plant.toString())" – Mr Asker Mar 30 '15 at 14:11
  • Yes, my mistake, try changing line 211 to the line I posted in my answer. Leave line 212 as it is. – bwegs Mar 30 '15 at 14:13
  • @MrAsker Can you post the code of your `plant` class? – bwegs Mar 30 '15 at 14:23
  • @MrAsker disregard my last comment and see my updated answer. You're most likely changing the orientation while `plant` is `null`. Just check for this instead before trying to set your `EditText` with its contents. – bwegs Mar 30 '15 at 14:34
  • I added the if condition I am getting something back on "txtSelectedPlant" as before but if I change the orientation the value of "txtSelectedPlant" disappeares. There is no crashing because of the if condition. I added the plant class too. – Mr Asker Mar 30 '15 at 15:01
  • @MrAsker Ok if the problem you're having is losing the value inside of `txtSelectedPlant` then I'd suggest just saving and restoring that value directly in the `instanceState` with `outState.putString("PLANT_TEXT", txtSelectedPlant.getText().toString());` in `onSaveInstanceState()` and `txtSelectedPlant.setText(savedInstanceState.getString("PLANT_TEXT"));` in `onRestoreInstanceState()` – bwegs Mar 30 '15 at 15:10