使用Arraylist从sqlite中检索记录

时间:2012-12-09 10:27:23

标签: android sqlite

我正在从数据库中检索所有记录并保存数组列表中的所有记录。当我显示数组列表记录,显示重复数据时,我不知道什么是prolblem?

在view_record类中调用此函数:

public ArrayList<tuple> getdata() {         // TODO Auto-generated method stub

        tuple obj=new tuple();
        Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);

        if(c == null) {
         return null;
        }

        ArrayList <tuple> data = new ArrayList<tuple>();

        // String result = " ";

        int i=0;

        for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
                  obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
                  obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
                  obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
                  obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
                  obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
                  obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
                  obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
                  obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
                  data.add(i, obj);
                  i++;
       }
       c.close();

       return data;     }

我的view_record类

public class view_record extends Activity {

    @Override protected void onCreate(Bundle savedInstanceState) {      // TODO Auto-generated method stub      

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

        TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
        ImageView img=(ImageView) findViewById(R.id.img_view);      

        db_handler info=new db_handler(this);
        info.open();    

        //   Log.d("abc", "adb");

        ArrayList <tuple> data=info.getdata();
        Log.d("abc", "adb");

        String result="";

        for(int i=0;i<data.size();i++){
               result +=" " + data.get(i).ROWID + "   " + data.get(i).CNAME + "   " + data.get(i).SNAME + "   " + data.get(i).FAMILY + "    " + data.get(i).LOCATION + "\n";

              tv.setText(result);
              img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
        }
        info.close();   } }

我想查看如下:

   " 1 cname sname family location "
   " 2 cname sname family location "

但我得到了              “2 cname sname family location”              “2 cname sname family location”

表示最后一条记录显示两次。

还有一件事,我想得到cname = something的所有记录,这样做时会出错...

1 个答案:

答案 0 :(得分:0)

你没有在for循环中创建一个新项目。那就是你得到的结果相同。只是做...

for loop开头添加此行obj=new tuple();

回答您的第二个问题

for(int i=0;i<data.size();i++){
               result +=" " + data.get(i).ROWID + "   " + data.get(i).CNAME + "   " + data.get(i).SNAME + "   " + data.get(i).FAMILY + "    " + data.get(i).LOCATION + "\n";


              img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
        }
   tv.setText(Html.fromHtml(result));