无法刷新RecyclerView

时间:2017-04-06 06:43:16

标签: android android-recyclerview recycler-adapter

我是Android编程的新手,我的问题是当我从MainActivity更新另一个Activity中的一条记录时,RecyclerView没有刷新。

我有一个带有RecyclerView的ManinActivity,一个用于插入和更新记录的activity_Detail,以及一个用于查看存储在数据库中的项目的activity_CardView。

这是我的代码:

MainActivity:

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;
rvNoteAdapter rvNoteAdapter;

private Toolbar mToolbar;
private FloatingActionButton fab;
private String rowID = null;

NoteDatabaseAdapter note_database;
FloatingActionButton btnAddNewRecord;

android.widget.LinearLayout parentLayout;
LinearLayout layoutDisplayPeople;

TextView tvNoRecordsFound;

ArrayList<create_note> notes;





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getAllWidgets();
    note_database = new NoteDatabaseAdapter(MainActivity.this,6);
    bindWidgetsWithEvent();
    //displayAllRecords();
    Recycler_do();

    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(mToolbar);

    //getSupportActionBar().setDisplayHomeAsUpEnabled(true);



}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        String note_type = data.getStringExtra(Constants.COLUMN_NOTE_TYPE);
        String note_text = data.getStringExtra(Constants.COLUMN_NOTE_TEXT);
        String note_id = data.getStringExtra(Constants.ID);

        create_note note = new create_note();
        note.setType(note_type);
        note.setText(note_text);


        if (requestCode == Constants.ADD_RECORD) {
            //sQLiteHelper.insertRecord(firstname, lastname);
            note_database.insert(note);

            //recyclerAdapterNote.addItem(0,note);
        } else if (requestCode == Constants.UPDATE_RECORD) {
            note.setId(note_id);
            //sQLiteHelper.updateRecord(firstname, lastname, rowID);
            note_database.update(note);
        }
        Recycler_do();
    }
}


private void getAllWidgets() {
    btnAddNewRecord = (FloatingActionButton) findViewById(R.id.fab);

    parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
    layoutDisplayPeople = (LinearLayout) findViewById(R.id.layoutDisplayNote);

    tvNoRecordsFound = (TextView) findViewById(R.id.tvNoRecordsFound);
    recyclerView = (RecyclerView) findViewById(R.id.rvNotes);
}

public void Recycler_do ()
{
   notes = note_database.getAllRecords();
    LinearLayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
    recyclerView.setLayoutManager(layoutManager);

    rvNoteAdapter adapter=new rvNoteAdapter(MainActivity.this,contacts);
    recyclerView.setAdapter(adapter);
}

private void bindWidgetsWithEvent() {
    btnAddNewRecord.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onAddRecord();
        }
    });
}

private void onAddRecord() {
    Intent intent = new Intent(MainActivity.this, Detail.class);
    intent.putExtra(Constants.DML_TYPE, Constants.INSERT);
    startActivityForResult(intent, Constants.ADD_RECORD);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

activity_Detail:

public class Detail extends AppCompatActivity {

EditText note_type;
EditText note_text;
RecyclerView recyclerView;

NoteDatabaseAdapter noteDatabaseAdapter=new NoteDatabaseAdapter(Detail.this,6);

String id;
String request="";
TextView toolbarText;

ImageView btnDML;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_Detail);

    getAllWidgets();
    bindWidgetsWithEvent();
    checkForRequest();
}
private void checkForRequest() {
     request = getIntent().getExtras().get(Constants.DML_TYPE).toString();
    if (request.equals(Constants.UPDATE)) {
        toolbarText.setText("update");
        note_text.setText(getIntent().getExtras().get(Constants.COLUMN_NOTE_TEXT).toString());
        note_type.setText(getIntent().getExtras().get(Constants.COLUMN_NOTE_TYPE).toString());
        id=getIntent().getExtras().get(Constants.ID).toString();
    } else {
        toolbarText.setText("new note");
    }
}

private void bindWidgetsWithEvent() {
    btnDML.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onButtonClick();
        }
    });

    final ImageView back_btn = (ImageView) findViewById(R.id.back_btn);
    back_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(Detail.this,"back btn",Toast.LENGTH_LONG).show();
            finish(); //back to prev activity

        }
    });

}

private void getAllWidgets() {
    note_type = (EditText) findViewById(R.id.note_type_EB);
    note_text = (EditText) findViewById(R.id.note_text_EB);
    toolbarText=(TextView) findViewById(R.id.toolbar_text);

    btnDML = (ImageView) findViewById(R.id.save_btn);
    recyclerView=(RecyclerView) findViewById(R.id.rvNotes);


    setTitle(null);

    Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(topToolBar);
    //topToolBar.setLogo(R.mipmap.ic_launcher);
    // topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
}

private void onButtonClick() {
    if (note_type.getText().toString().equals("") || note_text.getText().toString().equals("")) {
        Toast.makeText(getApplicationContext(), "Add Both Fields", Toast.LENGTH_LONG).show();
    } else if (request.equals(Constants.INSERT))
    {
        Intent intent = new Intent();
        intent.putExtra(Constants.COLUMN_NOTE_TYPE, note_type.getText().toString());
        intent.putExtra(Constants.COLUMN_NOTE_TEXT, note_text.getText().toString());
        intent.putExtra(Constants.ID, id);
        setResult(RESULT_OK, intent);
        finish();
    }
    else if (request.equals(Constants.UPDATE))
    {
        create_note note = new create_note();
        note.setType(note_type.getText().toString());
        note.setText(note_text.getText().toString());
        note.setId(id);
     try {
         noteDatabaseAdapter.update(note);
         ArrayList<create_note> noteArrayList = noteDatabaseAdapter.getAllRecords();
         ArrayList<create_note> temp=noteDatabaseAdapter.getAllRecords();
         rvNoteAdapter rvNoteAdaptermodel=new rvNoteAdapter(Detail.this,temp);

         **//do not refresh RecyclerView
         rvNoteAdaptermodel.updateItems(noteArrayList);**


         }catch (Exception e)
          {
              Log.d("Database", "Exception:" + e.getMessage());
          }
        finish();
        //

    }
}

activity_CardView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:padding="5dp"
>

<android.support.v7.widget.CardView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/cv">

<RelativeLayout
    android:id="@+id/inflateParentView"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    >
    <ImageView
        android:contentDescription="@string/action_new"
        android:id="@+id/back_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:src="@mipmap/ic_save"
        />

    <TextView
        android:layout_toRightOf="@id/back_btn"
        android:id="@+id/note_type_inflate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_weight="1"
        android:text="Name"
        android:textSize="15sp"
        android:gravity="start"

        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        />
    <TextView
        android:layout_toRightOf="@id/back_btn"
        android:id="@+id/note_text_inflate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_weight="1"
        android:text="Name"
        android:textSize="15sp"
        android:gravity="start"

        android:textColor="@color/colorPrimary"
        android:layout_below="@+id/note_type_inflate" />
    <TextView
        android:layout_toRightOf="@id/back_btn"
        android:id="@+id/note_id_inflate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_weight="1"
        android:text="Name"
        android:textSize="15sp"
        android:gravity="start"

        android:textColor="@color/colorPrimary"
        android:layout_below="@+id/note_text_inflate" />
</RelativeLayout>

rvNoteAdapter.java(适用于RecyclerView的适配器)

public class rvNoteAdapter extends RecyclerView.Adapter<rvNoteAdapter.ViewHolder> {

private List<create_note> noteList= Collections.emptyList();
Context noteContext;
private create_note note;
private String rowID = null;



public static class ViewHolder extends RecyclerView.ViewHolder{

    public TextView noteText;
    public TextView noteType;
    public TextView noteId;
    private CardView cardView;

    public ViewHolder(View itemView){
        super(itemView);

        noteText=(TextView) itemView.findViewById(R.id.note_text_inflate);
        noteType=(TextView) itemView.findViewById(R.id.note_type_inflate);
        noteId=(TextView) itemView.findViewById(R.id.note_id_inflate);

        cardView = (CardView) itemView.findViewById(R.id.cv);
    }

    }


public rvNoteAdapter(Context context,List<create_note> Note_List){
    this.noteList=Note_List;
    this.noteContext=context;
}
private Context getNoteContext()
{
    return noteContext;
}

@Override
public rvNoteAdapter.ViewHolder onCreateViewHolder (ViewGroup parent,int viewType)
{
   // Context context=parent.getContext();
   // LayoutInflater inflater=LayoutInflater.from(context);

    //View NoteView=inflater.inflate(R.layout.activity_CardView,parent,false);

    //ViewHolder viewHolder=new ViewHolder(NoteView);
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_CardView, parent, false);
    ViewHolder memberViewHolder = new ViewHolder(view);

    return memberViewHolder;
}

@Override
public void onBindViewHolder(final rvNoteAdapter.ViewHolder viewHolder,int position)
{
    //viewHolder.noteText.setText(noteList.get(position).getText());
    create_note note=noteList.get(position);
    viewHolder.noteText.setText(note.getText());
    viewHolder.noteType.setText(note.getType());
    viewHolder.noteId.setText(note.getId());

    final int pos=position;

    viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            create_note note=(create_note)v.getTag();
            String note_text=viewHolder.noteText.getText().toString();
            String note_type=viewHolder.noteType.getText().toString();
            String note_id=viewHolder.noteId.getText().toString();


            Intent intent = new Intent(v.getContext(), Detail.class);
            intent.putExtra(Constants.COLUMN_NOTE_TYPE, note_type);
            intent.putExtra(Constants.COLUMN_NOTE_TEXT, note_text);
            intent.putExtra(Constants.ID, note_id);
            intent.putExtra(Constants.DML_TYPE, Constants.UPDATE);

            v.getContext().startActivity(intent);

           // mainActivity.onUpdateRecord(note_text,"jhkhkj",note_id);
            Toast.makeText(noteContext,"clicked"+pos,Toast.LENGTH_LONG).show();
        }
    });


}

//my problem with this code that not refreshed RecyclerView

public void updateItems(ArrayList<create_note> notes)
{
    noteList.clear();
    noteList.addAll(notes);
    notifyDataSetChanged();
}
public void addItem(int position, create_note note) {
    try {
        noteList.add(position, note);
        notifyItemInserted(position);
    }
    catch (Exception e) {

    }
}

public void removeItem(create_note note) {
    int position=noteList.indexOf(note);
    noteList.remove(position);
    notifyItemRemoved(position);
}

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

NoteDatabaseAdapter.java(数据库适配器):

public class NoteDatabaseAdapter extends SQLiteOpenHelper {
public static final String TABLE_NAME = "tbl_note";
public static final String ID = "ID";
public static final String COLUMN_NOTE_TYPE = "type";
public static final String COLUMN_NOTE_TEXT = "text";



private SQLiteDatabase database;

 public NoteDatabaseAdapter(Context context,int newVersion) {

     super(context,"noteDatabase.db",null,newVersion);
 }
 @Override
 public void onCreate(SQLiteDatabase db)
 {
     try {
         String sql = "create table "+ TABLE_NAME +  " ( id integer primary key autoincrement NOT NULL," + COLUMN_NOTE_TYPE + " NVARCHAR," + COLUMN_NOTE_TEXT + " NVARCHAR)";
         db.execSQL(sql);
     }catch (Exception e)
     {
         Log.d("Database", "Exception:" + e.getMessage());
     }

 }

 @Override
 public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
 {
     try{

             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
             onCreate(db);

     }catch (Exception e)
     {
         Log.d("Database", "Exception:" + e.getMessage());
     }


 }

public void insert(create_note note) {
    try {
        database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_NOTE_TYPE, note.getType());
        contentValues.put(COLUMN_NOTE_TEXT, note.getText());
        database.insert(TABLE_NAME, null, contentValues);
        database.close();
    } catch (Exception e) {
        Log.d("Database", "Exception:" + e.getMessage());
    }
}

public void update(create_note note) {
    try {
        database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_NOTE_TYPE, note.getType());
        contentValues.put(COLUMN_NOTE_TEXT, note.getText());

        database.update(TABLE_NAME,contentValues,"id="+note.getId(),null);
        database.close();
    } catch (Exception e) {
        Log.d("Database", "Exception:" + e.getMessage());
    }
}

public ArrayList<create_note> getAllRecords() {
    database = this.getReadableDatabase();
    Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);

    ArrayList<create_note> notes = new ArrayList<create_note>();
    create_note note_model;
    cursor.moveToLast();
    if (cursor.getCount() > 0) {
        for (int i = 0; i < cursor.getCount(); i++) {


            note_model = new create_note();
            note_model.setId( cursor.getString(0));
            note_model.setType(cursor.getString(1));
            note_model.setText(cursor.getString(2));

            notes.add(note_model);
            cursor.moveToPrevious();
        }
    }
    cursor.close();
    database.close();

    return notes;
}

} create_note.java(object class)

public class create_note {
private String id;
private String type;
private String text;

public create_note(){}

public create_note(String type, String text) {
    this.type = type;
    this.text = text;
}

public create_note(String id, String type, String text) {
    this.id = id;
    this.type = type;
    this.text = text;
}

public String getId() {
    return id;
}

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

public String getType() {
    return type;
}

public void setText(String text) {
    this.text = text;
}

public String getText() {
    return text;
}

public void setType(String type) {
    this.type = type;
}
}

我的问题出现在UpdateItem方法的rvNoteAdapter.java中 adapter.invalidate不起作用,

有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

使用它来设置和刷新recyclelerview的一部分。

 if (null == rvNoteAdapter) {
                 rvNoteAdapter rvNoteAdaptermodel=new 

rvNoteAdapter(Detail.this,temp);
                     rvNoteAdaptermodel.updateItems(noteArrayList);
                        recyclerView.setAdapter(adapter);
                    } else {
                        rvNoteAdaptermodel.updateItems(noteArrayList);
                        rvNoteAdapter.notifyDataSetChanged();
                    }

你的updateItems方法应该是,

public void updateItems(ArrayList<create_note> notes)
{
    noteList.clear();
    noteList.addAll(notes);
}

答案 1 :(得分:0)

我使用此方法更新Recyclerview

MainActivity中的

  1. 将ArreyList设为静态
  2. 将rvNotAdapter设为静态
  3. 然后我在DetailActivity中使用这些变量。

    DetailActivity中的

    使用此代码:

    ArreyList<create_note> noteArreyList = noteDatabaseAdapter.getAllRecords();
    MainActivity.notes.clear();
    MainActivity.notes.addAll(noteArreyList);
    
    MainActivity.rvNoteAdapter.notifyDataSetChanged();
    

    我在数据库中提升数据后使用此代码:

    noteDatabaseAdapter.update(note);