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

Posted

技术标签:

【中文标题】如何将数据库中的数据调用到我的活动中【英文标题】:How to call data from database to my activity 【发布时间】:2018-12-08 22:39:27 【问题描述】:

我是 android 的初学者,我正在做我的毕业项目,显示埃及的所有城市和地方我在这里面临这个问题

我希望活动看起来像这样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);
    


这是我的城市活动

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

与您类似,我最近才开始使用 android 应用程序和 sql 数据库,所以我强烈建议您切换到新的架构组件库:

“新”房间持久性库以其清晰的结构和方便的编译时警告使数据库流量变得非常容易。

特别是对于您的用例,我建议您查看“带景观的房间”-codelab。至少那是我开始的地方,它让我很好地理解了如何使用房间库作为我的 mysql 数据库的接口并在回收器视图中显示提到的数据,据我了解,这比正常的列表视图,由于动态数据绑定。

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

【讨论】:

以上是关于如何将数据库中的数据调用到我的活动中的主要内容,如果未能解决你的问题,请参考以下文章

如何将 URL 中的 XmL 数据保存到我的数据库中

如何根据从 ajax 调用返回的数据动态地将选项添加到我的自动完成功能?

如何将数据从 Intent 传递到 Fragment

如何将变量从 AsyncTask 返回到 Android 中的 Google Map 活动

如何将 PictureBox 中的图像保存到我的数据库中?

如何将模板中的动态表传递给我的视图以迭代地将它们保存到我的数据库中