我有两个片段LatestFragment
和LatestDetailsFragment
。LatestFragment显示一个列表视图,而LatestDetailsFragment显示从LatestFragment中单击的列表项的详细信息。现在我想保持LatestFragment的状态,以便从LatestDetailsFragment列表再次显示在onItemClick之前。但是当我尝试恢复时,我得到一个空指针异常。我怎么能实现呢?我实现了一个无限的listview,一次加载20个项目。我想恢复到当前的listview位置。
这是我的LatestFragment代码
public class LatestFragment extends Fragment implements OnItemClickListener,
OnScrollListener {
ProgressDialog progressDialog;
ArrayList<CarItem> adverts;
TextView loadingmore;
// products JSONArray
JSONArray products = null;
// url to get all products list
private static final String url_latest ="http:...";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COUNT = "count";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_HEADING = "tag";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_PRICE = "price";
private static final String TAG_ID = "item_id";
private static final String TAG_LOCATION = "location";
private static final String TAG_PHOTO = "photo";
private static final String TAG_MODEL = "model";
private static final String TAG_MAKE = "make";
private static final String TAG_REGISTRATION = "registration";
private static final String TAG_CATEGORY = "category";
private static final String TAG_TRANSMISSION = "transmission";
private static final String TAG_FUEL = "fuel";
private static final String TAG_ENGINE = "engine_size";
// Bundle key names
private static final String KEY_DESCRIPTION = "advert_description";
private static final String KEY_ID = "advert_id";
private static final String KEY_RATE = "advert_rate";
private static final String KEY_LOCATION = "advert_location";
private static final String KEY_FUEL = "advert_fuel";
private static final String KEY_ENGINE = "advert_engine";
private static final String KEY_MODEL = "advert_model";
private static final String KEY_MAKE = "advert_make";
private static final String KEY_TRANSMISSION = "advert_transmission";
private static final String KEY_REGISTRATION = "advert_registration";
private static final String KEY_CATEGORY = "advert_category";
ListView latestlist;
CarItem advert;
boolean loadingMore;
int currentPage;
int itemCount;
public LatestFragment() {
advert = new CarItem();
loadingMore = false;
currentPage = 0;
itemCount = 0;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View rootView = inflater.inflate(R.layout.fragment_latest, container,
false);
latestlist = (ListView) rootView.findViewById(R.id.listView_latest);
loadingmore = (TextView) rootView
.findViewById(R.id.latest_textView_more);
new GetLatest().execute();
latestlist.setOnItemClickListener(this);
latestlist.setOnScrollListener(this);
return rootView;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Fragment detailsFragment = new LatestDetailsFragment();
CarsListAdapter adapter = (CarsListAdapter) latestlist.getAdapter();
advert = (CarItem) parent.getItemAtPosition(position);
int advert_id = advert.getId();
String advert_description = advert.getDescription();
String advert_location = advert.getLocation();
String advert_price = advert.getPrice();
String advert_engine = advert.getEngineSize();
String advert_model = advert.getModel();
String advert_make = advert.getMake();
String advert_transmission = advert.getTransmission();
String advert_fuel = advert.getFuel();
String advert_registration = advert.getRegistration();
String advert_category = advert.getCategeory();
Bundle bundle = new Bundle();
bundle.putString(KEY_DESCRIPTION, advert_description);
bundle.putInt(KEY_ID, advert_id);
bundle.putString(KEY_RATE, advert_price);
bundle.putString(KEY_LOCATION, advert_location);
bundle.putString(KEY_ENGINE, advert_engine);
bundle.putString(KEY_MODEL, advert_model);
bundle.putString(KEY_MAKE, advert_make);
bundle.putString(KEY_TRANSMISSION, advert_transmission);
bundle.putString(KEY_FUEL, advert_fuel);
bundle.putString(KEY_REGISTRATION, advert_registration);
bundle.putString(KEY_CATEGORY, advert_category);
detailsFragment.setArguments(bundle);
FragmentManager fragmentManager = getActivity()
.getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, detailsFragment)
.addToBackStack("latest").commit();
}
protected class GetLatest extends
AsyncTask<LatestFragment, Void, LatestFragment> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.show();
}
@Override
protected LatestFragment doInBackground(LatestFragment... params) {
adverts = getLatest();
return null;
}
@Override
protected void onPostExecute(LatestFragment params) {
super.onPostExecute(params);
if (adverts.size() != 0) {
latestlist.setAdapter(new CarsListAdapter(getActivity(),
adverts));
currentPage = currentPage + 1;
}
progressDialog.dismiss();
}
}
public ArrayList<CarItem> getLatest() {
InputStream is = null;
String result = "";
ArrayList<CarItem> results = new ArrayList<CarItem>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("currentPage", String
.valueOf(currentPage)));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_latest);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in connection " + e.toString());
// results.setText("Error in connection");
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// Check your log cat for JSON reponse
Log.d("All Products: ", result);
try {
JSONObject json = new JSONObject(result);
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
itemCount = json.getInt(TAG_COUNT);
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_ID);
String location = c.getString(TAG_LOCATION);
String photo_url = c.getString(TAG_PHOTO);
String price = c.getString(TAG_PRICE);
String description = c.getString(TAG_DESCRIPTION);
String header = c.getString(TAG_HEADING);
String registration = c.getString(TAG_REGISTRATION);
String make = c.getString(TAG_MAKE);
String model = c.getString(TAG_MODEL);
String category = c.getString(TAG_CATEGORY);
String transmission = c.getString(TAG_TRANSMISSION);
String fuel = c.getString(TAG_FUEL);
String engine_size = c.getString(TAG_ENGINE);
// creating new CarItem object
CarItem car = new CarItem();
car.setHeader(header);
car.setDescription(description);
car.setId(id);
car.setLocation(location);
car.setPrice(price);
car.setPhoto(photo_url);
car.setRegistration(registration);
car.setMake(make);
car.setModel(model);
car.setCategory(category);
car.setTransmission(transmission);
car.setEngineSize(engine_size);
car.setFuel(fuel);
results.add(car);
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return results;
}
@Override
public void onResume() {
super.onResume();
// latestlist.setAdapter(new CarsListAdapter(getActivity(), adverts));
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom iten that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)
&& ((currentPage * 20) < itemCount)) {
loadingmore.setVisibility(View.VISIBLE);
loadingMore = true;
new LoadMore().execute();
}
}
private class LoadMore extends
AsyncTask<LatestFragment, Void, LatestFragment> {
CarsListAdapter adapter = (CarsListAdapter) latestlist.getAdapter();
ArrayList<CarItem> newadverts = new ArrayList<CarItem>();
@Override
protected LatestFragment doInBackground(LatestFragment... params) {
newadverts = getLatest();
return null;
}
protected void onPostExecute(LatestFragment param) {
super.onPostExecute(param);
if (newadverts.size() != 0) {
loadingmore.setVisibility(View.GONE);
adverts.addAll(newadverts);
adapter.notifyDataSetChanged();
}
loadingMore = false;
}
}
这是我的Logcat内容:
08-24 10:06:59.158: E/AndroidRuntime(1176): FATAL EXCEPTION: main
08-24 10:06:59.158: E/AndroidRuntime(1176): java.lang.NullPointerException
08-24 10:06:59.158: E/AndroidRuntime(1176): at com.koncious.safirisha.LatestFragment$LoadMore.onPostExecute(LatestFragment.java:321)
08-24 10:06:59.158: E/AndroidRuntime(1176): at com.koncious.safirisha.LatestFragment$LoadMore.onPostExecute(LatestFragment.java:1)
08-24 10:06:59.158: E/AndroidRuntime(1176): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-24 10:06:59.158: E/AndroidRuntime(1176): at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-24 10:06:59.158: E/AndroidRuntime(1176): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-24 10:06:59.158: E/AndroidRuntime(1176): at android.os.Handler.dispatchMessage(Handler.java:99)
08-24 10:06:59.158: E/AndroidRuntime(1176): at android.os.Looper.loop(Looper.java:137)
08-24 10:06:59.158: E/AndroidRuntime(1176): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-24 10:06:59.158: E/AndroidRuntime(1176): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 10:06:59.158: E/AndroidRuntime(1176): at java.lang.reflect.Method.invoke(Method.java:511)
08-24 10:06:59.158: E/AndroidRuntime(1176): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-24 10:06:59.158: E/AndroidRuntime(1176): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-24 10:06:59.158: E/AndroidRuntime(1176): at dalvik.system.NativeStart.main(Native Method)
任何人都请帮忙。
答案 0 :(得分:0)
要保存状态,您应该覆盖onSaveInstanceState:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
要恢复状态,您应该覆盖onRestoreInstanceState:
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
点击此链接了解更多信息: