Android: создание собственного ListView с помощью SQLite - PullRequest
0 голосов
/ 29 июля 2011

В моем проекте у меня есть данные, которые считываются из базы данных, и я пытаюсь показать эти данные в виде списка. Пока все хорошо, но я не знаю, как форматировать строки в виде списка.

вот код моего Java-файла.

public class racuni extends ListActivity {
    private ArrayList<String> results = new ArrayList<String>();
    private String tableName = DbHelper.racuniTable;
    private SQLiteDatabase newDB;

DbHelper dbhelper;  

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

    dbhelper = new DbHelper(this);

//      addRacun("Tom", 111, "osebni");
//      addRacun("Tom", 875.999, "personal");

    openAndQueryDatabase();

    displayResultList();
}

private void addRacun(String ime, double stanje, String tip) {
    SQLiteDatabase db = dbhelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(DbHelper.colName, ime);
    values.put(DbHelper.colValue, stanje);
    values.put(DbHelper.colAccType, tip);
    db.insert(DbHelper.racuniTable, null, values);
}

private void displayResultList() {        
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
    getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
    try {
        DbHelper dbHelper = new DbHelper(this.getApplicationContext());
        newDB = dbHelper.getWritableDatabase();         
        Cursor c = newDB.rawQuery("SELECT _id, Ime, Stanje, Tip_racuna FROM Racuni", null);
        if (c != null ) {
            if  (c.moveToFirst()) {
                do {
                    int id = c.getInt(c.getColumnIndex("_id"));
                    String firstName = c.getString(c.getColumnIndex("Ime"));
                    double stanje = c.getDouble(c.getColumnIndex("Stanje"));
                    String tipracuna = c.getString(c.getColumnIndex("Tip_racuna")); 
                    results.add("Ime: " + firstName + ", Stanje: " + stanje + " Tip racuna: " +tipracuna);
                }while (c.moveToNext());
            }
        }           
    } catch (SQLiteException se ) {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    } 
}
}

xml файл simple_list_item_1.xml

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

    <ListView android:layout_height="wrap_content" android:id="@+id/list" android:layout_width="match_parent"></ListView>

</LinearLayout>

и файл racuni_pregled.xml

 <?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">
  <RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  >

    <ImageView android:layout_height="wrap_content" android:src="@drawable/icon" android:id="@+id/imageView_logo" android:layout_width="wrap_content"></ImageView>
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:text="Računi" android:layout_toRightOf="@id/imageView_logo" android:layout_alignBottom="@id/imageView_logo" ></TextView>
    <View android:layout_width="fill_parent" android:layout_height="2dip" android:background="#000000" android:layout_below="@id/imageView_logo"/>
    <TextView android:onClick="accountClick" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/imageView_logo" android:minWidth="200sp" android:clickable="true"></TextView>

    <ListView
    android:layout_below="@id/imageView_logo"
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

    <Button android:text="Button" android:id="@+id/button_7days" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/android:list" android:layout_marginLeft="50sp"></Button>
    <Button android:text="Button" android:id="@+id/button_thismonth" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/android:list" android:layout_toRightOf="@id/button_7days"></Button>
    <Button android:text="Button" android:id="@+id/button_lastmonth" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/android:list" android:layout_toRightOf="@id/button_thismonth"></Button>

    <View android:id="@+id/racuni_pregled_vmesnacrta" android:layout_width="fill_parent" android:layout_height="2dip" android:background="#000000" android:layout_below="@id/button_7days"/>

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView4" android:text="Skupno" android:layout_below="@id/racuni_pregled_vmesnacrta"></TextView>

    <TextView android:text="TextView" android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/textView4" android:layout_below="@id/racuni_pregled_vmesnacrta"></TextView>

  </RelativeLayout>
</LinearLayout>

также добавьте файл dbhelper.java, если кто-то хочет проверить:

public class DbHelper extends SQLiteOpenHelper {

    public static final String dbName = "myWallet.db";
    public static final String racuniTable = "Racuni";
    public static final String colID = "_id";
    public static final String colName = "Ime";
    public static final String colValue = "Stanje";
    public static final String colAccType = "Tip_racuna";

    public static final String transakcijeTable = "Transakcije";
    public static final String colTransID = "_id";
    public static final String colTransDate = "Datum";
    public static final String colTransCategory = "Kategorija";
    public static final String colAmount = "Znesek";
    public static final String colIDracuni = "id_racuna";

    public DbHelper(Context context) {
        super(context, dbName, null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //executes only once
        //create tables
        Log.v("TAG", "creating table:" +racuniTable);
        String sql = "create table " +racuniTable+" (" +colID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " 
        +colName+ " TEXT, " +colValue+ " REAL, " +colAccType+ " TEXT);";

        Log.v("TAG", "creating table:" +transakcijeTable);
        String sql1 = "create table " +transakcijeTable+" (" +colTransID+ " INTEGER, " 
        +colTransDate+ " TEXT, " +colTransCategory+ " TEXT, " +colAmount+ " REAL, " 
        +colIDracuni+ " INTEGER NOT NULL ,FOREIGN KEY (" +colIDracuni+ ") REFERENCES " +racuniTable+ "(" +colID+ "));";

        Log.v("TAG", "adding account:");

        db.execSQL(sql);
        db.execSQL(sql1);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.v("TAG", "dropping table: "+ racuniTable);
        db.execSQL("DROPTABLE IF EXISTS " +racuniTable);
        Log.v("TAG", "dropping table: "+ transakcijeTable);
        db.execSQL("DROPTABLE IF EXISTS " +transakcijeTable);

        this.onCreate(db);
    }

} 

Можете ли вы помочь мне, пожалуйста? Как я могу создать одну строку списка? Я нашел несколько учебных пособий, но не смог помочь с ними.

1 Ответ

0 голосов
/ 20 сентября 2011

Вы получаете Force close Errors?

Вы видите вид?

setContentView(R.layout.racuni_pregled);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...