如何通过单击按钮从sqlite数据库中检索数据并在列表视图中显示

时间:2015-12-27 17:12:44

标签: android sqlite listview

我实际上很困惑,而不是寻找任何新的东西来添加或纠正它让我困惑,现在我不知道要添加什么也不正确

我想从sqlite数据库中检索数据,点击按钮SEARCH TRIP然后我希望它显示在列表视图中,通过该列表视图我也可以点击其中一个列表视图并单击它以指示我显示另一个页面信息,但我仍然怀疑

在我的logcat中,运行时没有错误,当我点击按钮SEARCH TRIP没有任何反应没有错误我有这些类:DATABASEHELPER,LISTVIEWCURSORADAPTERACTIVITY,TRIPSDBADAPTER

按钮位于片段中,因为当我指定其中一个类(如LISTVIEWCURSORADAPTERACTIVITY或TRIPSDBADAPTER)时,当我在方法上实现View.onclicklistener时,其中一个按钮位于片段上显示错误我应该在哪里放置按钮的连接

如果可能的话,有人可以帮我解决一下我做错的代码吗?

DatabaseHelper.java

import android.content.Contect;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {


public static final String DATABASE_NAME = "stallion_db";
public static final String TABLE_NAME = "one-way";
public static final String COL_1 = "depart from";
public static final String COL_2 = "arrive_to";
public static final String COL_3 = "report_time";
public static final String COL_4 = "depart_on";
public static final String COL_5 = "departure time";
public static final String COL_6 = "price";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME + "" + " (NO INTEGER PRIMARY KEY AUTOINCREMENT," +
            " depart_from TEXT, arrive_to TEXT, report_time VARCHAR, depart_on DATE, departure_time VARCHAR," +
            " price INTEGER); ");
    db.execSQL("INSERT INTO oneway values (1, mombasa, nairobi, 10:30AM, 25-12-2015, 11:00AM, 900)");
db.execSQL("SELECT FROM oneway WHERE depart_from = mombasa and arrive_to = nairobi");
}       


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Getting All Contacts
public List<ConstructorOneWay> getAlltrips() {
    List<ConstructorOneWay> tripList = new ArrayList<ConstructorOneWay>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;



    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            ConstructorOneWay trip = new ConstructorOneWay();
            trip.setID(Integer.parseInt(cursor.getString(0)));
            trip.setDepart(cursor.getString(1));
            trip.setArrive(cursor.getString(2));
            trip.setReport(cursor.getString(3));
            trip.setdeparting(cursor.getString(4));
            trip.setprice(Integer.parseInt(cursor.getString(5)));
            // Adding trips to list
            tripList.add(trip);
        } while (cursor.moveToNext());
    }

    // return contact list
    return tripList;
}



}

ListViewCursorAdapterActivity.java

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ListViewCursorAdaptorActivity extends Activity {
private TripsdbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;  

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

    dbHelper = new TripsdbAdapter(this);
    dbHelper.open();

    //Generate ListView from SQLite Database
    displayListView();
}

private void displayListView() {
    Cursor cursor = dbHelper.fetchallTrips();

    // The desired columns to be bound
    String[] columns = new String[] {
            TripsdbAdapter.Depart_from,
            TripsdbAdapter.Arrive_to,
            TripsdbAdapter.Depart_on,
            TripsdbAdapter.Departure_time,
            TripsdbAdapter.Price,
    };

    // the XML defined views which the data will be bound to
    int[] to = new int[] {
            R.id.tv1,
            R.id.tv2,
            R.id.tv3,
            R.id.tv4,
            R.id.tv5,

    };

    // create the adapter using the cursor pointing to the desired data
    //as well as the layout information
    dataAdapter = new SimpleCursorAdapter(
            this, R.layout.display_one_way_trip,
            cursor,
            columns,
            to,
            0);

    ListView listView = (ListView) findViewById(R.id.listView1);
    // Assign adapter to ListView
    listView.setAdapter(dataAdapter);


    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> listView, View view,
                                int position, long id) {
            // Get the cursor, positioned to the corresponding row in the result set
            Cursor cursor = (Cursor) listView.getItemAtPosition(position);
        }
    }); }}

TripsdbAdapter.java

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TripsdbAdapter {



//FOR DISPLAYING AFTER SEARCH

public static final String ID = "id";
public static final String Depart_from = "Depart from";
public static final String Arrive_to = "Arrive to";
public static final String Depart_on = "Depart on";
public static final String Departure_time = "Departure time";
public static final String Price = "Price";

private static final String TAG = "TripsdbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "stallion_db";
private static final String SQLITE_TABLE = "oneway";
private static final int DATABASE_VERSION = 1;

private Context mCtx;

public TripsdbAdapter(Context mContext) {
    this.mCtx = mContext;
}


public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
}

public Cursor fetchCountriesByName(String inputText) throws SQLException {
    Log.w(TAG, inputText);
    Cursor mCursor = null;
    if (inputText == null  ||  inputText.length () == 0)  {
        mCursor = mDb.query(SQLITE_TABLE, new String[] {Depart_from,
                        Arrive_to, Depart_on, Departure_time, Price},
                null, null, null, null, null);
    }
    else {
        mCursor = mDb.query(true, SQLITE_TABLE, new String[] {Depart_from,
                         Arrive_to, Depart_on, Departure_time, Price},
                Depart_from + " like '%" + inputText + "%'", null,
                null, null, null, null);
    }
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

public Cursor fetchallTrips() {

    Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {Depart_from,
                    Arrive_to, Depart_on, Departure_time, Price},
            null, null, null, null, null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}


public void open() {
} }

logcat的:

enter image description here

1 个答案:

答案 0 :(得分:0)

主要活动

public class MainActivity extends AppCompatActivity {

    private TripsdbAdapter dbHelper;
    private SimpleCursorAdapter dataAdapter;
    private Button btnGetList;
    private ListView listView;

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

        dbHelper = new TripsdbAdapter(this);
        dbHelper.open();

        listView = (ListView) findViewById(R.id.listView1);
        btnGetList = (Button) findViewById(R.id.btnGetList);
        btnGetList.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                displayListView();
            }
        });
    }

private void displayListView() {
        Cursor cursor = dbHelper.fetchallTrips();

        // The desired columns to be bound
        String[] columns = new String[] {TripsdbAdapter.ID ,TripsdbAdapter.Depart_from, TripsdbAdapter.Arrive_to, TripsdbAdapter.Depart_on, TripsdbAdapter.Departure_time, TripsdbAdapter.Price, };

        // the XML defined views which the data will be bound to
        int[] to = new int[] { R.id.tv1, R.id.tv2, R.id.tv3, R.id.tv4, R.id.tv5,R.id.tv6

        };

        // create the adapter using the cursor pointing to the desired data
        // as well as the layout information
        dataAdapter = new SimpleCursorAdapter(this, R.layout.display_one_way_trip, cursor, columns, to, 0);

        // Assign adapter to ListView
        listView.setAdapter(dataAdapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
                // Get the cursor, positioned to the corresponding row in the
                // result set
                Cursor cursor = (Cursor) listView.getItemAtPosition(position);
            }
        });
    }

public class TripsdbAdapter {

        // FOR DISPLAYING AFTER SEARCH

        public static final String ID = "_id";
        public static final String Depart_from = "depart_from";
        public static final String Arrive_to = "arrive_to";
        public static final String Depart_on = "depart_on";
        public static final String Departure_time = "departure_time";
        public static final String Price = "price";

        private static final String TAG = "TripsdbAdapter";
        private DatabaseHelper mDbHelper;
        private SQLiteDatabase mDb;

        private static final String DATABASE_NAME = "stallion_db";
        private static final String SQLITE_TABLE = "oneway";
        private static final int DATABASE_VERSION = 1;

        private Context mCtx;

        public TripsdbAdapter(Context mContext) {
            this.mCtx = mContext;
            mDbHelper = new DatabaseHelper(mContext);
        }

        public void close() {
            if (mDbHelper != null) {
                mDbHelper.close();
            }
        }

        public Cursor fetchCountriesByName(String inputText) throws SQLException {
            Log.w(TAG, inputText);
            Cursor mCursor = null;
            if (inputText == null || inputText.length() == 0) {
                mCursor = mDb.query(SQLITE_TABLE, new String[] { Depart_from, Arrive_to, Depart_on, Departure_time, Price }, null, null, null, null, null);
            } else {
                mCursor = mDb.query(true, SQLITE_TABLE, new String[] { Depart_from, Arrive_to, Depart_on, Departure_time, Price }, Depart_from + " like '%" + inputText + "%'",
                        null, null, null, null, null);
            }
            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;

        }

        public Cursor fetchallTrips() {

            Cursor mCursor = mDb.query(SQLITE_TABLE, new String[]  {ID,Depart_from, Arrive_to, Depart_on, Departure_time, Price }, null, null, null, null, null);

            if (mCursor != null) {
                mCursor.moveToFirst();
            }
            return mCursor;
        }

        public void open() {
            mDb = mDbHelper.getReadableDatabase();
        }
    }
}

DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "stallion_db";
    public static final String TABLE_NAME = "oneway";
    public static final String COL_1 = "depart_from";
    public static final String COL_2 = "arrive_to";
    public static final String COL_3 = "report_time";
    public static final String COL_4 = "depart_on";
    public static final String COL_5 = "departure_time";
    public static final String COL_6 = "price";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "" + " (NO INTEGER PRIMARY KEY AUTOINCREMENT,"
                + " depart_from TEXT, arrive_to TEXT, report_time VARCHAR, depart_on DATE, departure_time VARCHAR," + " price INTEGER); ");

        db.execSQL("INSERT INTO oneway values (1, 'mombasa', 'nairobi', '10:30AM', '25-12-2015', '11:00AM', 900)");
        db.execSQL("INSERT INTO oneway values (2, 'abcd', 'nairobi', '10:30AM', '26-12-2015', '10:00AM', 800)");
        db.execSQL("INSERT INTO oneway values (3, 'pqrs', 'nairobi', '10:30AM', '27-12-2015', '09:00AM', 700)");
        // db.execSQL("SELECT FROM oneway WHERE depart_from = mombasa and arrive_to = nairobi");
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Getting All Contacts
    public List<ConstructorOneWay> getAlltrips() {
        List<ConstructorOneWay> tripList = new ArrayList<ConstructorOneWay>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ConstructorOneWay trip = new ConstructorOneWay();
                trip.setID(Integer.parseInt(cursor.getString(0)));
                trip.setDepart(cursor.getString(1));
                trip.setArrive(cursor.getString(2));
                trip.setReport(cursor.getString(3));
                trip.setDeparting(cursor.getString(4));
                trip.setPrice(Integer.parseInt(cursor.getString(5)));
                // Adding trips to list
                tripList.add(trip);
            } while (cursor.moveToNext());
        }

        // return contact list
        return tripList;
    }

}

activity_main.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" >

    <Button
        android:id="@+id/btnGetList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get All" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnGetList" >
    </ListView>

</RelativeLayout>