【问题标题】:Why is my ListView not working with my SQL Database?为什么我的 ListView 不能与 mySQL 数据库一起使用?
【发布时间】:2015-02-14 11:22:13
【问题描述】:

我遇到了以下问题:

我创建了一个 SQL 数据库,现在尝试将它与我的 ListViewActivity 连接,以便在布局中显示它。但是当我运行模拟器时,ListView 不显示任何内容。我希望有人能尽快帮助我:)

我的 ListViewActivity 的代码:

import java.util.ArrayList;
import com.example.fotooh2.R;
import com.example.fotooh2.DatabaseHandler;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

import android.widget.ListView;

public class ListViewActivity extends Activity {

    public ListView listView1;

    public static ArrayList<String> ArrayofPositions = new ArrayList<String>();

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

        DatabaseHandler db = new DatabaseHandler(this);
        db.getAllPositionstoList();
        Log.d("FirstScreenActivity", "ListView bis hier!"); // LOG Fehlersuche

        listView1 = (ListView) findViewById(R.id.listView1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.listview_item_row, ArrayofPositions);

        listView1.setAdapter(adapter);

        Log.d("FirstScreenActivity", "ListView Läuft!"); // LOG Fehlersuche

    }
}

我的 listview_item_row 的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

     <ImageView android:id="@+id/imgIcon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="15dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

     <TextView android:id="@+id/txtTitle"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:textStyle="bold"
        android:textSize="22dp"
        android:textColor="#000000"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

</LinearLayout>

“suche_liste”的代码:

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"> 

     <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

DatabaseHandler 中的代码:

  public List<Position> getAllPositionstoList() {
        List<Position> PositionsList = new ArrayList<Position>();
        // Select All Query
        String selectQuery = "SELECT * FROM " + TABLE_POSITIONS;

        SQLiteDatabase data = this.getWritableDatabase();
        Cursor cursor = data.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Position position = new Position();
                String name = "Name:" + cursor.getString(1);
                ListViewActivity.ArrayofPositions.add(name);
                PositionsList.add(position);
            } while (cursor.moveToNext());
        }

        // return Positions-Liste
        return PositionsList;
    }
}

【问题讨论】:

    标签: android sql database listview android-sqlite


    【解决方案1】:

    http://developer.android.com/reference/android/widget/ArrayAdapter.html: “默认情况下,此类期望提供的资源 id 引用单个 TextView。如果您想使用更复杂的布局,请使用也采用字段 id 的构造函数。该字段 id 应该引用 TextView在更大的布局资源中。”

    试试:

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.listview_item_row,R.id.txtTitle, ArrayofPositions);
    

    如果您还想填充图像,似乎您需要一个从 BaseAdapter 继承的自定义类。

    /edit :这段代码,使用你的 2 个 XML 文件,绝对有效:

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.suche_liste);
                ArrayList<String> ArrayOfPositions = new ArrayList<String>();
    
                ArrayOfPositions.add("Hi");
                ArrayOfPositions.add("Ho");
                ListView listView1 = (ListView) findViewById(R.id.listView1);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.listview_item_row,R.id.txtTitle, ArrayOfPositions);
    
                listView1.setAdapter(adapter);
    
            }
    

    【讨论】:

    • 嗯谢谢你,但是当我运行模拟器时 ListView 仍然是空的
    • 您是否 100% 确定您的数组包含数据?我添加了一个工作代码示例,将“Hi”和“Ho”显示为列表项。
    • 好的,很酷,列表视图中的“hi”和“ho”可以正常工作:)
    • hmmmm,我创建了 ArraysofPositions,它应该包含 SQL-Lite 数据库中的所有数据,我不知道为什么它不起作用
    • 您的数据库似乎是空的。您应该在您的 getAllPositionstoList() 方法中设置一个断点并单步执行它以查看您的查询是否返回任何数据。哦,顺便说一句:完成后您应该关闭光标。
    【解决方案2】:

    “SQLLITE_Data”的代码:

    package com.example.fotooh2;
    
    import java.util.List;
    
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    
    
    public class SQLLITE_Data extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            DatabaseHandler db = new DatabaseHandler(this);
    
            /**
             * CRUD Operations
             * */
            // Inserting Positions
            Log.d("Insert: ", "Inserting ..");
            db.addPosition(new Position("Hobbersdorfer Felder", "Landschaft" , 53.94966, 10.70343));
            db.addPosition(new Position("Felder bei Pelzerhaken", "Landschaft", 54.10039, 10.83878));
            db.addPosition(new Position("Felder bei Neustadt", "Landschaft" , 54.10713, 10.84201));
            db.addPosition(new Position("Felder bei Gronenberg", "Landschaft" , 54.04454, 10.69646));
            db.addPosition(new Position("Felder bei Stolpe", "Landschaft" , 54.15785, 10.78290));
            db.addPosition(new Position("Felder bei Ruhleben", "Landschaft" , 54.11740, 10.88896));
            db.addPosition(new Position("Niendorfer Hafen: ", "Häfen" , 53.99321, 10.81323));
            db.addPosition(new Position("Neustädter Hafen: ", "Häfen" , 54.10509, 10.81117));
    
    
            // Reading all positions
            Log.d("Reading: ", "Reading all positions..");
            List<Position> positions = db.getAllPositions();       
    
            for (Position cn : positions) {
                String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() +" ,Kategorie: " + cn.getKategorie() + " ,Länge: " + cn.getLaenge()+" ,Breite: " + cn.getBreite();
                    // Writing Contacts to log
            Log.d("Name: ", log);
    
            }
        }
    }
    

    完整的DatabaseHandler代码:

    package com.example.fotooh2;
    
    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;
    
    
    public class DatabaseHandler extends SQLiteOpenHelper {
    
        // All Static variables
    
        // Database Version
    
        private static final int DATABASE_VERSION = 5;
    
        // Database Name
    
        private static final String DATABASE_NAME = "PositionManager";
    
        // Positions table name
    
        private static final String TABLE_POSITIONS = "positions";
    
        // Positions Table Columns names
    
        private static final String KEY_ID = "_id";
    
        private static final String KEY_NAME = "Name";
    
        private static final String KEY_KATEGORIE = "Kategorie";
    
        private static final String KEY_LAENGE = "Laenge";
    
        private static final String KEY_BREITE = "Breite";
    
        public DatabaseHandler(Context context) {
    
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
    
        }
    
        // Creating Tables
    
        @Override
        public void onCreate(SQLiteDatabase db) {
    
            String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_POSITIONS + "("
    
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                    + KEY_KATEGORIE + " TEXT," + KEY_LAENGE + " REAL," + KEY_BREITE
                    + " REAL" + ")";
    
            db.execSQL(CREATE_CONTACTS_TABLE);
    
        }
    
        // Upgrading database
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
            // Drop older table if existed
    
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_POSITIONS);
    
            // Create tables again
    
            onCreate(db);
    
        }
    
        /**
         * 
         * All CRUD(Create, Read, Update, Delete) Operations
         */
    
        // Adding new contact
    
        void addPosition(Position position) {
    
            SQLiteDatabase db = this.getWritableDatabase();
    
            ContentValues values = new ContentValues();
    
            values.put(KEY_NAME, position.getName()); // Name
    
            values.put(KEY_KATEGORIE, position.getKategorie()); // Kategorie
    
            values.put(KEY_LAENGE, position.getLaenge()); // Länge
    
            values.put(KEY_BREITE, position.getBreite()); // Breite
    
            // Inserting Row
    
            db.insert(TABLE_POSITIONS, null, values);
    
            db.close(); // Closing database connection
    
        }
    
        // Getting single position
    
        Position getPosition(int id) {
    
            SQLiteDatabase db = this.getReadableDatabase();
    
            Cursor cursor = db.query(TABLE_POSITIONS, new String[] { KEY_ID,
    
            KEY_NAME, KEY_KATEGORIE, KEY_LAENGE, KEY_BREITE }, KEY_ID + "=?",
    
            new String[] { String.valueOf(id) }, null, null, null, null);
    
            if (cursor != null)
    
                cursor.moveToFirst();
    
            Position position = new Position(Integer.parseInt(cursor.getString(0)),
                    cursor.getString(1), cursor.getString(2), cursor.getFloat(3),
                    cursor.getFloat(4));
    
            // return position
    
            return position;
    
        }
    
        // Getting All Positions
    
        public List<Position> getAllPositions() {
    
            List<Position> positionList = new ArrayList<Position>();
    
            // Select All Query
    
            String selectQuery = "SELECT  * FROM " + TABLE_POSITIONS;
    
            SQLiteDatabase db = this.getWritableDatabase();
    
            Cursor cursor = db.rawQuery(selectQuery, null);
    
            // looping through all rows and adding to list
    
            if (cursor.moveToFirst()) {
    
                do {
    
                    Position position = new Position();
    
                    position.setID(Integer.parseInt(cursor.getString(0)));
    
                    position.setName(cursor.getString(1));
    
                    position.setKategorie(cursor.getString(2));
    
                    position.setLaenge(cursor.getFloat(3));
    
                    position.setBreite(cursor.getFloat(4));
    
                    // Adding position to list
    
                    positionList.add(position);
    
                } while (cursor.moveToNext());
    
            }
    
            // return position list
    
            return positionList;
    
        }
    
        // Updating single position
    
        public int updatePosition(Position position) {
    
            SQLiteDatabase db = this.getWritableDatabase();
    
            ContentValues values = new ContentValues();
    
            values.put(KEY_NAME, position.getName());
    
            values.put(KEY_KATEGORIE, position.getKategorie());
    
            values.put(KEY_LAENGE, position.getLaenge());
    
            values.put(KEY_BREITE, position.getBreite());
    
            // updating row
    
            return db.update(TABLE_POSITIONS, values, KEY_ID + " = ?",
    
            new String[] { String.valueOf(position.getID()) });
    
        }
    
        // Deleting single position
    
        public void deletePosition(Position position) {
    
            SQLiteDatabase db = this.getWritableDatabase();
    
            db.delete(TABLE_POSITIONS, KEY_ID + " = ?",
    
            new String[] { String.valueOf(position.getID()) });
    
            db.close();
    
        }
    
        // Getting positions Count
    
        public int getPositionsCount() {
    
            String countQuery = "SELECT  * FROM " + TABLE_POSITIONS;
    
            SQLiteDatabase db = this.getReadableDatabase();
    
            Cursor cursor = db.rawQuery(countQuery, null);
    
            int resultCount = cursor.getCount();
    
            // return count
    
            return resultCount;
    
        }
    
        public List<Position> getAllPositionstoList() {
            List<Position> PositionsList = new ArrayList<Position>();
            // Select All Query
            String selectQuery = "SELECT * FROM " + TABLE_POSITIONS;
    
            SQLiteDatabase data = this.getWritableDatabase();
            Cursor cursor = data.rawQuery(selectQuery, null);
    
            // looping through all rows and adding to list
    
            if (cursor.moveToFirst()) {
    
                do {
                    Position position = new Position();
    
                    String name = "Name:" + cursor.getString(1);
                    ListViewActivity.ArrayofPositions.add(name);
    
                    PositionsList.add(position);
                } while (cursor.moveToNext());
    
                cursor.close(); // Cursor Close
            }
    
            // return Positions-Liste
            return PositionsList;
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-09
      • 1970-01-01
      • 2012-12-19
      • 2011-12-25
      • 2020-10-08
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多