Read values from a table in Sqlite

Asked

Viewed 2,155 times

4

I am in need of a help in the following situation: I need to take the values of a column in the bank and write these values in a variable, and then this variable will randomly generate one of these stored data.

Down the class where I create the bank:

import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import dominio.android.forca.data.DataBaseDescription.Contact;

class AddressBookDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "Forca.db";
    private static final int DATABASE_VERSION = 1;

    // constructor
    public AddressBookDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // creates the contacts table when the database is created
    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL for creating the contacts table
        final String CREATE_CONTACTS_TABLE =
                "CREATE TABLE " + Contact.TABLE_NAME + "(" +
                        Contact._ID + " integer primary key, " +
                        Contact.COLUMN_WORD + " TEXT, " +
                        Contact.COLUMN_TIP + " TEXT);";
        db.execSQL(CREATE_CONTACTS_TABLE); // create the contacts table
    }

    // normally defines how to upgrade the database when the schema changes
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

Below is the class describing the table name and columns, and other information from Contentprovider:

import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;

public class DataBaseDescription {
    // ContentProvider's name: typically the package name
    public static final String AUTHORITY =
            "dominio.android.forca.data";

    // base URI used to interact with the ContentProvider
    private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);

    // nested class defines contents of the contacts table
    public static final class Contact implements BaseColumns {
        public static final String TABLE_NAME = "palavrasforca"; // table's name

        // Uri for the contacts table
        public static final Uri CONTENT_URI =
                BASE_CONTENT_URI.buildUpon().appendPath(TABLE_NAME).build();

        // column names for contacts table's columns
        public static final String COLUMN_WORD = "palavra";
        public static final String COLUMN_TIP = "dica";


        // creates a Uri for a specific contact
        public static Uri buildContactUri(long id) {
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }


    }
}

And now, the class I’m establishing a method to randomly generate the column value COLUMN_WORD table. There’s the problem. I don’t know how to redeem these values and play within the public String[] palavras = new String[] {};

import java.util.Random;

public class Palavras{

    public String[] palavras = new String[] {};


    public Palavras() {
    }

    public String sorteio() {
        String palavraSorteada = palavras[(int)(random()*palavras.length)];

        return palavraSorteada;
    }

    public static double random() {
        Random r = new Random();

        return r.nextDouble();
    }
}

Sorry for the mistakes in the codes above, I’m starting to learn to program on Android.

1 answer

2


You can take the Random value from SQL itself for example:

private void Exemplo(){
    SQLiteDatabase db = getReadableDatabase();
    String selectQuery = "SELECT dica, palavra FROM palavrasforca ORDER BY random() LIMIT 1";
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
      String dica = cursor.getString(cursor.getColumnIndex("dica"));
      String palavra = cursor.getString(cursor.getColumnIndex("palavra "));
   }
}

or if you want to press memory

   private String[] Exemplo(){
            List<String> dados = new ArrayList()
            SQLiteDatabase db = getReadableDatabase();
            String selectQuery = "SELECT palavra FROM palavrasforca";
            Cursor cursor = db.rawQuery(selectQuery, null);

            if (cursor.moveToFirst()) {
              do{
                  String palavra = cursor.getString(cursor.getColumnIndex("palavra"));
                  dados.add(palavra) 
              }while (cursor.moveToNext())
            }
            //aqui dados terá todos os valores do banco
            //converte o list para array
            return dados.toArray(new String[dados.size()]);

        }

Place the code in the Addressbookdatabasehelper class

I hope I’ve helped!

  • Very good!! Thank you! Just one more question. I have a class Words, there in it I have a vector of String ready. How I would take this select and throw it at her?

  • As you do not know the amount of items you have in the bank, I recommend using the List<String> because in it you only call the .add, if at the end you want to pass to a String array you can do the following palavras = dados.toArray(new String[dados.size()])

  • I’m having a problem. Because I did it the second way and returned a List<String>, and in the Words class he is not recognizing the Addressbookdatabasehelper class when I call lista_palavras = Exemplo(); What could be?

  • I edited the answer, the Example method returns "void", only adapt to return String[] and do the conversion below.

  • The last thing kkk. How can I identify the hint of the word that was randomized.

  • You can make an appointment at the bank SELECT dica FROM palavrasforca WHERE palavra = 'palavraexemplo', the same way you do the query and the cursor only change to cursor.getString(cursor.getColumnIndex("dica"))

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.