如何从Android中的SQLite获取记录

时间:2013-05-13 17:07:52

标签: android android-listview android-sqlite

我不擅长Android,学习东西。我正试图从Android中的SQLite中获取记录。这是我的代码。请帮助我的错在哪里。感谢。

    //DatabaseAdapter.java// 

    package com.example.wg_an;
    import java.util.ArrayList;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;

    public class DatabaseAdapter {
        SQLiteDatabase database;
        DatabaseOpenHelper dbHelper;

        public DatabaseAdapter(Context context) {
            dbHelper = new DatabaseOpenHelper(context);

        }

        public void open() {
            database = dbHelper.getWritableDatabase();
        }

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

        public long insertTest(String no, String name) {
            ContentValues values = new ContentValues();
            values.put("no", no);
            values.put("name", name);

            return database.insert("test", null, values);
        }

        public ArrayList<String> getAllLabels() {

            Cursor mcursor = database.rawQuery("SELECT name FROM "
                    + DatabaseOpenHelper.TABLE_NAME, null);

            ArrayList<String> result = new ArrayList<String>();

            do {
                result.add(mcursor.getString(mcursor.getColumnIndex("name")));
            } while (mcursor.moveToNext());

            return result;
        }

    }



    //MainActivity2.java//

    package com.example.wg_an;

    import java.util.ArrayList;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.Toast;

    public class MainActivity2 extends Activity implements OnClickListener {
        EditText etno, etname;
        Button btnSave;
        DatabaseAdapter dbAdapter;

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);

            dbAdapter = new DatabaseAdapter(getApplicationContext());

            etno = (EditText) findViewById(R.id.txtNo);
            etname = (EditText) findViewById(R.id.txtName);
            btnSave = (Button) findViewById(R.id.Save);
            btnSave.setOnClickListener(this);

            Button back = (Button) findViewById(R.id.buttonBackPg);
            back.setOnClickListener(this);

            Button view_list = (Button) findViewById(R.id.view_list);
            view_list.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.buttonBackPg) {
                startActivity(new Intent(getApplicationContext(),
                        MainActivity.class));
            }

            if (v.getId() == R.id.view_list) {

                ListView listview = (ListView) findViewById(R.id.list_all);
                ArrayList<String> data = dbAdapter.getAllLabels();
                dbAdapter.close();
                listview.setAdapter(new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_1, data));

            }

            if (v.getId() == R.id.Save) {

                String no = etno.getText().toString();
                String name = etname.getText().toString();
                dbAdapter.open();
                long inserted = dbAdapter.insertTest(no, name);

                if (inserted >= 0) {
                    Toast.makeText(getApplicationContext(), "data saved",
                            Toast.LENGTH_LONG).show();

                    etno.setText("");
                    etname.setText("");

                } else {
                    Toast.makeText(getApplicationContext(), "data not saved",
                            Toast.LENGTH_LONG).show();
                }
                dbAdapter.close();
            }
        }
    }



    //activity_main2.xml//

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity2" >

        <EditText
            android:id="@+id/txtNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView1"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="19dp"
            android:ems="10"
            android:hint="No"
            android:inputType="text" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/buttonBackPg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/Save"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="77dp"
            android:text="Back" />

        <Button
            android:id="@+id/Save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/buttonBackPg"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="32dp"
            android:onClick="onClick"
            android:text="Save" />

        <EditText
            android:id="@+id/txtName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/textView1"
            android:layout_below="@+id/txtNo"
            android:layout_marginTop="36dp"
            android:ems="10"
            android:hint="Name"
            android:inputType="text">

        </EditText>

        <Button
            android:id="@+id/view_list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/txtName"
            android:layout_below="@+id/Save"
            android:text="View List" />

        <ListView
            android:id="@+id/list_all"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/msg"
            android:layout_alignLeft="@+id/msg" >
        </ListView>

    </RelativeLayout>

3 个答案:

答案 0 :(得分:1)

尝试此修改

public ArrayList<String> getAllLabels() {

    Cursor mcursor = database.rawQuery("SELECT name FROM "
        + DatabaseOpenHelper.TABLE_NAME, null);

    ArrayList<String> result = new ArrayList<String>();

    if(mcursor!=null)
    {

        //move cursor to first result record
        mcursor.moveToFirst();

        do {
            result.add(mcursor.getString(mcursor.getColumnIndex("name")));
        } while (mcursor.moveToNext());
    }
    return result;
}

答案 1 :(得分:0)

for fetch data use like that



 public Cursor getdata()

            {
                Log.v(TAG + ".getdata", "getdatamethod called");
                Cursor mCursor = null;
                openAsWrite();

                mCursor=db.query(tablenam,
                        new String[] {"column name"},null, null, null, null,    null);


                return mCursor;

            }

答案 2 :(得分:0)

Final Working Code is here --


//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseAdapter {
    SQLiteDatabase database;
    DatabaseOpenHelper dbHelper;

    public DatabaseAdapter(Context context) {
        dbHelper = new DatabaseOpenHelper(context);

    }

    public void open() {
        database = dbHelper.getWritableDatabase();
    }

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

    public long insertTest(String no, String name) {
        ContentValues values = new ContentValues();
        values.put("no", no);
        values.put("name", name);

        return database.insert("test", null, values);
    }

    public ArrayList<String> getAllLabels() {

        Cursor mcursor = database.rawQuery("SELECT * FROM "
            + DatabaseOpenHelper.TABLE_NAME, null);

        ArrayList<String> result = new ArrayList<String>();

        if(mcursor!=null)
        {

            //move cursor to first result record
            mcursor.moveToFirst();

            do {
                String display = mcursor.getString(mcursor.getColumnIndex("name")) + " - " + mcursor.getString(mcursor.getColumnIndex("no"));  
                result.add(display);
            } while (mcursor.moveToNext());
        }
        return result;
    }
}


//MainActivity2.java //
package com.example.wg_an;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity2 extends Activity implements OnClickListener {
    EditText etno, etname;
    Button btnSave;
    DatabaseAdapter dbAdapter;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        dbAdapter = new DatabaseAdapter(getApplicationContext());

        etno = (EditText) findViewById(R.id.txtNo);
        etname = (EditText) findViewById(R.id.txtName);
        btnSave = (Button) findViewById(R.id.Save);
        btnSave.setOnClickListener(this);

        Button back = (Button) findViewById(R.id.buttonBackPg);
        back.setOnClickListener(this);

        Button view_list = (Button) findViewById(R.id.view_list);
        view_list.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.buttonBackPg) {
            startActivity(new Intent(getApplicationContext(),
                    MainActivity.class));
        }

        if (v.getId() == R.id.view_list) {

            startActivity(new Intent(getApplicationContext(),
                    MainActivity3.class));
        }

        if (v.getId() == R.id.Save) {

            String no = etno.getText().toString();
            String name = etname.getText().toString();
            dbAdapter.open();
            long inserted = dbAdapter.insertTest(no, name);

            if (inserted >= 0) {
                Toast.makeText(getApplicationContext(), "data saved",
                        Toast.LENGTH_LONG).show();

                etno.setText("");
                etname.setText("");

            } else {
                Toast.makeText(getApplicationContext(), "data not saved",
                        Toast.LENGTH_LONG).show();
            }
            dbAdapter.close();
        }
    }
}


//MainActivity3.java//
package com.example.wg_an;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity3 extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    DatabaseAdapter dbAdapter;
    ListView listview;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        dbAdapter = new DatabaseAdapter(this);
        dbAdapter.open();
        try {
            Button back = (Button) findViewById(R.id.back_2);
            back.setOnClickListener(this);

            listview = (ListView) findViewById(R.id.list_all);
            Log.d("Reading: ", "Reading MA3..");
            ArrayList<String> data = dbAdapter.getAllLabels();

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, data);
            listview.setAdapter(adapter);

            dbAdapter.close();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.back_2) {
            startActivity(new Intent(getApplicationContext(),
                    MainActivity2.class));
        }

    }
}


//DatabaseOpenHelper.java//
package com.example.wg_an;

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


public class DatabaseOpenHelper extends SQLiteOpenHelper {


public static final String DBName = "test_database.db";
public static final String TABLE_NAME = "test";
public static final String TABLE_SQL = "Create Table "+ TABLE_NAME 
+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"no TEXT, "
+"name TEXT);";

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


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


@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub


}


}


//activity_main2.xml//
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity2" >

    <Button
        android:id="@+id/buttonBackPg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Save"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="77dp"
        android:text="Back Screen-1" />

    <Button
        android:id="@+id/Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonBackPg"
        android:layout_alignLeft="@+id/txtName"
        android:onClick="onClick"
        android:text="Save" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="21dp"
        android:text="Add Records - Screen-2" />

    <EditText
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/Save"
        android:layout_alignLeft="@+id/txtNo"
        android:layout_marginBottom="58dp"
        android:ems="10"
        android:hint="Name"
        android:inputType="text" />

    <EditText
        android:id="@+id/txtNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="No"
        android:inputType="text" />

    <Button
        android:id="@+id/view_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/txtName"
        android:layout_below="@+id/txtName"
        android:text="View List" />

</RelativeLayout>



//activity_main3.xml//

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity3" >

    <Button
        android:id="@+id/back_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="17dp"
        android:text="Back Screen-2" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        android:text="List of Records - Screen-3" />

    <ListView
        android:id="@+id/list_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="58dp"
        android:layout_marginTop="58dp"
        android:layout_below="@+id/textView3"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>