嗨,Guys是一天新的Android开发,只有我开始使用从服务器获取数据的凌空表格。现在我的问题是从服务器获取json响应并将其设置为recycleler adapter并将其保存在sharedpreferences中。我在oncreateview方法中写了一个volley调用我的疑问是在我再次访问活动之后再次切换它从服务器获取相同数据的片段并将其保存在共享偏好中,就像明智的数据每次访问该片段时加倍我让我发布代码:
这是我的片段代码:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
//Creating Views
Context context;
SharedPreferences.Editor editor;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
RequestQueue yog;
Task_DB taskobj = new Task_DB(getContext());
String yogan;
AppController app;
RequestQueue queue;
String Url;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Gson gsong = new Gson();
String jsons = sharedPreferences.getString(MY_PREFERENCE_KEY, "");
Type type = new TypeToken<ArrayList<Model_Task_List>>() {
}.getType();
model_task_lists = gsong.fromJson(jsons, type);
if (model_task_lists == null) {
model_task_lists = new ArrayList<Model_Task_List>();
}
//Showing a progress dialog
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
yogan = sharedPreferences.getString("user_id", null);
queue= AppController.getInstance(getActivity().getApplicationContext()).getRequestQueue();
Url = "http://xxx.xx.x.xxx/xxxx/xxx.svc/getlist/GetTask/" + yogan;
//Creating a json array request
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.GET, Url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("GetTaskResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
modelobj.setUserName(json_arrayJSONObject.getString("UserName"));
modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
model_task_lists.add(modelobj);
taskadapter = new Task_List_Adapter(model_task_lists, getContext());
recyclerView.setAdapter(taskadapter);
taskadapter.notifyDataSetChanged();
//
}
//Finally initializing our adapter
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
Log.e("yog", error.toString());
}
});
//Creating request queue
queue.start();
queue.add(jsonArrayRequest);
return view;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
queue.stop();
SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getContext());
editor = sharedpref.edit();
Gson gson = new Gson();
String god = gson.toJson(model_task_lists);
editor.putString(MY_PREFERENCE_KEY, god);
editor.commit();
super.onStop();
super.onStop();
}
}
这是我的Appcontroller类:
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class AppController extends android.app.Application {
private static AppController mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private AppController(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized AppController getInstance(Context context) {
if (mInstance == null) {
mInstance = new AppController(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
我希望你们能理解我遇到的问题我会很高兴有人帮助我提前谢谢!!
答案 0 :(得分:0)
使用布尔值在SharedPreferences中创建另一个键('First_Time')。在进行服务器调用之前检查此值。如果值为false,则进行服务器调用并将值设置为true。因此,当您下次重新输入片段时,该值将为true,并且不会进行服务器调用。
在你片段的onCreate方法 -
SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(getContext());
//Check if key exists
if(!sharedPrefs.contains("First_Time")){
editor = sharedpref.edit();
editor.putBoolean("First_Time", true);
}
现在在进行截击呼叫检查之前 -
if(sharedpref.getBoolean("First_Time")){ //Checking if Fragment launched first time
//Set this value to false so that it doesn't execute next time.
editor = sharedpref.edit();
editor.putBoolean("First_Time", false);
//Now make your volley call for the first and the last time here.
}