-2

I got a code: I got SQLite database with one table.:

package com.example.kanlane;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class SQLite extends SQLiteOpenHelper {

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "sosDB";
    public static final String TABLE_CONTACTS = "contacts";

    public static final String KEY_ID = "_id";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_USERBINDER = "user_binder";


    public SQLite(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_CONTACTS + "(" + KEY_ID + " integer primary key," + KEY_EMAIL +
                " text," + KEY_EMAIL + " text" + ")");


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists " + TABLE_CONTACTS);

        onCreate(db);


    }
}

Register activity which inserts data to SQLite, it inserts email and user_binder strings:

public class Register extends AppCompatActivity {
    //Variables
    EditText mName, mEmail, mPassword, mUser_binder;
    SQLite sqLite;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);


        mName = findViewById(R.id.Name);
        mEmail = findViewById(R.id.Email);
        mPassword = findViewById(R.id.Password);
        mUser_binder = findViewById(R.id.user_bind);
        mLoginbtn = findViewById(R.id.login_mainscreen);
        mRegisterBtn = findViewById(R.id.register_btn);

        sqLite = new SQLite(this);


       
        mRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                
                String id = mDataBase.getKey();
                String name = mName.getText().toString().trim();
                String email = mEmail.getText().toString().trim();
                String password = mPassword.getText().toString().trim();
                String user_binder = mUser_binder.getText().toString().trim();

                SQLiteDatabase database = sqLite.getWritableDatabase();
                ContentValues contentValues = new ContentValues();

                contentValues.put(SQLite.KEY_EMAIL, email);
                contentValues.put(SQLite.KEY_USERBINDER, user_binder);
                database.insert(SQLite.TABLE_CONTACTS, null, contentValues);





                User newUser = new User(id, name, email, password, user_binder);
                mDataBase.push().setValue(newUser);

                if(TextUtils.isEmpty(email)){
                    mEmail.setError("Введите почту...");
                    return;
                }
                if(TextUtils.isEmpty(password)){
                    mEmail.setError("Введите пароль...");
                    return;
                }
                if(password.length() < 8 ){
                    mPassword.setError("Пароль должен состоять из 8-ми символов.");
                    return;
                }

                
                fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override


                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){

                            Toast.makeText(Register.this, "Пользователь зарегистрирован.",Toast.LENGTH_LONG).show();

                            startActivity(new Intent(getApplicationContext(), MainActivity.class));
                        }else{
                            Toast.makeText(Register.this, "Произошла ошибка. Повторите." +
                                    task.getException().getMessage(),Toast.LENGTH_LONG).show();
                        }
                    }
                });


            }
        });



}
}

And MainActivity which needs to read data from SQLite and put it in variables (String emailfrom, emailto;)

public class MainActivity extends AppCompatActivity {

        Button mAccountBtn;
        Button mSosButton;
        DatabaseReference databaseReference;
        SQLite sqLite;



        //EmailTo это Email
        //EmailFrom это UserBinder



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

            mAccountBtn = findViewById(R.id.account_btn);
            mSosButton = findViewById(R.id.sos_button);

            sqLite = new SQLite(this);

            SQLiteDatabase database = sqLite.getWritableDatabase();
            

}

All I need is to read data which Register activity inserted and put it in strings. How to do it?

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
  • Does this answer your question? [How to perform an SQLite query within an Android application?](https://stackoverflow.com/questions/1243199/how-to-perform-an-sqlite-query-within-an-android-application) – Martin Zeitler May 22 '22 at 19:30

1 Answers1

0

All I need is to read data which Register activity inserted and put it in strings. How to do it?

You extract data into a Cursor using a query that SELECT's the appropriate data via a suitable SQLiteDatabase method that returns a Cursor. It is then a matter of traversing the returned Cursor using the Cursor's methods.

The two suitable SQLiteDatabase methods to query are the query method and rawQuery. The former being a convenience method that builds the underlying SQL based upon parameters passed to the method (of which there are four). The latter is passed the SQL string.

e.g. say you wanted to get the data for a provided email you could use:-

Cursor csr = database.query(TABLE_CONTACTS,null,"KEY_EMAIL=?",new String[]{"the_email_address"},null,null,null);
  • The 3rd and 4th parameter are used to build the WHERE clause. The first is the actual clause where the ? is replaced (bound) using the 4th parameter. This is the recommended way to handle variable data within the query as it protects against SQL injection.

or

Cursor csr = database.rawQuery("SELECT * FROM " + TABLE_CONTACTS + " WHERE " + KEY_EMAIL + "=?",new String[]{"the_email_address"});
  • The second parameter is data to be bound, i.e. to replace the ?'s on a 1 by 1 basis.

You traverse the Cursor typicaly using the move... methods. It should be noted that a Cursor will be initially positioned at a position that is before the first row. So you have to move to a suitable row. In the case above you would be looking for just a single row; as such you would probably want to use the moveToFirst method. Noting that this returns true if the move can be made (there is a row) or false if the move cannot be made (there are no rows).

So you probably want

if (csr.moveToFirst()) {
    ....
}
csr.close();

You extract the data from the Cursor using the get... methods to get the value from a column.

So to get all the data .... (the body of the if statement) could be :-

String id = csr.getString(0);
String email = csr.getString(1);
String user_binder = csr.getString(2);

This uses the Cursor's get.... methods

MikeT
  • 51,415
  • 16
  • 49
  • 68