Question

I can't understand why I doesen't get any data out of the database. I have to admit that I am confues about listviews, textviews and adapters. The database contains a person and a gift. That should be poured into a textview. Somehow it seems that I have to make a listview, but.... I am confused. I have read a lot, and worked hard, but I have no idea. I would appreciate it if anyone could help me :-)

The only thing that happens is that na empty list is appearing.

Here is the code:

Main Activity.java:

package com.example.julegaveliste2;



import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends ListActivity {
    DatabaseHelper db;
    Button knapp1;
    Button knapp2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final DatabaseHelper db = new DatabaseHelper(MainActivity.this);

        knapp1 = (Button) findViewById(R.id.Legg_Til);
        knapp2 = (Button) findViewById(R.id.Les_database);

        knapp2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
            visliste(db.getWritableDatabase());
            }
        });


       knapp1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                LagTabell(db.getWritableDatabase());

            }
        }); 

    }

    public static void LagTabell(SQLiteDatabase db)
    {
        ContentValues jul = new ContentValues();
        jul.put("person", "Ida");
        jul.put("gave", "blomst");
        db.insert("julegaveliste2", "person", jul); 
    }

    public void visliste(SQLiteDatabase db)
    {   
        Cursor cursor=db.rawQuery("SELECT _id, person, gave FROM julegaveliste2", null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.activity_list_item, cursor, new String[]{"person","gave"}, new int[]{R.id.person,R.id.gave},0);

        ListView listView = (ListView) findViewById(R.id.listView1);
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }


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

}

DatabaseHelper.java:

package com.example.julegaveliste2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME="julegaveliste2.db";
    private static final int SCHEMA=1;

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, SCHEMA);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE julegaveliste2 (_id INTEGER PRIMARY KEY AUTOINCREMENT, person TEXT NOT NULL, gave TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        throw new RuntimeException("How did we get here?");
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView    
        android:id="@+id/person"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/gave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/Legg_Til"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="15dp"
        android:layout_marginRight="17dp"
        android:text="@string/opprett_database" />

    <Button
        android:id="@+id/Les_database"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/Legg_Til"
        android:layout_alignBottom="@+id/Legg_Til"
        android:layout_toRightOf="@+id/person"
        android:text="@string/les_database" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_above="@+id/Legg_Til"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="42dp" >
    </ListView>

    <ListView
        android1:id="@+id/listView1"
        android1:layout_width="match_parent"
        android1:layout_height="100dp" >

    </ListView>

</RelativeLayout>
Was it helpful?

Solution

You should try to replace your SimpleCursorAdapter with an ArrayAdapter. To do this we would need a few modifications to your code. We need a new class in your application, which I will call PresentItem, an ArrayAdapter for your list, an XML layout for each row in the list, and a method for converting SQLite rows to PresentItems. First out is the new model, PresentItem:

public class PresentItem  {
    private String name, present;
    private int id;

    public PresentItem(int id, String name, String present) {
         // Init 
    }

    // Getters, setters, etc.

}

So, when we now read from your database, we can convert each rows we get from our query to new PresentItems:

public List<PresentItem> getPresentItems(SQLiteDatabase db) {
    Cursor cursor = db.query("julegaveliste2", 
      new String[] {"_id", "person", "gave"}, null, null, null, null, null);

    List<PresentItem> result = new ArrayList<PresentItem>();
    PresentItem item;

    if (cursor != null && cursor.moveToFirst()) {
        int index = cursor.getColumnIndex("_id");
        int id = cursor.getInt(index));

        index = cursor.getColumnIndex("name");
        String name = cursor.getString(index));

        index = cursor.getColumnIndex("present");
        String present = cursor.getString(index);

        item = new PresentItem(id, name, present);
        result.add(item);
    }
    return result;
}

Once we have the PresentItems parsed from the database, we need a way to display them. To display the PresentItems in your app, we need our own ArrayAdapter, which would look something like this:

public class PresentListAdapter extends ArrayAdapter<PresentItem> {
  private Context ctx;
  private List<PresentItem> presentItems;
  public PresentListAdapter(Context ctx, int layoutResourceId, List<PresentItem> presentItems) { 
    super(context, layoutResourceId, presentItems);
    this.ctx = ctx;
    this.presentItems = presentItems;
}

  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
      convertView = inflater.inflate(mLayoutResourceId, parent, false);
    }
  PresentItem item = presentItems.get(position);
  ((TextView) convertView.findViewById(R.id.row_id)).setText("" + item.getId());
  ((TextView) convertView.findViewById(R.id.name)).setText(item.getName());
  ((TextView) convertView.findViewById(R.id.present)).setText(item.getPresent());
  return convertView;
}

To use the adapter in your app, do something like this:

public void visListe(SQLiteDatabase db){   
  List<PresentItem> items = getPresentItems(db);
  PresentItemAdapter adapter = new PresentItemAdapter(this, R.layout.presentListItem, items);
  ListView listView = (ListView) findViewById(R.id.listView1);
  listView.setAdapter(adapter);
  listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

And, as you might notice, our adapter uses presentListItem as its layout, which we define in res/layout/presentListItem.xml as:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <TextView android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/row_id"
            />
    <TextView android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/name"
            />    
     <TextView android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/present"
            />
</LinearLayout>

I hope I made it clear and beware bugs in the code - I wrote most of it from memory with a few quick Google searches to help me :) Ask if you need anymore help ^^

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top