Bret
Bret

Reputation: 3

Android, How can I fill data from SQL DB to custom array adapter?

I'm trying to get the data to load into mArrayAdapter. Is this at all possible?

I want the list to look just like the other lists in other activities.

-------------------------------
Startpage.java,
-------------------------------
package com.example.sqltest;
import android.app.ListActivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class Startpage extends ListActivity {
    final Context context = this;
    String[] startpage;
    private SQLiteAdapter mySQLiteAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startpage = new String[]{SQLiteAdapter.KEY_CONTENT}; //  <--- This returns the word"content" 


        //startpage = getResources().getStringArray(R.array.startpage);  <---- How do I load SQL DATA to here?


        setListAdapter(new mArrayAdapter(this, startpage));
        mySQLiteAdapter = new SQLiteAdapter(this);
        mySQLiteAdapter.openToWrite();
        mySQLiteAdapter.deleteAll();
        mySQLiteAdapter.insert("this");
        mySQLiteAdapter.insert("that");
        mySQLiteAdapter.insert("where");
        mySQLiteAdapter.close();
        getListView().setOnItemClickListener(

        new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                switch (position) {
                case 0:
                    Intent int1 = new Intent(view.getContext(),
                            AndroidSQLite.class);
                    startActivity(int1);

                    break;
                case 1:
                    Intent int2 = new Intent(view.getContext(),
                            AndroidSQLite.class);
                    startActivity(int2);

                    break;
                case 2:
                    Intent int3 = new Intent(view.getContext(),
                            AndroidSQLite.class);
                    startActivity(int3 );

                    break;
                case 3:
                    Intent int4 = new Intent(view.getContext(),
                            AndroidSQLite.class);
                    startActivity(int4 );

                    break;

                }

            }
        });

    }

    public class mArrayAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;

        public mArrayAdapter(Context context, String[] values) {
            super(context, R.layout.startpage, values);
            this.context = context;
            this.values = values;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(R.layout.startpage, parent, false);
            TextView textView = (TextView) rowView.findViewById(R.id.startpage);
            ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);

            ListView list = getListView();

            list.setOnItemLongClickListener(new OnItemLongClickListener() {

                @Override
                public boolean onItemLongClick(AdapterView<?> parent,
                        View view, int position, long id) {                 

                    String s = values[position];

                    System.out.println(s);

                    if (s.equals("this")) {                     
                        Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();
                    } else if (s.equals("that")) {
                        Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();;
                    } else if (s.equals("where")) {
                        Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();
                    }               
                    return true;
                }
            });         

            textView.setText(values[position]);         
            Context context1 = context;
            AssetManager assetManager = context1.getResources().getAssets();
            Typeface typeface = Typeface.createFromAsset(assetManager, (getString(R.string.font1))); 
            textView.setTextColor(Color.YELLOW);
            textView.setTypeface(typeface);     
            String s = values[position];

            System.out.println(s);

            if (s.equals("this")) {
                imageView.setImageResource(R.drawable.ic_launcher);
            } else if (s.equals("that")) {
                imageView.setImageResource(R.drawable.ic_launcher);
            } else if (s.equals("where")) {
                imageView.setImageResource(R.drawable.ic_launcher);
            } else {
                imageView.setImageResource(R.drawable.ic_launcher);
            }

            return rowView;
        }
    }   
}
-------------------------------
SQLiteAdapter.java
-------------------------------
package com.example.sqltest;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class SQLiteAdapter {

    public static final String MYDATABASE_NAME = "MY_DATABASE";
    public static final String MYDATABASE_TABLE = "MY_TABLE";
    public static final int MYDATABASE_VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String KEY_CONTENT = "Content";

    //create table MY_DATABASE (ID integer primary key, Content text not null);
    private static final String SCRIPT_CREATE_DATABASE =
        "create table " + MYDATABASE_TABLE + " ("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_CONTENT + " text not null);";

    private SQLiteHelper sqLiteHelper;
    private SQLiteDatabase sqLiteDatabase;

    private Context context;

    public SQLiteAdapter(Context c){
        context = c;
    }

    public SQLiteAdapter openToRead() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getReadableDatabase();
        return this;    
    }

    public SQLiteAdapter openToWrite() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getWritableDatabase();
        return this;    
    }

    public void close(){
        sqLiteHelper.close();
    }

    public long insert(String content){

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_CONTENT, content);
        return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
    }

    public int deleteAll(){
        return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
    }

    public Cursor queueAll(){
        String[] columns = new String[]{KEY_ID, KEY_CONTENT};
        Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, 
                null, null, null, null, null);

        return cursor;
    }

    public class SQLiteHelper extends SQLiteOpenHelper {

        public SQLiteHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(SCRIPT_CREATE_DATABASE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

        }

    }

}
----------------------------------
startpage.xml   layout
----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom|left"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/logo"
        android:layout_width="50sp"
        android:layout_height="50sp"
        android:layout_marginLeft="5sp"
        android:layout_marginRight="20sp"
        android:layout_marginTop="5sp" /> 

    <TextView
        android:id="@+id/startpage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="bottom|left"
        android:text="@+id/label"
        android:textSize="27sp" />
</LinearLayout>
----------------------------------
main.xml layout
----------------------------------
<?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"
    >
<ListView
    android:id="@+id/contentlist"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
</LinearLayout>
----------------------------------
row.xml  layout
----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"/>

The code is based on a tutorial.

Upvotes: 0

Views: 2678

Answers (1)

Karakuri
Karakuri

Reputation: 38595

You haven't updated the data source for the adapter after calling setListAdapter(new mArrayAdapter(this, startpage));. All the mySQLiteAdapter.<foo> code just modifies the data in your database, you never actually retrieve it again and swap it into your adapter. All you have is a String array with one item, whose values is "content".

Add a method in your mArrayAdapter class:

public void setData(String[] newData) {
    values = newData;
    notifyDataSetChanged(); // tells the adapter the data has been updated
}

Although, you could use a CursorAdapter and use the Cursor you get from querying the database to populate the list. You can look at the ApiDemos sample project in the sdk to see how to use CursorAdapter.

Upvotes: 1

Related Questions