将数据从数据库插入listView

时间:2014-09-09 20:39:27

标签: android listview

我想用一个名为"添加新用户"的按钮启动一个应用程序。和一个标题为"没有添加用户"在MainActivity中...然后在添加新用户之后,我想在ListView中添加该用户的名称,删除textView" No User Added"在MainActivity中...如何继续?请帮助我

2 个答案:

答案 0 :(得分:0)

创建一个包含“No User Added”文本的ArrayList,并将其设置为ListView数据。然后为“添加新用户”按钮设置setOnClickListener。执行创建新用户的过程,将新用户数据添加到ArrayList中,然后更新ListView数据。

例如:

ArrayList<String> userList = new ArrayList<String>();
userList.add("No User Added");

// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.the_row, userList);
ListView dataList = (ListView) findViewById(R.id.the_row);
dataList.setAdapter(adapter);

// Button onClickListener
AddButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Update ArrayList with new User
            adapter.notifyDataSetChanged();
        }

    });

答案 1 :(得分:0)

我已经完成了一次,查看我的代码 - (这里 DataHandler 是管理数据库的类文件) -

    public class HistoryPage extends Fragment
{
DataHandler handler;
int i,num;
String nm1,nm2,result;
private ListView mainListView ;  
private ArrayAdapter<String> listAdapter ;
View v;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
{
    v=inflater.inflate(R.layout.page, container,false);
    ActionBar bar=((ActionBarActivity)getActivity()).getSupportActionBar();
    bar.setTitle("History");
    bar.show();
    setHasOptionsMenu(true);
    mainListView = (ListView)v.findViewById( R.id.mainListView );
    handler=new DataHandler(getActivity().getBaseContext());
    handler.open();
    Cursor c=handler.returnData();
    c.moveToFirst();
    num=c.getCount();
    String[] Results = new String[num];
    for(i=0 ; i<num ; i++)
    {
        nm1=c.getString(0).toString();
        nm2=c.getString(1).toString();
        result=c.getString(2).toString();
        Results[i]=nm1+" & "+nm2+" - "+result;
        c.moveToNext();
    }
    handler.close();
    ArrayList<String> hstry = new ArrayList<String>();
    hstry.addAll(Arrays.asList(Results));
    listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.textv,hstry);
    mainListView.setAdapter( listAdapter );
    return v;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) 
{
    super.onCreateOptionsMenu(menu,inflater);
    inflater.inflate(R.menu.clear, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    switch(item.getItemId())
    {
        case R.id.cc:handler=new DataHandler(getActivity().getBaseContext());
                     handler.open();
                     handler.removeall();
                     listAdapter.clear();
                     break;
        case R.id.Back_d:getFragmentManager().popBackStack();
    }
    return false;
}

}