显示数据从SQLite数据库到ListView控件中的Andr​​oid [英] Display data from SQLite database into ListView in Android

查看:240
本文介绍了显示数据从SQLite数据库到ListView控件中的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管这个问题已经被问了很多次就在这里,我只是找不到正确的答案,以适应我的code。我意识到这可能是一些小的,但我似乎无法找到的问题,因为我只是真的很新的这个和迫切需要的答案尽快。

任何帮助将是非常美联社preciated,谢谢你。

下面是我的code getClientNames DatabaseHelper 类:

 公开光标getSitesByClientname(字符串ID){
    字串[] args = {ID};

光标myCursor = db.rawQuery(SELECT client_sitename FROM+ CLIENT_SITES_TABLE +WHERE CLIENT_ID =?,参数);
        字符串结果=;
        / *诠释计数= myCursor.getCount();
        的String []的结果=新的String [计数+ 1];
        INT I = 0; * /

         如果(myCursor!= NULL){
                如果(myCursor.getCount()大于0)
                {
                    为(myCursor.moveToFirst();!myCursor.isAfterLast(); myCursor.moveToNext())
                    {
                        结果结果= + myCursor.getString(myCursor.getColumnIndex(client_sitename));
                    }
                }
            }
            返回结果;
}
 

一个问题是,我回来了字符串'到'光标',但我不知道什么是解决这个问题的最好办法,因为我认为我应该返回一个指针。

下面是在 ClientSites 在这里我想显示的数据类:

 公共类ClientSites延伸活动{

//公共最后静态字符串ID_EXTRA =com.example.loginfromlocal._ID;

        私人DBUserAdapter dbHelper = NULL;
    私人光标ourCursor = NULL;
    专用适配器适配器= NULL;


    @燮pressWarnings(德precation)
    @燮pressLint(NewApi)
    公共无效的onCreate(包savedInstanceState){
        尝试
        {
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.client_sites);

            意图I = getIntent();
            字符串UID =将String.valueOf(i.getIntExtra(用户ID,0));

            ListView控件myListView =(ListView控件)findViewById(R.id.myListView);

            dbHelper =新DBUserAdapter(本);

            //dbHelper.createDatabase();

            dbHelper.openDataBase();

            ourCursor = dbHelper.getSitesByClientname(UID);
            Log.e(警报,uID.toString());

            startManagingCursor(ourCursor);
            Log.e(ERROR,开始后管理光标:);

            // @燮pressWarnings(德precation)
            // SimpleCursorAdapter适配器=新SimpleCursorAdapter(getBaseContext(),R.id.myListView,NULL,NULL,NULL);
            CursorAdapter的适配器=新SimpleCursorAdapter(这一点,R.id.myListView,NULL,NULL,NULL,0);
            适配器=新的适配器(ourCursor);

            //Toast.makeText(ClientSites.this,Bo​​oo !!!,Toast.LENGTH_LONG).show();

            myListView.setAdapter(适配器);

            myListView.setOnItemClickListener(onListClick);


        }
        赶上(例外五)
        {
            Log.e(ERROR,XXERROR在code:+ e.toString());
            e.printStackTrace();
        }

    }

    私人AdapterView.OnItemClickListener onListClick =新AdapterView.OnItemClickListener(){
        公共无效onItemClick(适配器视图<>父,
                                视图中查看,INT位置,
                                长ID)
        {
            意图I =新的意图(ClientSites.this,InspectionPoints.class);

            i.putExtra(ID_EXTRA,将String.valueOf(ID));
            startActivity(ⅰ);

        }
    };


    类适配器扩展的CursorAdapter {
        @燮pressWarnings(德precation)
        适配器(光标C){
          超(ClientSites.this,C);
        }

        // @覆盖
        公共无效bindView(查看行,上下文ctxt,
                           光标C){
            持有人440 =(持有人)row.getTag();
            holder.populateFrom(C,dbHelper);
        }
        @覆盖
        公共查看NewView的(语境ctxt,光标C,
                           ViewGroup中父){
          LayoutInflater充气= getLayoutInflater();
          查看排= inflater.inflate(R.layout.row,父母,假);
          持有人440 =新的持有人(行);
          row.setTag(保持器);
          返回(行);
        }
      }

    静态类持有人{
        私人TextView的名称= NULL;

        座(查看行){
            名称=(TextView中)row.findViewById(R.id.ingredientText);
        }

        无效populateFrom(光标C,DBUserAdapter R){
            name.setText(r.getName(C));
        }
    }
 

}

再次感谢所有帮助,这将是巨大的!

下面是code,我现在用的尝试,并在列表视图中显示数据。我从最初的尝试改变它几分,但还是不知道我做错了。真的AP preciate有这方面的帮助,干杯!

 公共无效的onCreate(包savedInstanceState){
        尝试
        {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.client_sites);

            意图I = getIntent();
            字符串UID =将String.valueOf(i.getIntExtra(用户ID,0));
            // INT的uid = i.getIntExtra(用户ID,0);

            // ListView控件myListView =(ListView控件)findViewById(R.id.myListView);

            dbHelper =新DBUserAdapter(本);

            dbHelper.createDatabase();

            dbHelper.openDataBase();

            的String []的结果= dbHelper.getSitesByClientname(UID);

            // setListAdapter(新ArrayAdapter<字符串>(ClientSites.this,R.id.myListView,结果));
            //适配器=新的ArrayAdapter<字符串>(ClientSites.this,R.id.myListView,结果);
            setListAdapter(新ArrayAdapter<字符串>(ClientSites.this,R.layout.client_sites,结果));

            // ListView控件myListView =(ListView控件)findViewById(R.id.myListView);
            ListView控件的ListView = getListView();
            listView.setTextFilterEnabled(真正的);

            // ourCursor = dbHelper.getSitesByClientname(UID);
            //Log.e("ALERT,uID.toString());

            // startManagingCursor(ourCursor);
            //Log.e("ERROR,开始后管理光标:);

            // @燮pressWarnings(德precation)
            // SimpleCursorAdapter适配器=新SimpleCursorAdapter(getBaseContext(),R.id.myListView,NULL,NULL,NULL); //看看这个早上!!!!!!!!!!!
            // CursorAdapter的适配器=新SimpleCursorAdapter(这一点,R.id.myListView,NULL,NULL,NULL,0);
            //适配器=新的适配器(ourCursor);

            //Toast.makeText(ClientSites.this,Bo​​oo !!!,Toast.LENGTH_LONG).show();

            //myListView.setAdapter(adapter);

            //myListView.setOnItemClickListener(onListClick);
 

解决方案

我从创建数据库的列表视图。这里是code我用我的应用程序

下面是数据库处理程序的一部分。它会返回一个类别列表我的列表视图。它可以返回一个字符串列表,如果这是你所需要的。

 公开名单<类别> getAllCategorys(){
        ArrayList的<类别>所属分类=新的ArrayList<类别>();
        //选择所有查询
        字符串selectQuery =SELECT * FROM+ TABLE_CATEGORY;
        SQLiteDatabase DB = this.getWritableDatabase();
        光标光标= db.rawQuery(selectQuery,NULL);
        //遍历所有行和添加到列表
        尝试{
            如果(cursor.moveToFirst()){
                做 {
                    类别类别=新类别();
                    category.setID(的Integer.parseInt(cursor.getString(0)));
                    category.setCategory(cursor.getString(1));
                    //添加类别列出
                    categoryList.add(类);
                }而(cursor.moveToNext());
            }
        }最后{
            cursor.close();
        }
        db.close();
        //返回分类列表
        返回所属分类;
 

下面是我如何填补的ListView通过调用数据库。

  INT大小= db.getCategoryCount();
名单<类别>所属分类= db.getAllCategorys();

category_data =新的String [尺寸-1];
INT I = 0;
对于(分类CN:所属分类)
{
    category_data [I] = cn.getCategory(); //获取类别的名称,并把它添加到阵列
    我++;
}

listAdapter =新的ArrayAdapter<字符串>(这一点,R.layout.categoryrow,category_data);
listViw.setAdapter(listAdapter);
 

编辑:这是什么,应该为你工作。

 公开名单<字符串> getSitesByClientname(字符串ID){
    字串[] args = {ID};
    ArrayList的<字符串>结果=新的ArrayList<字符串>();
    SQLiteDatabase DB = this.getWritableDatabase();

    光标myCursor = db.rawQuery(SELECT client_sitename FROM+ CLIENT_SITES_TABLE +WHERE CLIENT_ID =?,参数);

    尝试{
       如果(myCursor.moveToFirst()){
           做{
              result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex(client_sitename));
           }而(myCursor.moveToNext());
        }
    }最后{
         myCursor.close();
    }
    db.close();
    返回结果;
}
 

使用像这样

 名单,其中,字符串> sites_data = dbHelper.getSitesByClientname(UID);

result_data =新的String [sites_data.size()];
INT I = 0;
对于(字符串S:sites_data)
{
    result_data [I] =秒; //获取类别的名称,并把它添加到阵列
    我++;
}

listAdapter =新的ArrayAdapter<字符串>(这一点,R.layout.client_sites,result_data);
listViw.setAdapter(listAdapter);
 

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this and badly need the answer asap.

Any help would be really appreciated, Thanks.

Here's my code getClientNames in DatabaseHelper class:

public Cursor getSitesByClientname(String id) {
    String[] args={id};

Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
        String results = "";
        /*int count = myCursor.getCount();
        String[] results = new String[count + 1];
        int i = 0;*/

         if (myCursor != null) {           
                if(myCursor.getCount() > 0)
                {   
                    for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
                    {
                        results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename")); 
                    }
                }
            }
            return results;
}

One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.

Here's the ClientSites class where I want to display the data:

public class ClientSites extends Activity {

//public final static String ID_EXTRA="com.example.loginfromlocal._ID";

        private DBUserAdapter dbHelper = null;
    private Cursor ourCursor = null;
    private Adapter adapter=null;


    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void onCreate(Bundle savedInstanceState) {
        try
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.client_sites);

            Intent i = getIntent();
            String uID = String.valueOf(i.getIntExtra("userID", 0));

            ListView myListView = (ListView)findViewById(R.id.myListView);

            dbHelper = new DBUserAdapter(this);

            //dbHelper.createDatabase();

            dbHelper.openDataBase();

            ourCursor = dbHelper.getSitesByClientname(uID);
            Log.e("ALERT", uID.toString());

            startManagingCursor(ourCursor);
            Log.e("ERROR", "After start manage cursor: ");

            //@SuppressWarnings("deprecation") 
            //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
            CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
            adapter = new Adapter(ourCursor);

            //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();

            myListView.setAdapter(adapter);

            myListView.setOnItemClickListener(onListClick);


        }
        catch (Exception e)
        {
            Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
            e.printStackTrace();
        } 

    }

    private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                                View view, int position,
                                long id) 
        {
            Intent i=new Intent(ClientSites.this, InspectionPoints.class);

            i.putExtra(ID_EXTRA, String.valueOf(id));
            startActivity(i);

        }
    };


    class Adapter extends CursorAdapter {
        @SuppressWarnings("deprecation")
        Adapter(Cursor c) {
          super(ClientSites.this, c);
        }

        //@Override
        public void bindView(View row, Context ctxt,
                           Cursor c) {
            Holder holder=(Holder)row.getTag();
            holder.populateFrom(c, dbHelper);
        }
        @Override
        public View newView(Context ctxt, Cursor c,
                           ViewGroup parent) {
          LayoutInflater inflater=getLayoutInflater();
          View row = inflater.inflate(R.layout.row, parent, false);
          Holder holder=new Holder(row);
          row.setTag(holder);
          return(row);
        }
      }

    static class Holder {
        private TextView name=null;

        Holder(View row) {
            name=(TextView)row.findViewById(R.id.ingredientText);
        }

        void populateFrom(Cursor c, DBUserAdapter r) {
            name.setText(r.getName(c));
        }
    }

}

Thanks again, any help with this would be great!

Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong. Would really appreciate any help on this, Cheers!

public void onCreate(Bundle savedInstanceState) {
        try
        {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.client_sites);

            Intent i = getIntent();
            String uID = String.valueOf(i.getIntExtra("userID", 0));
            //int uID = i.getIntExtra("userID", 0);

            //ListView myListView = (ListView)findViewById(R.id.myListView);

            dbHelper = new DBUserAdapter(this);

            dbHelper.createDatabase();

            dbHelper.openDataBase();

            String[] results = dbHelper.getSitesByClientname(uID);

            //setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
            //adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
            setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));

            //ListView myListView = (ListView)findViewById(R.id.myListView);
            ListView listView = getListView();
            listView.setTextFilterEnabled(true);

            //ourCursor = dbHelper.getSitesByClientname(uID);
            //Log.e("ALERT", uID.toString());

            //startManagingCursor(ourCursor);
            //Log.e("ERROR", "After start manage cursor: ");

            //@SuppressWarnings("deprecation") 
            //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!! 
            //CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
            //adapter = new Adapter(ourCursor);

            //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();

            //myListView.setAdapter(adapter);

            //myListView.setOnItemClickListener(onListClick);

解决方案

I Created a Listview from a database. Here is the code I used for my app

Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.

public List<Category> getAllCategorys() {
        ArrayList<Category> categoryList = new ArrayList<Category>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CATEGORY;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        try{
            if (cursor.moveToFirst()) {
                do {
                    Category category = new Category();
                    category.setID(Integer.parseInt(cursor.getString(0)));
                    category.setCategory(cursor.getString(1));
                    // Adding category to list
                    categoryList.add(category);
                } while (cursor.moveToNext());
            }   
        }finally{
            cursor.close();
        }   
        db.close();
        // return category list
        return categoryList;

Here is how I fill the ListView by calling the database.

int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();

category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{   
    category_data[i] = cn.getCategory(); // get the name of the category and add it to array
    i++;   
} 

listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);

EDIT: Here is something that should work for you

public List<String> getSitesByClientname(String id) {
    String[] args={id};
    ArrayList<String> result = new ArrayList<String>();
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE +      " WHERE client_id=?", args);

    try{
       if (myCursor.moveToFirst()){
           do{
              result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
           }while(myCursor.moveToNext());
        }
    }finally{
         myCursor.close();
    }
    db.close();
    return result;
}

Use it like this

List<String> sites_data = dbHelper.getSitesByClientname(uID);

result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{   
    result_data[i] = s; // get the name of the category and add it to array
    i++;   
} 

listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);

这篇关于显示数据从SQLite数据库到ListView控件中的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆