In order to make this code work, I needed to remove this line from onCreate
:
this.setRetainInstance(true);
سؤال
I am trying to prevent loosing of webview state on rotation changes here is my fragment code :
public class ContentFragment extends Fragment {
private String mArticleId, imageUrl;
private WebView mContent;
private ImageView mBackground;
private LinearLayout mLayout;
private Bundle webViewBundle;
public static ContentFragment newInstance(String idcko) {
ContentFragment f = new ContentFragment();
Bundle args = new Bundle();
args.putString("idcko", idcko);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
mArticleId = getArguments().getString("idcko");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_content, null);
mContent = (WebView) root.findViewById(R.id.content_web);
if (webViewBundle == null) {
new FetchContent().executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR, "");
} else {
Log.e("else", "");
mContent.restoreState(webViewBundle);
}
return root;
}
@Override
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
mContent.saveState(webViewBundle);
}
private class FetchContent extends AsyncTask<String, String, String> {
private JSONParser jsonParser;
private String content;
@Override
protected String doInBackground(String... params) {
jsonParser = new JSONParser();
List<NameValuePair> parametre = new ArrayList<NameValuePair>();
parametre.add(new BasicNameValuePair("post_id", mArticleId));
JSONObject jObj = jsonParser
.getJSONFromUrlNonHtml(
"http://www.androidaci.net/api/get_post/",
parametre, "GET");
try {
JSONObject post = jObj.getJSONObject("post");
content = post.getString("content");
} catch (JSONException e) {
e.printStackTrace();
}
return content;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mContent.loadDataWithBaseURL("", removePlayStore(result),
"text/html", "UTF-8", "");
}
}
I load the content from website in HTML form, I modify it a bit with JSOUP and I show it, it works on first try, but upon rotation changes I loose the state. How can I save this ?
المحلول
In order to make this code work, I needed to remove this line from onCreate
:
this.setRetainInstance(true);