Java Android: sqlite-DB via simpleCurorAdapter an Gridview andocken - wo ist der Fehler

User7634

Cadet 4th Year
Registriert
Aug. 2012
Beiträge
109
Hallo,
seit Stunden versuche ich - als kleine Übung - eine sqLite-Datenbank über einen simpleCursorAdapter an Gridview anzudocken. Die App soll meine Badminton-Spiele erfassen und darstellen. Aber es scheitert schon ganz am Anfang. Die Alternative via ListView hat funktiniert, bei GridView hakt es. Das AVD zeigt mir nur ein leeres Layout (s. Anhang) Über google habe ich keine Lösung gefunden. Die Datenbank als solche wird korrekt erstellt, habe ich mit sqliteBrowser überprüft. Mein code ist auszugsweise wie folgt. Ich danke für jeden Hinweis.

Code:
MainActivity.java

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Intent matchList = new Intent(this, MatchGridViewActivity.class);
        startActivity(matchList);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

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

Code:
MatchGridViewActivity.java

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.GridView;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;

public class MatchGridViewActivity extends AppCompatActivity {

    private SQLiteDatabase db;
    private Cursor cursor;

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

        GridView gv = (GridView)findViewById(R.id.MatchGridView);

        try {
            SQLiteOpenHelper BadmintonDatabaseHelper = new BadmintonDatabaseHelper(this);
            db = BadmintonDatabaseHelper.getReadableDatabase();
            cursor = db.query("MATCH",
                    new String[]{"_id", "DATUM", "PLAYER1", "PLAYER2"},
                    null, null, null, null, null);

            SimpleCursorAdapter gvAdapter = new SimpleCursorAdapter(this,
                    android.R.layout.simple_list_item_1,
                    cursor,
                    new String[]{"DATUM", "PLAYER1", "PLAYER2"},
                    new int[]{android.R.id.text1, android.R.id.text1, android.R.id.text1},0);

            gv.setAdapter(gvAdapter);
            

        } catch (SQLiteException e) {
            Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
            toast.show();
        }

    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        cursor.close();
        db.close();
    }
}

Code:
BadmintonDatabaseHelper.java

class BadmintonDatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "badminton"; // database name 
    private static final int DB_VERSION = 1; // version database

    BadmintonDatabaseHelper(Context context){
        super(context, DB_NAME, null, DB_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        updateMyDatabase(db, 0, DB_VERSION);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        updateMyDatabase(db, oldVersion, newVersion);
    }

    private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 1) {
            db.execSQL("CREATE TABLE PLAYER (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + "NAME TEXT NOT NULL, "
                    + "DESCRIPTION TEXT, "
                    + "IMAGE_RESOURCE_ID INTEGER);");
            insertPlayer(db, "Peter", "Netter Typ");
            insertPlayer(db, "Paul", "Guter Spieler");
            insertPlayer(db, "Stefan", "Bruder");
            insertPlayer(db, "Theo", "Zuschauer");

            db.execSQL("CREATE TABLE MATCH (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + "DATUM TEXT NOT NULL, "
                    + "PLAYER1 INTEGER NOT NULL, "
                    + "PLAYER2 INTEGER NOT NULL, "
                    + "COMMENT TEXT, "
                    + "CAR INTEGER, "
                    + "SET1P1 INTEGER NOT NULL, "
                    + "SET1P2 INTEGER NOT NULL, "
                    + "SET2P1 INTEGER, "
                    + "SET2P2 INTEGER, "
                    + "SET3P1 INTEGER, "
                    + "SET3P2 INTEGER, "
                    + "ADDSETP1 INTEGER, "
                    + "ADDSETP2 INTEGER);");

            insertMatch(db, "2016-01-16", 1, 0, "Abbruch nach Verletzung Theo", 1, 22, 20, 6, 2);


        }
    }

    private void insertMatch(SQLiteDatabase db, String datum, int spieler1, int spieler2, String Kommentar, int Fahrer, int S1P1, int S1P2) {
        this.insertMatch(db, datum, spieler1, spieler2, Kommentar, Fahrer, S1P1, S1P2, 0, 0);
    }

    private void insertMatch(SQLiteDatabase db, String datum, int spieler1, int spieler2, String Kommentar, int Fahrer, int S1P1, int S1P2, int S2P1, int S2P2) {
        this.insertMatch(db, datum, spieler1, spieler2, Kommentar, Fahrer, S1P1, S1P2, S2P1, S2P2, 0, 0);
    }

    private void insertMatch(SQLiteDatabase db, String datum, int spieler1, int spieler2, String Kommentar, int Fahrer, int S1P1, int S1P2, int S2P1, int S2P2, int S3P1, int S3P2) {
        this.insertMatch(db, datum, spieler1, spieler2, Kommentar, Fahrer, S1P1, S1P2, S2P1, S2P2, S3P1, S3P2, 0, 0);
    }

    private void insertMatch(SQLiteDatabase db, String datum, int spieler1, int spieler2, String Kommentar, int Fahrer, int S1P1, int S1P2, int S2P1, int S2P2, int S3P1, int S3P2, int ASP1, int ASP2) {
        ContentValues MatchValues = new ContentValues();
        MatchValues.put("DATUM", datum);
        MatchValues.put("PLAYER1", spieler1);
        MatchValues.put("PLAYER2", spieler2);
        MatchValues.put("COMMENT", Kommentar);
        MatchValues.put("CAR", Fahrer);
        MatchValues.put("SET1P1", S1P1);
        MatchValues.put("SET1P2", S1P2);
        MatchValues.put("SET2P1", S2P1);
        MatchValues.put("SET2P2", S2P2);
        MatchValues.put("SET3P1", S3P1);
        MatchValues.put("SET3P2", S3P2);
        MatchValues.put("ADDSETP1", ASP1);
        MatchValues.put("ADDSETP2", ASP2);
        
        db.insert("MATCH", null, MatchValues);


    }

Code:
activity_match_grid_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.marc.badminton.MatchGridViewActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_match_grid_view" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Code:
content_match_grid_view.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/MatchGridView"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp">

</GridView>
 

Anhänge

  • AVD.png
    AVD.png
    143,3 KB · Aufrufe: 329
würde erstmal den code übersichtlicher gestalten. so ne get-abfrage direkt in die db klasse und nicht ins oncreate und dann den cursor mittels der get-methode abgreifen.

ich würde das nen bisschen abändern.

1. ich würde ein get methode in der db anlegen. diese liefert dir einen cursor zurück:

Code:
// Select All Data
	public Cursor SelectAllData() {
		// TODO Auto-generated method stub
		
		 try {
			 SQLiteDatabase db;
			 db = this.getReadableDatabase(); // Read Data
				
			 String strSQL = "..."; // entsprechend deiner DB
			 Cursor cursor = db.rawQuery(strSQL, null);
			 
			 return cursor;
				
		 } catch (Exception e) {
		    return null;
		 }

	}

2. dann in der gridviewactivity:


Code:
String[] cols = new String[]{"DATUM", "PLAYER1", "PLAYER2"};
int[] names = new int[]{android.R.id.text1};

final Cursor myData = myDb.SelectAllData();  
startManagingCursor(myData);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1 , myData ,cols,names);

http://www.thaicreate.com/mobile/android-sqlite-gridview.html

ist zwar ne thailändische seite, aber der code ist auf englisch kommentiert
 
Zurück
Oben