为什么我的ListView无法使用我的SQL数据库?

时间:2015-02-14 11:22:13

标签: android sql database listview android-sqlite

我遇到了以下问题:

我创建了一个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;
    }
}

2 个答案:

答案 0 :(得分:0)

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);

        }

答案 1 :(得分:0)

“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;

    }
}