从sqlite将数据显示到recycleler视图而不重新启动应用程序

时间:2016-09-23 11:38:45

标签: android sqlite android-fragments android-recyclerview

我有一个包含RecyclerViewFragmentDialog的应用程序,我从用户获取数据到sqlite并且一切正常, 但问题是,当我点击添加到Dialog时,我必须重新启动应用程序以显示数据,如何在不重启的情况下显示数据?

这是我的DialogFragment

public class addAction extends DialogFragment implements View.OnClickListener {
EditText addTitle, addDesc;
Button add, clear,close;
private DatabaseHelpher db;
String Title,Des;
public addAction() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.addaction, container, false);
    addTitle = (EditText) rootView.findViewById(R.id.todotitle);
    addDesc = (EditText) rootView.findViewById(R.id.tododescription);
    add = (Button) rootView.findViewById(R.id.addbutton);
    add.setOnClickListener(this);
    close = (Button) rootView.findViewById(R.id.Close);
    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
        }});
    clear = (Button) rootView.findViewById(R.id.clear);
    clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addTitle.setText("");
            addDesc.setText("");}});
    return rootView;}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getDialog().setTitle("Add Action");
    db = new DatabaseHelpher(getContext());
}
private void insert() {
    Title = addTitle.getText().toString();
    Des= addDesc.getText().toString();
    db.insertIntoDB(Title, Des);}
@Override
public void onClick(View v) {
    if (addTitle.getText().toString().trim().equals("")) {
        addTitle.setError(" Title is required!");
    } else if (addDesc.getText().toString().trim().equals("")) {
        addDesc.setError(" Postion is required!");
    }
    Toast.makeText(getContext(),"your data is saved", Toast.LENGTH_SHORT).show();
    insert();
}}

MainActivity

public class MainActivity extends AppCompatActivity {
List<ToDoModule> dbList;
RecyclerView mRecyclerView;
DatabaseHelpher helpher;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().hide();
    helpher = new DatabaseHelpher(this);
    dbList= new ArrayList<ToDoModule>();
    dbList = helpher.getDataFromDB();



    mRecyclerView = (RecyclerView)findViewById(R.id.AppRecyclerView);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new RecyclerAdapter(this,dbList);
    this.dbList =helpher.getDataFromDB();
    mAdapter.notifyDataSetChanged();
    mRecyclerView.setAdapter(mAdapter);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setImageResource(R.drawable.ic_action_name);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentManager fm = getSupportFragmentManager();
            addAction add = new addAction();
            add.show(fm,"fragment_edit_name");
        }});}
@Override
protected void onResume() {
    super.onResume();
}
}
来自getdata()

SQlHelper方法

  public List<ToDoModule> getDataFromDB(){
    List<ToDoModule> modelList = new ArrayList<ToDoModule>();
    String query = "select * from "+ TODO_TABLE;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query,null);
    if (cursor.moveToFirst()){
        do {
            ToDoModule model = new ToDoModule();
            model.setActionTitle(cursor.getString(1));
            model.setActionDesc(cursor.getString(2));
            modelList.add(model);
        }while (cursor.moveToNext());
    }
    return modelList;
}

}

RecyclerViewAdapter

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

static List<ToDoModule> dbList;
static Context context;
RecyclerAdapter(Context context, List<ToDoModule> dbList ){
    this.dbList = new ArrayList<ToDoModule>();
    this.context = context;
    this.dbList = dbList;
}
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.actionitems, null);
    ViewHolder viewHolder = new ViewHolder(itemLayoutView);
    return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
    holder.Title.setText(dbList.get(position).getActionTitle());
    holder.Desc.setText(dbList.get(position).getActionDesc());
}
@Override
public int getItemCount() {
    return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder  {
    public TextView Title,Desc;
    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        Title = (TextView) itemLayoutView.findViewById(R.id.todotitle);
        Desc = (TextView)itemLayoutView.findViewById(R.id.des);
    }
}
 }

3 个答案:

答案 0 :(得分:0)

您可以在数据发生变化时向适配器实施通知。

理想情况下,适配器RecyclerAdapter将使用以下方法进行暗示。

1)notifyItemRemoved
2)notifyItemRangeChanged
3)notifyItemRangeInserted

还有其他可用的方法,可以在this API reference link

中找到

现在为了更新数据,请使用recyclerAdapterObject.notifyDataSetChanged();

通知适配器

部分下进行this reference link更详细的实施

答案 1 :(得分:0)

首先不要在RecyclerAdapter(Context context, List<ToDoModule> dbList ){ this.dbList = new ArrayList<ToDoModule>(); this.context = context; this.dbList = dbList; }

中执行此操作
Context

你不应该保存this.dbList = new ArrayList<ToDoModule>(),除非你真的明白为什么需要这个。在这里你根本不使用它。此外,this.dbList = dbList也不是必需的,因为无论如何都要addAction

您可以为public class addAction extends DialogFragment implements View.OnClickListener { public interface OnToDoAddedListener{ void onTodoAdded(); } private OnToDoAddedListener mToDoAddedListener; ... public setOnTodoAddedListener(OnToDoAddedListner listener){ this.mToDoAddedListener = listener; } } 对话框片段添加界面,例如

mToDoAddedListener.onTodoAdded()

然后使用insert()方法调用MainActivity.onCreate

然后,您应该将addAction方法中的监听器添加到onTodoAdded()对象,并在this.dbList.clear(); this.dbList.addAll(helpher.getDataFromDB(); mAdapter.notifyDataSetChanged(); 实施中调用此代码:

"myWords" : {
  "words" : [
    null,
    "Tool box",
    "Ice Cream",
    "Lavender",
    "Speakers",
    "Pepsi",
    "Windows",
    "Linux",
  ]
}

答案 2 :(得分:0)

在你的代码中,我没有看到你更新列表的位置(只是带有添加动作的按钮)所以我将用一个通用的例子来解释。

您实例化RecyclerAdapter的地方:

final List<ObjectXPTO> list = new ArrayList<>();
list =helpher.getDataFromDB(); 
final RecyclerAdapter mAdapter = new RecyclerAdapter(this,list);

fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ObjectXPTO newObject = new ObjectXPTO(); // Just to exemplify, you need to get this object from you database 
            list.add(newObject);
            mAdapter.notifyDataSetChanged(); 
        }
    }); 

恢复,您需要在适配器上使用的列表中添加新对象,并通知适配器数据集已更改,因此适配器将更新

修改 如果我理解正确,您可以在片段或活动的某个位置添加数据,因此您需要传递给Activity(适配器所在的位置)数据更改的信息。

将此方法添加到MainActivity:

public static void updateList(List<ToDoModule> newList){
    dbList.clear();
    dbList.addAll(newList);
    mAdapter.notifyDataSetChanged();
} 

因此,在片段中,您可以传递新的List并更新MainActivity中的列表,或者您可以在此方法中执行新的查询。

这只是为了解释,您可能需要比较(在UI线程之外),如果项目不在列表中,并且只添加尚未包含的项目(以避免整个列表更新)。 / p>

聚苯乙烯。您需要将列表和适配器变量更改为静态。