无法从sqlite数据库获取所有行

时间:2015-03-23 10:26:17

标签: java android sqlite

我正在开发名为Stock Manager的小应用程序。我想将所有行详细信息返回到listview。但我只收到最后一行详细信息。

检查此数据库文件DataBaseHandler.java

package com.example.stockmanager;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHandler extends SQLiteOpenHelper{


    private SQLiteDatabase sql=null;
    private static String CREATE_TABLE="";

    public DataBaseHandler(Context context) 
    {
        super(context, Util.DATABASE_NAME, null, Util.DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        CREATE_TABLE = "CREATE TABLE " +Util.STOCK_TABLE + "("
                +Util.USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                +Util.CURRENT_STOCK +" TEXT NOT NULL, "
                +Util.DATE +" TEXT NOT NULL, "
                +Util.TIME +" TEXT NOT NULL" + ")";
        db.execSQL(CREATE_TABLE);
        Log.i("Authentication", ""+CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " +Util.STOCK_TABLE);

    }

    public void insertDetails(Model m)
    {
        sql=this.getWritableDatabase();
        ContentValues cn=new ContentValues();

        cn.put(Util.CURRENT_STOCK, m.getCurrentStock().toString());
        cn.put(Util.DATE, m.getDate().toString());
        cn.put(Util.TIME, m.getTime().toString());
        long insertId=sql.insert(Util.STOCK_TABLE, null, cn);
        Log.i("new raw inserted", ""+insertId);
    }

    public List<Model> getAllDetails()
    {
        List<Model> show=new ArrayList<Model>(); 
        sql=this.getReadableDatabase();
        Cursor cursor=null;
        /*String query="SELECT * FROM " +Util.STOCK_TABLE+" ORDER BY "+Util.USER_ID+" ASC";
        cursor=sql.rawQuery(query, null);*/
        cursor=sql.query(Util.STOCK_TABLE, new String[] {Util.CURRENT_STOCK,Util.DATE,Util.TIME}, null, null, null, null, null);
        cursor.moveToFirst();
        while(!cursor.isAfterLast())
        {
            Model m=new Model();
            m.setCurrentStock(cursor.getString(0));
            m.setDate(cursor.getString(1));
            m.setTime(cursor.getString(2));

            show.add(m);
            cursor.moveToNext();
        }
        cursor.close();
        sql.close();
        return show;
    }

     public String getLastStock()
     {
         sql=this.getWritableDatabase();

            Cursor cursor;
            String q="SELECT "+Util.CURRENT_STOCK+" FROM "+Util.STOCK_TABLE+" ORDER BY " +Util.USER_ID+" DESC LIMIT 1";
            cursor=sql.rawQuery(q, null);
            String stock = null;
            if(cursor.moveToFirst())
                stock=cursor.getString(0);

        return stock;

     }
}

检查此java文件History.java

package com.example.stockmanager;


import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class History extends Activity {

    private ListView lst;
    private Adaptar aa;
    private ArrayList<String> array_stock;
    private ArrayList<String> array_date;
    private ArrayList<String> array_time;
    private DataBaseHandler data;


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

        lst=(ListView)findViewById(R.id.listView1);
        data=new DataBaseHandler(getApplicationContext());
        try
        {
        List<Model> ls=data.getAllDetails();

        array_stock = new ArrayList<String>(ls.size());
        array_date = new ArrayList<String>(ls.size());
        array_time = new ArrayList<String>(ls.size());

        Log.i("Size", ""+array_stock);

        for(int i=0;i<ls.size();i++)
        {
            Model m=ls.get(i);
            String stock=m.getCurrentStock();
            String date=m.getDate();
            String time=m.getTime();


            Log.i("Stock", ""+stock);
            Log.i("date", ""+date);
            Log.i("time", ""+time);


            array_stock.add(stock);
            array_date.add(date);
            array_time.add(time);


        }

        aa=new Adaptar(this,ls);
        lst.setAdapter(aa);

        /*lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View rowView, int positon,long id) {
                Toast.makeText(rowView.getContext(), ""+positon, Toast.LENGTH_LONG).show();
                removeListItem(rowView,positon);
            }
        });*/

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }


    /*protected void removeListItem(View rowView, final int positon) {

          final Animation animation = AnimationUtils.loadAnimation(History.this,android.R.anim.slide_out_right);
          rowView.startAnimation(animation);
          Handler handle = new Handler();
          handle.postDelayed(new Runnable() {

            @Override
              public void run() {
                  array_stock.remove(positon);
                  array_date.remove(positon);
                  array_time.remove(positon);

                  aa.notifyDataSetChanged();
                  animation.cancel();
              }
          },1000);

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

检查此adaptar类Adaptar.java

package com.example.stockmanager;

import java.util.List;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;

public class Adaptar extends ArrayAdapter<Model> implements ListAdapter{

    private List<Model> lsadd;
    private LayoutInflater inflator;

    public Adaptar(History history, List<Model> ls) {
        // TODO Auto-generated constructor stub
        super(history, R.layout.row, ls);
        this.lsadd=ls;
        inflator=history.getLayoutInflater();
    }

    static class ViewHolder
    {
        protected TextView stock;
        protected TextView date;
        protected TextView time;

    }


    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        // TODO Auto-generated method stub
        ViewHolder viewholder=null;
        final int temposition= arg0;
        if(arg1==null)
        {
            arg1=inflator.inflate(R.layout.row, null);
            viewholder=new ViewHolder();
            viewholder.stock=(TextView)arg1.findViewById(R.id.t2);
            viewholder.date=(TextView)arg1.findViewById(R.id.t3);
            viewholder.time=(TextView)arg1.findViewById(R.id.t4);


            arg1.setTag(viewholder);
            arg1.setTag(R.id.t2, viewholder.stock);
            arg1.setTag(R.id.t3, viewholder.date);
            arg1.setTag(R.id.t4, viewholder.time);

            }
        else
        {
            viewholder=(ViewHolder)arg1.getTag();
        }


        viewholder.stock.setText(lsadd.get(temposition).getCurrentStock());
        viewholder.date.setText(lsadd.get(temposition).getDate());
        viewholder.time.setText(lsadd.get(temposition).getTime());
        return arg1;
        }

}

logcat的

03-23 11:15:43.080: I/Checking(1167): com.example.stockmanager.Model@b2da59b0
03-23 11:15:43.090: I/Checking(1167): com.example.stockmanager.Model@b2d8fe48
03-23 11:15:43.090: I/Checking(1167): com.example.stockmanager.Model@b2da7e20
03-23 11:15:43.090: I/Checking(1167): com.example.stockmanager.Model@b2d87cf8
03-23 11:15:43.090: I/Size(1167): []
03-23 11:15:43.090: I/Stock(1167): 106
03-23 11:15:43.090: I/date(1167): 23-3-2015
03-23 11:15:43.090: I/time(1167): 11:12:13
03-23 11:15:43.090: I/Stock(1167): 106
03-23 11:15:43.090: I/date(1167): 23-3-2015
03-23 11:15:43.090: I/time(1167): 11:12:13
03-23 11:15:43.090: I/Stock(1167): 106
03-23 11:15:43.090: I/date(1167): 23-3-2015
03-23 11:15:43.090: I/time(1167): 11:12:13
03-23 11:15:43.090: I/Stock(1167): 106
03-23 11:15:43.090: I/date(1167): 23-3-2015
03-23 11:15:43.090: I/time(1167): 11:12:13

我的数据库

user_id current_stock    date          time
1           50         24-3-2015      1:58:22
2           100        24-3-2015      1:58:26
3           150        24-3-2015      1:58:29
4           200        24-3-2015      1:58:36
5           195        24-3-2015      1:58:41
6           245        24-3-2015      1:58:49

2 个答案:

答案 0 :(得分:0)

在您的适配器中,您不会覆盖方法getCount,因为:

@Override
public int getCount() {
    return lsadd.size();
}

删除这些行:

    arg1.setTag(R.id.t2, viewholder.stock);
    arg1.setTag(R.id.t3, viewholder.date);
    arg1.setTag(R.id.t4, viewholder.time);

答案 1 :(得分:0)

在get allDetails方法中尝试此示例:

SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts", null ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME))); res.moveToNext(); }