notifyDataSetChanged()不会更新片段中onActivityResult中调用的视图

时间:2018-02-13 19:07:48

标签: android android-fragments android-recyclerview notifydatasetchanged

我使用 onActivityResult()在我的RecyclerView中插入数据,但是 notifyDataSetChanged()不会更新RecyclerView。我做了一些搜索,但我无法为我找到决定。

只有当我返回并重新打开应用程序时,才会显示新数据。

如何更新观点?

这是我的 RecyclerViewFragment 代码:

public class RecyclerViewFragment extends Fragment{

    View v;
    private RecyclerView recyclerView;
    private List<Deadline> deadlines;
    DeadlineAdapter deadlineAdapter;

    DbActivity db;
    Cursor fullData;
    LinearLayout empty;

    String summary, date, time;

    public RecyclerViewFragment() { // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        v = inflater.inflate(R.layout.fragment_recycler_view, container, false);
        recyclerView = v.findViewById(R.id.recycler_view);
        empty = v.findViewById(R.id.empty);

        db = new DbActivity(getContext());
        fullData = db.getAllData();
        if (fullData.getCount() > 0){
            if (fullData.moveToFirst()) {
                deadlines = new ArrayList<>();
                int i = 1;
                do {
                    String check = fullData.getString(4);
                    if (!check.startsWith("co")){
                        summary = fullData.getString(1);
                        date = fullData.getString(2);
                        time = fullData.getString(3);
                        String deadline = fullData.getString(4);
                        String labels = fullData.getString(5);
                        //String labels = "wtf";
                        deadlines.add(new Deadline(summary, date, time, deadline,
                                labels));
                        i++;
                    }
                } while (fullData.moveToNext());
            }
            empty.setVisibility(View.GONE);
        }
        else {
            deadlines = new ArrayList<>();
            recyclerView.setVisibility(View.GONE);
            empty.setVisibility(View.VISIBLE);
        }
        deadlineAdapter = new DeadlineAdapter(getContext(), deadlines);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(deadlineAdapter);
        return v;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent data) {
        if (requestCode == Codes.INTENT_RESULT_CODE){
            if(resultCode == Codes.INTENT_RESULT_CODE) {
                DbActivity db = new DbActivity(getContext());
                Cursor newDeadline = db.getAllData();
                newDeadline.moveToLast();
                summary = newDeadline.getString(1);
                date = newDeadline.getString(2);
                time = newDeadline.getString(3);
                String deadline = newDeadline.getString(4);
                String labels = newDeadline.getString(5);
                deadlines.add(new Deadline(summary, date, time, deadline, labels));
                deadlineAdapter.notifyDataSetChanged();
                super.onActivityResult(requestCode, resultCode, data);
            }
        }
    }
}

AddTaskActivity类

public class AddTaskActivity extends AppCompatActivity {

int minute, hour, year, month, day, check;
String format, summary, date, time;
TextView setDate, setTime;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_task);

    Toolbar toolbar = findViewById(R.id.toolbar_add_task_activity);
    toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_back));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    final EditText editText = findViewById(R.id.summary);

    CharCountTextView charCountTextView = findViewById(R.id.tvTextCounter);
    charCountTextView.setEditText(editText);
    charCountTextView.setCharCountChangedListener(new CharCountTextView.CharCountChangedListener() {
        @Override
        public void onCountChanged(int countRemaining, boolean hasExceededLimit) {
            //stop?
        }
    });

    check = 0;
    setDate = findViewById(R.id.setDate);

    final Calendar currentDate = Calendar.getInstance();
    year = currentDate.get(Calendar.YEAR);
    month = currentDate.get(Calendar.MONTH) + 1;
    day = currentDate.get(Calendar.DAY_OF_MONTH);
    setDate.setText(day + "/" + month + "/" + year);
    month -= 1;
    currentDate.set(Calendar.DAY_OF_MONTH, day);

    setDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerDialog datePickerDialog = new DatePickerDialog(AddTaskActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    monthOfYear += 1;
                    setDate.setText(dayOfMonth + "/" + monthOfYear + "/" + year);
                }
            }, year, month, day);
            datePickerDialog.getDatePicker().setMinDate(currentDate.getTimeInMillis() - 1000);
            datePickerDialog.show();
        }
    });


    setTime = findViewById(R.id.setTime);

    Calendar currentTime = Calendar.getInstance();
    hour = currentTime.get(Calendar.HOUR_OF_DAY);
    minute = currentTime.get(Calendar.MINUTE);
    hour = selectedTimeFormat(hour);
    setTime.setText(hour + " : " + minute + " " + format);

    setTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TimePickerDialog timePickerDialog = new TimePickerDialog(AddTaskActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    hourOfDay = selectedTimeFormat(hourOfDay);
                    setTime.setText(hourOfDay + " : " + minute + " " + format);
                }
            }, hour, minute, false);
            timePickerDialog.show();
        }
    });
}

public int selectedTimeFormat(int hour){
    if (hour == 0){
        format = "AM";
    } else if (hour >= 12){
        hour -= 12;
        format = "PM";
    } else {
        format = "AM";
    }
    return hour;
}

public int codeToReturn(){
    EditText editTextSummary = findViewById(R.id.summary);
    summary = editTextSummary.getText().toString();

    TextView textViewDate = findViewById(R.id.setDate);
    date = textViewDate.getText().toString();

    TextView textViewTime = findViewById(R.id.setTime);
    time = textViewTime.getText().toString();

    boolean check = isDateCorrect(date, time);
    if (!check){
        return 3;
    }
    if (TextUtils.isEmpty(summary.trim())) {
        return 2;
    } else return 1;
}

public boolean isDateCorrect (String date, String time){
    String format = date + " " + time;
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh : mm a");
    Date cal1 = new Date();
    Date cal2 = null;
    try {
        cal2 = df.parse(format);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long diff = cal2.getTime() - cal1.getTime();
    return (diff > 0);
}

public String getDeadline (String date, String time){
    String format = date + " " + time;
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh : mm a");
    Date cal1 = new Date();
    Date cal2 = null;
    try {
        cal2 = df.parse(format);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long diff = cal2.getTime() - cal1.getTime();

    long diffSeconds = diff/(1000);

    long diffMinutes = diff / (60 * 1000);

    long diffHours = diff / (60 * 60 * 1000);

    long diffDays = diff / (24 * 60 * 60 * 1000);

    if (diffDays>1 && diffHours > 24){
        return String.valueOf(diffDays) + " days " + String.valueOf(diffHours - (diffDays*24)) + " hrs";
    } else if (diffDays==1 && diffHours > 24) {
        return String.valueOf(diffDays) + " day " + String.valueOf(diffHours - (diffDays*24)) + " hrs";
    }else if (diffHours>=1){
        return String.valueOf(diffHours) + " h";
    } else if (diffSeconds > 0)
        return String.valueOf(diffSeconds) + " s";
    else return String.valueOf(diffMinutes) + " m";
}

public String getTags(List<String> tags){
    String parsedTags = String.valueOf(tags).replace("[", "").replace("]", "");
    return parsedTags;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_add_task, menu);
    return true;
}

@Override
public void onBackPressed() {
    Intent intent = new Intent();
    super.setResult(Codes.INTENT_EMPTY_CODE, intent);
    super.onBackPressed();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()){
        case android.R.id.home:
            finish();
            return true;

        case R.id.doneTask:
            TagsEditText tagsEditText = findViewById(R.id.labels);
            List<String> tags = tagsEditText.getTags();

            Codes.INTENT_RESULT_CODE = codeToReturn();
            if (Codes.INTENT_RESULT_CODE == 1){
                String deadline = getDeadline(date, time);
                String tagstostring = getTags(tags);
                DbActivity db = new DbActivity(this);
                boolean isInserted = db.insertData(summary, date, time, deadline, tagstostring, "list");
                if (isInserted)
                    //
                     ;
                super.setResult(Codes.INTENT_RESULT_CODE);
                finish();
            } else if (Codes.INTENT_RESULT_CODE == 2) {
                Toast.makeText(this, "You did not enter a summary", Toast.LENGTH_SHORT).show();
            } else if (Codes.INTENT_RESULT_CODE == 3) {
                Toast.makeText(this, "Invalid date", Toast.LENGTH_SHORT).show();
            }
    }
    return super.onOptionsItemSelected(item);
}

}

希望得到任何帮助。

1 个答案:

答案 0 :(得分:0)

这里可能错了,但如果您在数据库中没有数据运行.then(res => res.json()) ,那么您正在设置

onCreate()

但你永远不会打电话

recyclerView.setVisibility(View.GONE);
添加项目后,在recyclerView.setVisibility(View.VISIBLE);

,因此在重新启动应用程序之前,更新将不可见,并且在调用onActivityResult()时数据库中有一个项目。