片段可以保留收集的cardviews数据的状态

时间:2016-05-05 17:13:18

标签: android android-fragments android-recyclerview

在我更改Android应用程序的设计之前,我想知道是否可以保留片段的状态,包括重新创建时收集的所有数据。在我的片段中,我有一个异步任务,用于收集json的正确数据,并将它们发布到不同的卡片视图中。这是我的代码:

LatestEventsFragment.java

public class LatestEventsFragment extends Fragment {

RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<Event> arrayList = new ArrayList();
ProgressDialog progressDialog;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setRetainInstance(true);
    View view = inflater.inflate(R.layout.events_list, container, false);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView = (RecyclerView)view.findViewById(R.id.events_recycler);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setHasFixedSize(true);
    adapter = new EventsRecyclerAdapter(arrayList);
    recyclerView.setAdapter(adapter);
    EventsAsyncTask eventsAsyncTask = new EventsAsyncTask();
    eventsAsyncTask.execute();
    return view;
}

class EventsAsyncTask extends AsyncTask<String, Event, String> {

    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("Loading");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(String s) {

        progressDialog.dismiss();
    }

    @Override
    protected void onProgressUpdate(Event... values) {

        arrayList.add(values[0]);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            ServerConfig serverConfig = new ServerConfig();
            URL url = new URL(serverConfig.getEvents_url());
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";

            while((line = bufferedReader.readLine()) != null){
                stringBuilder.append(line+"\n");
            }

            httpURLConnection.disconnect();
            String json_string = stringBuilder.toString().trim();
            JSONObject jsonObject = new JSONObject(json_string);
            JSONArray jsonArray = jsonObject.getJSONArray("server_response");

            int count = 0;

            while(count<jsonArray.length()){

                JSONObject JO = jsonArray.getJSONObject(count);
                count++;
                String jsonString = JO.get("image").toString();
                byte[] temp = Base64.decode(jsonString.getBytes(), Base64.DEFAULT);
                Bitmap decodedByte = BitmapFactory.decodeByteArray(temp, 0, temp.length);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
                dateFormat.setTimeZone(TimeZone.getTimeZone("UCT"));
                Date date = dateFormat.parse(JO.getString("date_posted"));
                Date server_date = dateFormat.parse(JO.getString("server_date"));
                Event event = new Event(JO.getString("name"), decodedByte, JO.getInt("views"), date, server_date);
                publishProgress(event);
                Thread.sleep(500);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
}

EventsRecyclerAdapter.java

public class EventsRecyclerAdapter extends RecyclerView.Adapter<EventsRecyclerAdapter.RecyclerViewHolder>{

ArrayList<Event> arrayList = new ArrayList<>();

public EventsRecyclerAdapter(ArrayList<Event> arrayList){
    this.arrayList = arrayList;
}


@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.latest_events_card, parent, false);
    return new RecyclerViewHolder(view);
}

@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
    Event event = arrayList.get(position);

    try{
        String views = String.valueOf(event.getViews())+" views";
        String date_string = getTime(event.getServer_date().getTime() - event.getDate_posted().getTime());

        holder.name.setText(event.getName());
        holder.image.setImageBitmap(event.getImage());
        holder.views.setText(views);
        holder.date_posted.setText(date_string);

    }catch (Exception e){
        e.printStackTrace();
    }
}

private String getTime(Long time_difference){
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = time_difference / daysInMilli;
    int daysInt = (int)elapsedDays;
    time_difference = time_difference % daysInMilli;

    long elapsedHours = time_difference / hoursInMilli;
    int hoursInt = (int)elapsedHours;
    time_difference = time_difference % hoursInMilli;

    long elapsedMinutes = time_difference / minutesInMilli;
    int minutesInt = (int)elapsedMinutes;
    //time_difference = time_difference % minutesInMilli;

    //long elapsedSeconds = time_difference / secondsInMilli;

    String date_string = String.valueOf(daysInt);

    if(daysInt > 0) {
        if (daysInt == 1) {
            date_string = "1 Day";
        } else if (daysInt > 1) {
            date_string = daysInt + " Days";
        }
    }else if(hoursInt > 0){
            if(hoursInt == 1){
                date_string = "1 Hour ";
                if(minutesInt > 1){
                    date_string = date_string + minutesInt + " Minutes";
                }
            } else if(hoursInt > 1){
                date_string = hoursInt + " Hours ";
                if(minutesInt > 1){
                    date_string = date_string + minutesInt + " Minutes";
                }
            }
    }else if(minutesInt > 0){
        if (minutesInt == 1) {
            date_string = "1 Minute";
        } else if (minutesInt > 1) {
            date_string = minutesInt + " Minutes";
        }
    }

    return date_string + " ago";
}

@Override
public int getItemCount() {
    return  arrayList.size();
}

public  static class RecyclerViewHolder extends RecyclerView.ViewHolder{

    protected TextView name, views, date_posted, start_date, end_date;
    protected ImageView image;


    public RecyclerViewHolder(View v){
        super(v);
        name = (TextView)v.findViewById(R.id.name);
        image = (ImageView)v.findViewById(R.id.thumbnail);
        views = (TextView)v.findViewById(R.id.views);
        date_posted = (TextView)v.findViewById(R.id.date_posted);
    }
}
}

最后 Events.java

public class Event {
private int id;
private String name;
private String description;
private String start_date;
private String end_date;
private double entrance_fee;
private Bitmap image;
private int views;
private Date date_posted;
private Date server_date;


public Event(String name, Bitmap image, int views, Date date_posted, Date server_date){
    //int id, String name, , String start_date, double entrance_fee, Bitmap image, int views
    this.setDescription(description);
    this.setEnd_date(end_date);
    this.setEntrance_fee(entrance_fee);
    this.setId(id);
    this.setImage(image);
    this.setName(name);
    this.setViews(views);
    this.setStart_date(start_date);
    this.setDate_posted(date_posted);
    this.setServer_date(server_date);
}

public Date getServer_date() {
    return server_date;
}

public void setServer_date(Date server_date) {
    this.server_date = server_date;
}

public Date getDate_posted() {
    return date_posted;
}

public void setDate_posted(Date date_posted) {
    this.date_posted = date_posted;
}

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getStart_date() {
    return start_date;
}

public void setStart_date(String start_date) {
    this.start_date = start_date;
}

public String getEnd_date() {
    return end_date;
}

public void setEnd_date(String end_date) {
    this.end_date = end_date;
}

public double getEntrance_fee() {
    return entrance_fee;
}

public void setEntrance_fee(double entrance_fee) {
    this.entrance_fee = entrance_fee;
}

public Bitmap getImage() {
    return image;
}

public void setImage(Bitmap image) {
    this.image = image;
}

public int getViews() {
    return views;
}

public void setViews(int views) {
    this.views = views;
}
}

1 个答案:

答案 0 :(得分:0)

您可以在片段中使用onSaveInstanceState来保存数据,然后查看savedInstanceState中的onCreateView变量,看看它是否有数据。如果是,只需检索数据即可重新创建视图。

内部碎片:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);

    if(mDataToSave != null) {
        savedInstanceState.putString("myData", mDataToSave);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

   if(savedInstanceState != null){
      String restoredData = (String)savedInstanceState.getString("myData");
      //do something with restoredData
   }
   return rootView;
}

请记住将put和get savedInstanceState.putString()更改为savedInstanceState.put<WhateverYourDataTypeIs>()

如果您要在主要活动中通过片段交易添加片段,请确保仅在主要活动savedInstanceState为空时才添加片段。这样,如果片段已被添加,您将无法替换片段。

内部活动(如果您有片段交易):

if(savedInstanceState == null) {
        Fragment newFragment = new MyFragment();
        //add main fragment to fragment frame
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().add(R.id.fragment_container, newFragment).commit();
    }