2016-08-24 48 views
0

我試圖在onSaveinstanceState中保存對象(saveMOvie)以便在調試代碼時使用帶有主要和詳細片段的平板電腦的屏幕上進行還原,它們彼此相鄰,對象(saveMOvie)的值是null但是當使用屏幕上只有一個片段的手機時,object(saveMOvie)的值不等於null,誰能告訴我爲什麼?null onSaveInstanceState方法中的對象

MainActivityFragment

 public class MainActivityFragment extends Fragment { 
Movie moviesStore[]; 
GridView gridView; 
String[] moviesImages; 
View rootView; 
ImageAdapter imgadpt; 
boolean flag; 
OnNewsItemSelectedListener onis; 

Movie saveMOvie = new Movie(); 


public interface OnNewsItemSelectedListener { 
    public void onMovieSelected(Movie movie); 
} 

public MainActivityFragment() { 
} 

public static boolean isTablet(Context context) { 
    return (context.getResources().getConfiguration().screenLayout 
      & Configuration.SCREENLAYOUT_SIZE_MASK) 
      >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
} 



public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setRetainInstance(true); 

} 

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    menu.clear();//3shan myy7slash duplicate 
    inflater.inflate(R.menu.menu_main, menu); 
} 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 

    // This makes sure that the container activity has implemented 
    // the callback interface. If not, it throws an exception 
    try { 
     onis = (OnNewsItemSelectedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnNewsItemSelectedListener"); 
    } 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    int id = item.getItemId(); 


    if (id == R.id.open_settings_activity) { 

     Intent intent = new Intent(getActivity(), SettingsActivity.class); 
     startActivity(intent); 
    //refresh used when there is no connection 
    } else if (id == R.id.Refresh_activity) { 
     onStart(); 
    } 

    return super.onOptionsItemSelected(item); 
} 

public void updateMovies() { 


    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
    String mode = prefs.getString(getString(R.string.key), 
      getString(R.string.default_value)); 

    if (mode.equals("popular") || mode.equals("top_rated")) { 
     new FetchMovies().execute(mode); 
    } else { 
     if (flag) { 
      android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager(); 
      android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
      FavouriteActivityFragment fav = new FavouriteActivityFragment(); 
      fragmentTransaction.replace(R.id.frag_main, fav); 
      // fragmentTransaction.addToBackStack(null); 
      fragmentTransaction.commit(); 
     } else { 
      Intent intent = new Intent(getActivity(), FavouriteActivity.class); 
      startActivity(intent); 
     } 
    } 

} 

@Override 
public void onStart() { 
    super.onStart(); 
    transaction.commit(); 
    flag = isTablet(getActivity()); 
    ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo nf = cn.getActiveNetworkInfo(); 
    if (nf == null && nf.isConnected() != true) { 
     Snackbar snackbar = Snackbar 
       .make(rootView, "Network Not Available", Snackbar.LENGTH_LONG) 
       .setAction("RECONNECT", new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 
         onStart(); 
        } 
       }); 

     snackbar.show(); 
    } 
    updateMovies(); 
} 
@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putParcelable("movie",saveMOvie); 

} 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    if (savedInstanceState != null) { 



     onis.onMovieSelected(saveMOvie); 
    } 
    setHasOptionsMenu(true); 
    rootView = inflater.inflate(R.layout.fragment_main, container, false); 

    gridView = (GridView) rootView.findViewById(R.id.gridView); 


    return rootView; 
} 

public class FetchMovies extends AsyncTask<String, Void, Movie[]> { 
    private final String Log_Tag = FetchMovies.class.getSimpleName(); 

    private Movie[] getMovieDataFromJson(String moviesJasonStr) 
      throws JSONException 

    { 


     final String lists = "results"; 
     final String decription = "overview"; 
     final String originalTitle = "original_title"; 
     final String moviePoster = "poster_path"; 
     final String userRating = "vote_average"; 
     final String releaseDate = "release_date"; 
     final String id = "id"; 
     JSONObject moviesJason = new JSONObject(moviesJasonStr); 
     JSONArray moviesArray = moviesJason.getJSONArray(lists); 


     // String[] resultStrs = new String[moviesArray.length()]; 
     moviesStore = new Movie[moviesArray.length()]; 
     for (int i = 0; i < moviesArray.length(); i++) { 
      JSONObject oneMovieInfo = moviesArray.getJSONObject(i); 

      moviesStore[i] = new Movie(); 

      moviesStore[i].setPlotSynopsis(oneMovieInfo.getString("overview")); 
      moviesStore[i].setUserRating(oneMovieInfo.getString("vote_average")); 
      moviesStore[i].setReleaseDate(oneMovieInfo.getString("release_date")); 
      moviesStore[i].setOriginalTitle(oneMovieInfo.getString("original_title")); 
      moviesStore[i].setMoviePoster(oneMovieInfo.getString("poster_path")); 
      moviesStore[i].setId(oneMovieInfo.getString("id")); 


     } 


     return moviesStore; 

    } 

    @Override 
    protected Movie[] doInBackground(String... params) { 

     HttpURLConnection urlConnection = null; 
     BufferedReader reader = null; 

     // Will contain the raw JSON response as a string. 
     String moviesJasonStr = null; 
     StringBuilder baseUrl = new StringBuilder("https://api.themoviedb.org/3/movie/"); 
     baseUrl.append(params[0]); 
     baseUrl.append("?api_key="); 
     baseUrl.append(BuildConfig.MOVIE_DP_API_KEY); 

     try { 

      // URL url = new URL("https://api.themoviedb.org/3/movie/popular?api_key=d51b32efc0520227b7c1c67e0f6417f6"); 
      URL url = new URL(baseUrl.toString()); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.connect(); 


      InputStream inputStream = urlConnection.getInputStream(); 
      StringBuffer buffer = new StringBuffer(); 
      if (inputStream == null) { 

       return null; 
      } 
      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 
      while ((line = reader.readLine()) != null) { 

       buffer.append(line + "\n"); 
      } 

      if (buffer.length() == 0) { 

       return null; 
      } 
      moviesJasonStr = buffer.toString(); 
      Log.v(Log_Tag, "movies Jason String :" + moviesJasonStr); 
     } catch (IOException e) { 
      Log.e(Log_Tag, "Error ", e); 
      // Toast.makeText(getActivity(),"there is no internet connection",Toast.LENGTH_LONG).show(); 

      return null; 
     } finally { 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (final IOException e) { 
        Log.e(Log_Tag, "Error closing stream", e); 
       } 
      } 
     } 
     try { 
      return getMovieDataFromJson(moviesJasonStr); 
     } catch (JSONException e) { 
      Log.e(Log_Tag, e.getMessage(), e); 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Movie[] result) { 
     if (result != null) { 

      moviesImages = new String[result.length]; 

      for (int i = 0; i < result.length; i++) { 

       StringBuilder baseUrl = new StringBuilder(); 
       baseUrl.append("http://image.tmdb.org/t/p/w185/"); 
       baseUrl.append(result[i].getMoviePoster()); 

       moviesImages[i] = baseUrl.toString(); 
      } 

      imgadpt = new ImageAdapter(getActivity(), moviesImages); 
      gridView.setAdapter(imgadpt); 
      // if(flag){ 
      // onis.onMovieSelected(moviesStore[0]);} 
      gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { 
        String posterUrl = (String) imgadpt.getItem(position); 
        saveMOvie = moviesStore[position]; 
        if (flag) { 
         onis.onMovieSelected(moviesStore[position]); 

        } else { 


         Intent intent = new Intent(getActivity(), DetailActivity.class); 



         intent.putExtra("movie", moviesStore[position]); 


         startActivity(intent); 
        } 


       } 
      }); 
     } else { 
      Toast.makeText(getActivity(), "Cannot Fetch Data from api check your internet Connection", Toast.LENGTH_LONG).show(); 

     } 


    } 


} 

}

+0

saveMOvie的值爲null在哪裏? – Ramit

+0

inSaveInstanceState方法saveMOvie僅在具有兩個片段的平板電腦中彼此爲空 – Abanoub

+0

需要onMovieSelected的代碼以及爲什麼setRetainInstance爲true – Ramit

回答

0

onCreate(savedInstanceState)被調用時,檢查savedInstanceState是否爲空,如果沒有,那麼從它getExtras(因爲它是一個Bundle)。

if (savedInstanceState != null) 
savedInstanceState.getParcelable(key) 

然後做任何你想要的對象。

相關問題