ListView ArrayAdapter 没有从 SQLite 获取任何数据

ListView ArrayAdapter didn't get any data from SQLite

我有一个应用程序可以在 SQLite 数据库的 ListView 中显示数据

我没有得到任何异常等等,但我的数据没有显示

这是我的 Activity 代码

    package id.habatus.amsw;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;

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

public class SyncCollectActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private CollectDataHelper dbHelper;
    private ListView list;
    private List<SyncCollect> syncs;
    Cursor cursor;

    public static final int NAME_SYNCED_WITH_SERVER = 1;
    public static final int NAME_NOT_SYNCED_WITH_SERVER = 0;
    public static final String DATA_SAVED_BROADCAST = "id.habatus.datasaved";
    private BroadcastReceiver broadcastReceiver;
    private SyncCollectAdapter adapter;
    Button col, drop;
    ImageButton back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sync_collect);
        dbHelper = new CollectDataHelper(this);
        syncs = new ArrayList<>();

        list = findViewById(R.id.listViewNames);
        list.setOnItemClickListener(this);

        drop = findViewById(R.id.btncanvas);
        back = findViewById(R.id.kembali);
        loadData();
        refresh();
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                //loading the names again
                loadData();
                refresh();
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST));


        drop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(SyncCollectActivity.this,SyncActivity.class);
                startActivity(i);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(SyncCollectActivity.this,DecisionActivity.class);
            }
        });


    }

    private void loadData() {
        syncs.clear();
        Cursor cursor = dbHelper.getData();
        if (cursor.moveToFirst()){
            while (cursor.moveToNext()){
                SyncCollect sync = new SyncCollect(
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.id_p)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.nama)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.alamat)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.saldo)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.pinjaman)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.angsuran)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.keterangan)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.latitude)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.longitude)),
                        cursor.getString(cursor.getColumnIndex(CollectDataHelper.status)),
                        cursor.getInt(cursor.getColumnIndex(CollectDataHelper.syncstatus))

                );
                syncs.add(sync);
            }
        }
        adapter = new SyncCollectAdapter(this,R.layout.sync_item,syncs);
        list.setAdapter(adapter);
    }

    public void refresh(){
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    public void onPause() {
        unregisterReceiver(broadcastReceiver);
        super.onPause();
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }
}

在这个 activity 中,我想显示我的 SQLite 数据库中的所有数据,我怀疑在方法 loadData 上有问题,但也许是错误的。 这是我的 CollectDataHelper class

    package id.habatus.amsw;

/**
 * Created by SMK TELKOM on 9/6/2018.
 */

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

import java.util.ArrayList;
import java.util.HashMap;


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

import java.util.ArrayList;
import java.util.HashMap;


    public class CollectDataHelper extends SQLiteOpenHelper {
    public static final String KEY_ROWID ="_id";
    public static  final String id_p = "id_p";
    public static  final String nama = "nama";
    public static  final String alamat = "alamat";
    public static  final String saldo = "saldo";
    public static  final String pinjaman = "pinjaman";
    public static  final String angsuran = "angsuran";
    public static  final String keterangan = "keterangan";
    public static  final String latitude = "latitude";
    public static  final String longitude = "longitude";
    public static  final String syncstatus = "syncstatus";
    public static final String status = "status";
    public static  final String table = "collect";
    String TAG = "C_DL Activity";

    public static  final String broadcast = "id.habatus.amsw.broadcast";
    public static final  int SYNC_STATUS_OK = 1;
    public static final  int SYNC_STATUS_FAILED = 0;
    private static final String DATABASE_NAME = "col";
    private static final int DATABASE_VERSION = 1;
    private static final String  DROP_TABLE ="DROP TABLE IF EXISTS collect";
    public CollectDataHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql = "create table collect(id_p integer primary key, nama text null, alamat text null, saldo text null, pinjaman text null, angsuran text null, keterangan text null, latitude text null, longitude text null,status text null, syncstatus integer);";
        Log.d("Data", "onCreate: " + sql);
        db.execSQL(sql);
        sql = "INSERT INTO collect (`id_p`, `nama`, `alamat`, `saldo`, `pinjaman`, `angsuran`, `keterangan`, `latitude`, `longitude`, `status`, `syncstatus`) VALUES\n" +
                "(909095, 'AM Nata Waskita', 'Kediri', '0', '500000', '65000', 'segera', '-7.2583968', '112.7109815','NOTCOLL', '0');";
        db.execSQL(sql);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    public Cursor getList(){
        SQLiteDatabase db = getReadableDatabase();
        String query = "SELECT rowid as " +KEY_ROWID+ "," +id_p+ "," +nama+ "," +alamat+ "," +saldo+ "," +pinjaman+ "," +angsuran+
                "," +keterangan+ " FROM " + table;

        Cursor cursor= db.rawQuery(query,null);
        if (cursor == null){
            return null;
        } else if (!cursor.moveToFirst()){
            cursor.close();
            return null;
        }
        return  cursor;
    }
    public Cursor getListByKeyword(String search){
        SQLiteDatabase db = getReadableDatabase();
        String query = "SELECT rowid as "+KEY_ROWID+ "," +id_p+","+nama+ ","+alamat+","+saldo+","+pinjaman+","+angsuran+
                ","+keterangan+" FROM " + table + " WHERE " + nama + "  LIKE  '%" +search+ "%' " ;

        Cursor cursor = db.rawQuery(query,null );

        if(cursor == null){
            return null;
        }else if (!cursor.moveToFirst()){
            cursor.close();
            return null;
        }
        return cursor;
    }

    public ArrayList<HashMap<String, String>> getAllData() {
        ArrayList<HashMap<String, String>> wordList;
        wordList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT * FROM " + table;
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(id_p, cursor.getString(0));
                map.put(nama, cursor.getString(1));
                map.put(alamat, cursor.getString(2));
                map.put(saldo, cursor.getString(3));
                map.put(pinjaman, cursor.getString(4));
                map.put(angsuran, cursor.getString(5));
                map.put(keterangan, cursor.getString(6));
                map.put(latitude, cursor.getString(7));
                map.put(longitude, cursor.getString(8));
                map.put(status, cursor.getString(9));
                wordList.add(map);
            } while (cursor.moveToNext());
        }

        Log.e("select sqlite ", "" + wordList);

        database.close();
        return wordList;
    }

    public boolean edit(String id_p, String nama, String alamat, String saldo, String pinjaman, String angsuran, String keterangan,String latitude,
                        String longitude, String status,int syncstatus){
        try{
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(CollectDataHelper.nama,nama);
            cv.put(CollectDataHelper.alamat,alamat);
            cv.put(CollectDataHelper.saldo,saldo);
            cv.put(CollectDataHelper.pinjaman,pinjaman);
            cv.put(CollectDataHelper.angsuran,angsuran);
            cv.put(CollectDataHelper.keterangan,keterangan);
            cv.put(CollectDataHelper.latitude,latitude);
            cv.put(CollectDataHelper.longitude,longitude);
            cv.put(CollectDataHelper.status,status);
            cv.put(CollectDataHelper.syncstatus, syncstatus);
            int result = db.update(table,cv, CollectDataHelper.id_p + " =?",new String[]{id_p});
            if (result > 0){
                return true;
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
        return false;
    }
    public  boolean updatelocal(String id_p , int syncstatus){
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(DataHelper.syncstatus,syncstatus);

        database.update(DataHelper.table,contentValues, CollectDataHelper.id_p + "=" + id_p,null);
        return true;
    }
    public Cursor getUnsynced(){
        SQLiteDatabase db = this.getReadableDatabase();
        String sql = "SELECT * FROM " + table + " WHERE "+ syncstatus + " = 0";
        Cursor c = db.rawQuery(sql,null);
        return c;
    }
    public Cursor getData() {
        SQLiteDatabase db = this.getReadableDatabase();
        String sql = "SELECT * FROM " + table + " ORDER BY " + id_p + " ASC;";
        Cursor c = db.rawQuery(sql, null);
        return c;
    }


}

在方法 getData 中,我想 select 从收集的所有数据 table 并按其 id 排序,我在网站上的 SQLite 查询执行器上尝试了查询,它工作正常。

这是我的适配器class

    package id.habatus.amsw;

import android.content.Context;
import android.media.Image;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by SMK TELKOM on 9/20/2018.
 */

public class SyncCollectAdapter extends ArrayAdapter<SyncCollect> {
    private List<SyncCollect> SyncCollects;
    private Context context;

    public SyncCollectAdapter(Context context, int resource,List<SyncCollect> SyncCollects) {
        super(context, resource, SyncCollects);
        this.context = context;
        this.SyncCollects = SyncCollects;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //getting the layoutinflater
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //getting listview itmes
        View listViewItem = inflater.inflate(R.layout.sync_item2, null, true);
        TextView txid = listViewItem.findViewById(R.id.txid_p);
        TextView txnama = listViewItem.findViewById(R.id.txname);
        TextView txalamat = listViewItem.findViewById(R.id.txalamat);
        TextView txsaldo = listViewItem.findViewById(R.id.txsaldo);
        TextView txpinjaman = listViewItem.findViewById(R.id.txpinjaman);
        TextView txangsuran = listViewItem.findViewById(R.id.txangsuran);
        TextView txketerangan = listViewItem.findViewById(R.id.txketerangan);
        TextView txlatitude = listViewItem.findViewById(R.id.txlatitude);
        TextView txlongitude = listViewItem.findViewById(R.id.txlongitude);
        TextView txstatus = listViewItem.findViewById(R.id.txstatus);
        ImageView status = listViewItem.findViewById(R.id.imsync);

        //getting the current name
        SyncCollect name = SyncCollects.get(position);

        //setting the name to textview
        txid.setText(name.getId_p());
        txnama.setText(name.getNama());
        txalamat.setText(name.getAlamat());
        txsaldo.setText(name.getSaldo());
        txpinjaman.setText(name.getPinjaman());
        txangsuran.setText(name.getAngsuran());
        txketerangan.setText(name.getKeterangan());
        txlatitude.setText(name.getLatitude());
        txlongitude.setText(name.getLongitude());
        txstatus.setText(name.getStatus());


        //if the SyncCollected status is 0 displaying
        //queued icon
        //else displaying SyncCollected icon
        if (name.getSyncstatus() == 0)
            status.setBackgroundResource(R.drawable.refresh);
        else
            status.setBackgroundResource(R.drawable.checked);

        return listViewItem;
    }
}

我认为这个 class 没有任何问题,因为我在数据库中创建了它和我的专栏一样多,但我只是把它留在这里以备不时之需

这是我的 SyncCollect Class

    public class SyncCollect {

    public String nama;
    public String id_p;
    public int syncstatus;
    public String saldo;
    public String alamat;
    public String pinjaman;
    public String angsuran;
    public String keterangan;
    public String latitude;
    public String longitude;
    public String status;



    public SyncCollect(String id_p, String nama, String alamat, String pinjaman, String angsuran, String keterangan, String saldo, String latitude, String longitude,String status, int syncstatus) {
        this.id_p = id_p;
        this.nama = nama;
        this.alamat = alamat;
        this.saldo = saldo;
        this.pinjaman = pinjaman;
        this.angsuran = angsuran;
        this.keterangan = keterangan;
        this.latitude=latitude;
        this.longitude=longitude;
        this.status = status;
        this.syncstatus=syncstatus;

    }
    public int getSyncstatus() {
        return syncstatus;
    }

    public void setSyncstatus(int syncstatus) {
        this.syncstatus = syncstatus;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    public String getId_p() {
        return id_p;
    }

    public void setId_p(String id_p) {
        this.id_p = id_p;
    }

    public String getSaldo() {
        return saldo;
    }

    public void setSaldo(String saldo) {
        this.saldo = saldo;
    }

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getPinjaman() {
        return pinjaman;
    }

    public void setPinjaman(String pinjaman) {
        this.pinjaman = pinjaman;
    }

    public String getAngsuran() {
        return angsuran;
    }

    public void setAngsuran(String angsuran) {
        this.angsuran = angsuran;
    }

    public String getKeterangan() {
        return keterangan;
    }

    public void setKeterangan(String keterangan) {
        this.keterangan = keterangan;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getStatus() {
        return status;
    }

    public void  setStatus(String status){
        this.status = status;
    }
}

我认为这里也没什么问题,因为它的参数与我在数据库中的列相同。

我已经搜索了所有与此相关的内容,但没有解决这个问题,我希望有人能帮助我。

非常感谢

您的问题可能是由于 table 只有一行(根据 CollectDataHelper class 的 onCreate 方法中的插入)。

也就是说,假设插入了该行,然后没有插入其他行。

movetoFirst 将移动到第一行(仅),然后是 moveToNext,然后是最后一行之后(如果有多行,则在第二行,因此跳过第一行)因此返回 false 并且未输入 while 循环。因此没有数据可显示,也没有错误。

也许解决方案是使用:-

private void loadData() {
    syncs.clear();
    Cursor cursor = dbHelper.getData();
    while (cursor.moveToNext()){
        SyncCollect sync = new SyncCollect(
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.id_p)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.nama)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.alamat)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.saldo)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.pinjaman)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.angsuran)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.keterangan)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.latitude)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.longitude)),
            cursor.getString(cursor.getColumnIndex(CollectDataHelper.status)),
            cursor.getInt(cursor.getColumnIndex(CollectDataHelper.syncstatus))
        );
        syncs.add(sync);
    }
  • 即使 table 包含更多行,如果不进行上述更改,第一行也会被跳过。