简体   繁体   English

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

[英]How to retrieve data from sqlite database by clicking button and display in a listview

I'm actually confused instead of looking for any new thing to add or correct it confused me and now I don't know what to add nor correct 我实际上很困惑,而不是寻找要添加或纠正的任何新事物,这让我感到困惑,现在我不知道要添加或纠正什么

I want to retrieve data from the sqlite database from clicking the button SEARCH TRIP then I want it to display in a listview by which I would also be able to click one of the listview and click it to direct me to another page displaying the info, but I'm still having doubts in that 我想通过单击SEARCH TRIP按钮从sqlite数据库中检索数据,然后希望它显示在列表视图中,通过该列表视图,我也可以单击其中一个列表视图,然后单击它将我定向到另一个显示该信息的页面,但我对此仍然有疑问

in my logcat, there are no errors upon running and when I click the button SEARCH TRIP nothing happens there is no error I'm having these classes: DATABASEHELPER, LISTVIEWCURSORADAPTERACTIVITY, TRIPSDBADAPTER 在我的logcat中,运行时没有错误,当我单击SEARCH TRIP按钮时,没有任何反应,没有错误,我有以下这些类:DATABASEHELPER,LISTVIEWCURSORADAPTERACTIVITY,TRIPSDBADAPTER

The button is in the fragment since I'm having tabs in one of them the button is situated on the fragment when I implement the View.onclicklistener the on the method when I specify one of the classes such as LISTVIEWCURSORADAPTERACTIVITY or TRIPSDBADAPTER its showing error where should I put the connection of the button 按钮在片段中,因为我在其中一个中使用了选项卡,当我实现View.onclicklistener时,按钮位于片段中,当我指定诸如LISTVIEWCURSORADAPTERACTIVITY或TRIPSDBADAPTER之类的类之一时,其显示错误我应该把按钮的连接

If possible, can anyone please help me with the code what have I done wrong? 如果可能,任何人都可以通过代码帮助我,我做错了什么?

DatabaseHelper.java 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 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 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: logcat的:

enter image description here 在此处输入图片说明

Main Activity 主要活动

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 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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不单击我的案例的按钮的情况下使用SQLite的ListView显示列表数据? - How to Display List Data with ListView from SQLite without by clicking button on my case? 如何在Android中的SQLite数据库中以ListView显示数据 - How to display data in listview from sqlite database in android 如何从MySQL数据库中检索特定的用户数据并在listview中显示? - How to retrieve particular user data from MySQL database and display in listview? 如何从Android中的sqlite数据库检索数据并在TextView中显示 - How to retrieve data from sqlite database in android and display it in TextView Android Studio,如何从Sqlite数据库中检索数据并将其显示到textview中? - Android Studio, how to retrieve data from Sqlite database and display it into textview? 从现有的SQLite数据库显示数据到Listview - Display Data From Existing SQLite Database To Listview 在列表视图中显示sqlite数据库中的数据 - Display data from sqlite database in a listview 无法从数据库检索数据并在列表视图中显示 - Cannot retrieve data from database and display in listview 单击按钮时如何从sqlite数据库中检索数据 - How to retrieve the data from sqlite database on button click 通过单击删除按钮使用列表视图从SQLite删除数据 - Deleting data from SQLite using listview by clicking Delete Button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM