Как вызвать данные из базы данных в мою деятельность - PullRequest
0 голосов
/ 29 июня 2018

Я новичок в Android и IAM, работаю над своим дипломным проектом, который отображает все города и места в Египте Iam, сталкивающиеся с этой проблемой здесь

Я хочу, чтобы деятельность выглядела так макет

это мой адаптер БД

    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);
            }
        });
    }
}

это то, что я получаю, когда запускаю приложение результат

это содержимое 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 голосов
/ 29 июня 2018

Как и вы, я только недавно начал работать с приложениями для Android и базами данных sql, поэтому я настоятельно рекомендую вам перейти на новые библиотеки архитектуры-компонентов:

«Новая» библиотека сохраняемости помещений делает работу с базами данных довольно простой благодаря четкой структуре и удобным предупреждениям во время компиляции.

Особенно для вашего случая использования, я бы посоветовал вам проверить кодовую комнату "Комната с видом". По крайней мере, это то, с чего я начал, и это дало мне хорошее понимание того, как использовать библиотеку комнаты в качестве интерфейса к моей базе данных mysql и отображать упомянутые данные в виде переработчика, что, на мой взгляд, даже более эффективно, чем нормальный просмотр списка из-за динамического связывания данных.

Вот ссылка на codelab, надеюсь, это поможет: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...