如何从数据库调用数据到我的活动

时间:2018-06-29 17:22:42

标签: android database sqlite listview android-activity

我是android的初学者,iam正在从事我的毕业设计,该项目在这里显示了埃及iam面临的所有问题在埃及的所有城市和地方

我希望活动看起来像这样layout

这是我的数据库适配器

    package com.example.android.spot.Db;


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

import com.example.android.spot.Models.City;
import com.example.android.spot.Models.Place;
import com.example.android.spot.Models.User;


import java.util.List;

public class SpotDbAdapter extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    static final String DATABASE_NAME = "Spot.db";
    private Context context;

    public SpotDbAdapter(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }



    @Override
    public void onCreate(SQLiteDatabase db) {

        final String SQL_CREATE_User_TABLE = "CREATE TABLE " + SpotContract.UserEntry.Table_Name + " (" +
                SpotContract.UserEntry.COLUMN_User_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                SpotContract.UserEntry.COLUMN_Name + " TEXT NOT NULL, " +
                SpotContract.UserEntry.COLUMN_password + " TEXT NOT NULL, " +
                SpotContract.UserEntry.COLUMN_Email + " TEXT NOT NULL, " +
                SpotContract.UserEntry.COLUMN_Image + " TEXT " +
                " );";



       final String SQL_CREATE_Cities_TABLE = "CREATE TABLE " + SpotContract.CitiesEntry.Table_Name + " (" +
                SpotContract.CitiesEntry.COLUMN_City_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"  +
                SpotContract.CitiesEntry.COLUMN_Name + " TEXT NOT NULL, " +
                SpotContract.CitiesEntry.COLUMN_Image + " TEXT " +
                " );";


        final String SQL_CREATE_Places_TABLE = "CREATE TABLE " + SpotContract.PlacesEntry.Table_Name + " (" +
                SpotContract.PlacesEntry.COLUMN_Place_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                SpotContract.PlacesEntry.COLUMN_Name + " TEXT NOT NULL, " +
                SpotContract.PlacesEntry.COLUMN_Image + " TEXT, " +
                SpotContract.PlacesEntry.COLUMN_Description + " TEXT, " +
                SpotContract.PlacesEntry.COLUMN_Address + " TEXT, " +
                SpotContract.PlacesEntry.COLUMN_Contact + " TEXT DEFAULT NULL, " +
                SpotContract.PlacesEntry.COLUMN_Category + " TEXT, " +
                SpotContract.PlacesEntry.COLUMN_city_name + " TEXT NOT NULL " +
                " );";
                /*" FOREIGN KEY (" + SpotContract.PlacesEntry.COLUMN_city_name + ") REFERENCES " +
                SpotContract.CitiesEntry.Table_Name + " (" + SpotContract.CitiesEntry.COLUMN_Name + ") " +*/




        db.execSQL(SQL_CREATE_User_TABLE);
        db.execSQL(SQL_CREATE_Cities_TABLE);
        db.execSQL(SQL_CREATE_Places_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + SpotContract.UserEntry.Table_Name);
        db.execSQL("DROP TABLE IF EXISTS " + SpotContract.PlacesEntry.Table_Name);
        db.execSQL("DROP TABLE IF EXISTS " + SpotContract.CitiesEntry.Table_Name);

        onCreate(db);



    }

    public User Authenticate(User user) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(SpotContract.UserEntry.Table_Name,// Selecting Table
                new String[]{SpotContract.UserEntry.COLUMN_User_ID, SpotContract.UserEntry.COLUMN_Name, SpotContract.UserEntry.COLUMN_Email, SpotContract.UserEntry.COLUMN_password},//Selecting columns want to query
                SpotContract.UserEntry.COLUMN_Email + "=?",
                new String[]{user.email},//Where clause
                null, null, null);

        if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
            //if cursor has value then in user database there is user associated with this given email
            User user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));

            //Match both passwords check they are same or not
            if (user.password.equalsIgnoreCase(user1.password)) {
                return user1;
            }
        }
        //if user password does not matches or there is no record with that email then return @false
        return null;
    }

    public boolean isEmailExists(String email) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(SpotContract.UserEntry.Table_Name,// Selecting Table
                new String[]{SpotContract.UserEntry.COLUMN_User_ID, SpotContract.UserEntry.COLUMN_Name, SpotContract.UserEntry.COLUMN_Email, SpotContract.UserEntry.COLUMN_password},//Selecting columns want to query
                SpotContract.UserEntry.COLUMN_Email + "=?",
                new String[]{email},//Where clause
                null, null, null);

        if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
            //if cursor has value then in user database there is user associated with this given email so return true
            return true;
        }

        //if email does not exist return false
        return false;
    }
    public Cursor selectAllCities(){
        SQLiteDatabase db = getWritableDatabase();
        Cursor mCursor = db.rawQuery("SELECT * FROM " + SpotContract.CitiesEntry.Table_Name,null);
        if (mCursor != null) {
            mCursor.moveToFirst();
            if (mCursor.moveToFirst()) {
                do {

                    Log.e("city",mCursor.getString(1)+mCursor.getString(2));

                } while (mCursor.moveToNext());

            }

        }
      return mCursor;

    }
    public Cursor selectPlaces(String category, String city){
         SQLiteDatabase db = this.getWritableDatabase();
         Cursor mCursor = db.query(SpotContract.PlacesEntry.Table_Name,new String[]{"*"}, SpotContract.PlacesEntry.COLUMN_Category +"=?"+" AND "+ SpotContract.PlacesEntry.COLUMN_city_name+ "=?",
                new String[]{category,city}, null, null, null);
        if(mCursor.getCount()==0){
           new SpotData(context).insertPlacesRecords();
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
            if (mCursor.moveToFirst()) {
                do {
                    Log.e("place",mCursor.getString(1)+mCursor.getString(2));
                } while (mCursor.moveToNext());
            }

        }
        return mCursor;
    }
    public Cursor selectPlaces(String city){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor mCursor = db.query(SpotContract.PlacesEntry.Table_Name,new String[]{"*"}, SpotContract.PlacesEntry.COLUMN_Category +"=?",
                new String[]{city}, null, null, null);
        if(mCursor.getCount()==0){
            new SpotData(context).insertPlacesRecords();
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
            if (mCursor.moveToFirst()) {
                do {
                    Log.e("place",mCursor.getString(1)+mCursor.getString(2));
                } while (mCursor.moveToNext());
            }

        }
        return mCursor;
    }


    public long addUser(User user) {
        //get writable database
        SQLiteDatabase db = this.getWritableDatabase();

        //create content values to insert
        ContentValues values = new ContentValues();

        //Put username in  @values
        values.put(SpotContract.UserEntry.COLUMN_Name, user.userName);

        //Put email in  @values
        values.put(SpotContract.UserEntry.COLUMN_Email, user.email);

        //Put password in  @values
        values.put(SpotContract.UserEntry.COLUMN_password, user.password);

        // insert row
        long todo_id = db.insert(SpotContract.UserEntry.Table_Name, null, values);
        return todo_id;
    }
    public void addCity(List<City> cityList){
        SQLiteDatabase db = this.getWritableDatabase();

        for (int i = 0 ; i < cityList.size();i++){
            ContentValues values = new ContentValues();
            values.put(SpotContract.CitiesEntry.COLUMN_Name,cityList.get(i).cityName);
            values.put(SpotContract.CitiesEntry.COLUMN_Image,cityList.get(i).cityImage);
            long todo_id = db.insert(SpotContract.CitiesEntry.Table_Name, null, values);

       }
        Log.e("data","done");

        db.close();

    }
    public void addPlace(List <Place> placeList){
        SQLiteDatabase db = this.getWritableDatabase();

        for (int i = 0 ; i < placeList.size();i++){
            ContentValues values = new ContentValues();
            values.put(SpotContract.PlacesEntry.COLUMN_Name,placeList.get(i).placeName);
            values.put(SpotContract.PlacesEntry.COLUMN_Image,placeList.get(i).placeImage);
            values.put(SpotContract.PlacesEntry.COLUMN_Description,placeList.get(i).placeDescription);
            values.put(SpotContract.PlacesEntry.COLUMN_Address,placeList.get(i).address);
            values.put(SpotContract.PlacesEntry.COLUMN_Contact,placeList.get(i).contact);
            values.put(SpotContract.PlacesEntry.COLUMN_Category,placeList.get(i).category);
            values.put(SpotContract.PlacesEntry.COLUMN_city_name,placeList.get(i).city_name);
            long todo_id = db.insert(SpotContract.PlacesEntry.Table_Name, null, values);

        }
        Log.e("data","done,done");

        db.close();

    }

}

这是我的光标适配器

    package com.example.android.spot;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.spot.Db.SpotContract;
import com.squareup.picasso.Picasso;

/**
 * Created by CRIZMA-PC&LAPTOP on 28/06/2018.
 */

public class SpotCursorAdapter extends CursorAdapter {

    public SpotCursorAdapter(Context context, Cursor c) {
        super(context, c, 0 /* flags */);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.cities_list_item, parent, false);

    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView CityNameTextView = (TextView) view.findViewById(R.id.cityNameText);
        ImageView CityImageView = (ImageView) view.findViewById(R.id.cityImage);

        // Find the columns of  attributes that we're interested in
        int cityNameColumnIndex = cursor.getColumnIndex(SpotContract.CitiesEntry.COLUMN_Name);
        int cityImageColumnIndex = cursor.getColumnIndex(SpotContract.CitiesEntry.COLUMN_Image);

        // Read the  attributes from the Cursor for the current city
        String cityName = cursor.getString(cityNameColumnIndex);
        String cityImage = cursor.getString(cityImageColumnIndex);

        // Update the TextView and ImageView with the attributes for the current city
        CityNameTextView.setText(cityName);
        Picasso.with(context).load(cityImage).into(CityImageView);
    }

}

这是我的CitiesActivity

   import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.example.android.spot.Db.SpotContract;
import com.example.android.spot.Db.SpotDbAdapter;

public class CitiesActivity extends AppCompatActivity {


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

        ListView citiesListView = (ListView) findViewById(R.id.list);

        Cursor cursor = new SpotDbAdapter(this).selectAllCities();
        SpotCursorAdapter adapter = new SpotCursorAdapter(this, cursor);






        // Setup the item click listener
        citiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                Intent intent = new Intent(CitiesActivity.this, PlacesActivity.class);

                // Form the content URI that represents the specific city that was clicked on,
                // by appending the "id" (passed as input to this method) onto the
                // {@link CitiesEntry#CONTENT_URI}.
                // For example, the URI would be "content://com.example.android.cities/cities/2"
                // if the city with ID 2 was clicked on.
                Uri currentCityUri = ContentUris.withAppendedId(SpotContract.CitiesEntry.CONTENT_URI1, id);

                // Set the URI on the data field of the intent
                intent.setData(currentCityUri);


                startActivity(intent);
            }
        });
    }
}

这是我运行应用程序时得到的 result

这是logcat的内容

    06-29 16:23:07.876 2639-2657/com.example.android.spot E/EGL_emulation: tid 2657: eglSurfaceAttrib(1210): error 0x3009 (EGL_BAD_MATCH)
06-29 16:23:09.276 2639-2639/com.example.android.spot E/city: Ain Sokhna
06-29 16:23:09.276 2639-2639/com.example.android.spot E/city: Taba
06-29 16:23:09.276 2639-2639/com.example.android.spot E/city: Gouna
06-29 16:23:09.276 2639-2639/com.example.android.spot E/city: Marsa Matrouh
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Hurghada
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Neama Bay
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Luxor
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: El Mansourahttps://famouslogos.net/images/kfc-logo.jpg
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Giza
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Al-Minya
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Alexandria
06-29 16:23:09.277 2639-2639/com.example.android.spot E/city: Cairo
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Ain Sokhna
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Taba
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Gouna
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Marsa Matrouh
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Hurghada
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Neama Bay
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Luxor
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: El Mansoura
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Giza
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Al-Minya
06-29 16:23:09.277 2639-2639/com.example.android.spot E/lo: Alexandria
06-29 16:23:09.278 2639-2639/com.example.android.spot E/lo: Cairo
06-29 16:23:09.387 2639-2657/com.example.android.spot E/EGL_emulation: tid 2657: eglSurfaceAttrib(1210): error 0x3009 (EGL_BAD_MATCH)
06-29 16:23:11.155 2639-2639/com.example.android.spot E/city: Ain Sokhna
06-29 16:23:11.155 2639-2639/com.example.android.spot E/city: Taba
06-29 16:23:11.155 2639-2639/com.example.android.spot E/city: Gouna
06-29 16:23:11.155 2639-2639/com.example.android.spot E/city: Marsa Matrouh
06-29 16:23:11.155 2639-2639/com.example.android.spot E/city: Hurghada
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: Neama Bay
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: Luxor
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: El Mansourahttps://famouslogos.net/images/kfc-logo.jpg
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: Giza
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: Al-Minya
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: Alexandria
06-29 16:23:11.156 2639-2639/com.example.android.spot E/city: Cairo
06-29 16:23:11.235 2639-2657/com.example.android.spot E/EGL_emulation: tid 2657: eglSurfaceAttrib(1210): error 0x3009 (EGL_BAD_MATCH)

我无法弄清楚问题是什么,我需要向该城市活动显示数据库中的所有城市内容

1 个答案:

答案 0 :(得分:0)

类似于您,我最近才开始使用android应用和sql数据库,因此,我强烈建议您切换到新的Architecture-components-libraries:

“新的”房间持久性库具有清晰的结构和方便的编译时警告,可轻松实现数据库流量。

特别是对于您的用例,我建议您检查一下“带有视图的房间”代码实验室。至少这是我开始的地方,它使我对如何使用房间库作为mysql数据库的接口并在recycler视图中显示所提到的数据有了很好的了解,据我所知,它比a效率更高。正常的列表视图,归因于动态数据绑定。

以下是代码实验室的链接,希望对您有所帮助: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0