0

Hi I am working on a project in which I have to store and retrieve user's information like FirstName, lastName, Email along with profile picture in a listview in SQLite database I have stored and retrieve name and email but i don't know how to store and retrieve image from database.

DBHaandler Class

public class DBHandler extends SQLiteOpenHelper {

   public static final String db = "UserDB";

public DBHandler(Context context) {

    super(context,"UserDB" ,null, 1);
}

public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table formValidation(firstName TEXT,lastName TEXT,email TEXT primary key,password TEXT,confirmpassword TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS formValidation");


    // db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
}

public Boolean AddNewData(String firstName,String lastName,String email , String password, String confirmPassword) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues Values = new ContentValues();
    Values.put("firstName",firstName);
    Values.put("lastName",lastName);
    Values.put("email",email);
    Values.put("password",password);
    Values.put("confirmPassword",confirmPassword);
      /*   Values.put(COLUMN_FIRST_NAME,firstName);
        Values.put(COLUMN_LAST_NAME,lastName);
        Values.put(COLUMN_EMAIL,email);
        Values.put(COLUMN_PASSWORD,password);
        Values.put(COLUMN_CONFIRM_PASSWORD,confirmPassword);*/
    long result = db.insert("formValidation",null,Values);
    if (result==-1){
        return false;
    }else
        return true;
}

public Boolean checkTable(String email){

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("select * from formValidation where email =? ", new String[] {email});
    //  Cursor cursor = db.rawQuery("select * from " +TABLE_NAME+ " where " +COLUMN_EMAIL+ " =? ", new String[] {email});
    if (cursor.getCount()>0){
        return true;
    }else
        return false;

}

public Boolean checkEmailPassword(String email, String password){

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(" select * from formValidation where email =? AND  password =?", new String[] {email,password});

    // Cursor cursor = db.rawQuery(" select * from " +TABLE_NAME+ " where " +COLUMN_EMAIL+ " =?" + " AND " +COLUMN_PASSWORD+" =?", new String[] {email,password});
    if (cursor.getCount()>0){
        return true;
    }else
        return false;

}
public ArrayList<user> getAllData(){

    ArrayList<user> arrayList = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM formValidation" ,null);

    while (cursor.moveToNext())
    {
        String FirstName = cursor.getString(0);
        String LastName = cursor.getString(1);
        String Email = cursor.getString(2);

        user user = new user(FirstName,LastName,Email);
        arrayList.add(user);
    }
    return arrayList;
}}

SignUP Page`

public class Sign_Up extends AppCompatActivity {


firstName = (EditText) findViewById(R.id.idFirstName);
lastName = (EditText) findViewById(R.id.idLastName);
email = (EditText) findViewById(R.id.idEmail);
password = (EditText) findViewById(R.id.idpassword);
confirmPassword = (EditText) findViewById(R.id.idConfirmPassword);
signUpBtn = (Button) findViewById(R.id.idSignUp_btn);
BackToSigninBtn = (Button) findViewById(R.id.idBackToSignin_btn);
imageView = (ImageView) findViewById(R.id.add_photo);

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

        ActivityCompat.requestPermissions(Sign_Up.this,new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},CAMERA_REQUEST);

    }
});



signUpBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String FirstName = firstName.getText().toString();
        String LastName = lastName.getText().toString();
        String Email = email.getText().toString();
        String Password = password.getText().toString();
        String ConfirmPassword = confirmPassword.getText().toString();



        if (!validatFirstName() | !validateLastName() | !validateEmail() | !validatePassword() | !validateConfirmPassword()) {
            Toast.makeText(Sign_Up.this, "Fill All Fields", Toast.LENGTH_SHORT).show();

            return;

        }
        else
        {
            if (Password.equals(ConfirmPassword))
            {
                Boolean ValidEmail = dbHandler.checkTable(Email);
                if (ValidEmail==false)
                {
                    Boolean register = dbHandler.AddNewData(FirstName,LastName,Email,Password,ConfirmPassword);
                    if (register==true)
                    {


                        Toast.makeText(Sign_Up.this, "Account is created successfully please login to continue", Toast.LENGTH_SHORT).show();
                        firstName.setText("");
                        lastName.setText("");
                        email.setText("");
                        password.setText("");
                        confirmPassword.setText("");
                        Intent intent=new Intent(Sign_Up.this, Login_Page.class);
                        startActivity(intent);
                        finish();

                    }
                    else
                    {
                        Toast.makeText(Sign_Up.this, "Registration Failed", Toast.LENGTH_SHORT).show();

                    }
                }
                else
                {
                    Toast.makeText(Sign_Up.this, " The email address you entered already exists, please try another one", Toast.LENGTH_SHORT).show();

                }
            }
            else
            {
                Toast.makeText(Sign_Up.this, "Password Not Matched", Toast.LENGTH_SHORT).show();

            }

        }
    }
});

BackToSigninBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent=new Intent(Sign_Up.this, Login_Page.class);
        startActivity(intent);
        finish();
    }
});}private boolean validatFirstName(){

String Val = firstName.getText().toString();
if (Val.isEmpty()){
    firstName.setError("please enter your First Name");
    return false;
} else
{
    firstName.setError(null);
    return true;
}}private boolean validateLastName(){
String Val = lastName.getText().toString();
if (Val.isEmpty()){
    lastName.setError("please enter your Last Name");
    return false;
} else
{
    lastName.setError(null);
    return true;
}}private boolean validateEmail(){

String Val = email.getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

if (Val.isEmpty()){
    email.setError("please enter your Email ");
    return false;
}  else if (!Val.matches(emailPattern)) {
    email.setError("Please enter your email address in format yourname@exmaple.com");
    return false;
}
else
{
    email.setError(null);
    return true;
}}private boolean validatePassword(){
String Val = password.getText().toString();
if (Val.isEmpty()){
    password.setError("Password cannot be empty");
    return false;
}
else if ( Val.length() < 8){

    password.setError("Your password must be at least 8 characters long");
    return false;
}
else
{
password.setError(null);
    return true;
}}private boolean validateConfirmPassword(){
String Val = confirmPassword.getText().toString();
if (Val.isEmpty()){
    confirmPassword.setError("Field cannot be empty");
    return false;
} else
{
    confirmPassword.setError(null);
    return true;
}}
@Override public void onRequestPermissionsResult(int requestCode,String[] permissions,  int[] grantResults){ if (requestCode == CAMERA_REQUEST){
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        //gallery intent
        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, CAMERA_REQUEST);
    } else {
        Toast.makeText(this, "Dont Have Permission to access the file location", Toast.LENGTH_SHORT).show();}
    return;
}super.onRequestPermissionsResult(requestCode, permissions, grantResults);}@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
    Uri imageUri = data.getData();CropImage.activity(imageUri)
            .setGuidelines(CropImageView.Guidelines.ON) //enable image guidelines
            .setAspectRatio(1,1)//image will be square
            .start(this); }
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){

    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK){
        Uri resultUri = result.getUri();
        //set image choosed from gallery to image view
        imageView.setImageURI(resultUri);
    }
    else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
        Exception error = result.getError();
    }}


super.onActivityResult(requestCode, resultCode, data);}

Login Page

public class Login_Page extends AppCompatActivity {


EditText email,password;
TextView newUser;
Button signinBtn;
DBHandler dbHandler;
SessionManager sessionManager;

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


    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);


    email = (EditText) findViewById(R.id.idEmail);
    password = (EditText) findViewById(R.id.idpassword);
    signinBtn = (Button) findViewById(R.id.Login_btn);
    newUser = (TextView) findViewById(R.id.New_user);

    sessionManager = new SessionManager(getApplicationContext());
    dbHandler =new DBHandler(this);
    signinBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String Email = email.getText().toString();
            String Password = password.getText().toString();


            if (!validateEmail() | !validatePassword()){
                Toast.makeText(Login_Page.this, "Please Enter The Credentials", Toast.LENGTH_SHORT).show();
            } else {

                Boolean result = dbHandler.checkEmailPassword(Email,Password);
                if (result == true) {//store login session
                    sessionManager.setLogin(true);//store username in session
                    sessionManager.setUseremail(Email);

                    startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    finish();


                } else {
                    Toast.makeText(Login_Page.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
                }

            }
        }
    });
    if (sessionManager.getLogin()){
        startActivity(new Intent(getApplicationContext(),MainActivity.class));
    }
    newUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(Login_Page.this, Sign_Up.class);
            startActivity(intent);
        }
    });
}
private boolean validateEmail(){
    String Val = email.getText().toString();
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

    if (Val.isEmpty()){
        email.setError("please enter your Email");
        return false;
    }
    else
    {
        email.setError(null);
        return true;
    }

}

private boolean validatePassword(){
    String Val = password.getText().toString();
    if (Val.isEmpty()){
        password.setError("please enter your password");
        return false;
    }
    else
    {
        password.setError(null);
        return true;
    }

}}

MainActivity

public class MainActivity extends AppCompatActivity {
Button LogoutBtn;
TextView textView;
ImageView imageView;
SessionManager sessionManager;
ListView listView;
ArrayList<user> arrayList;
UserAdapter adapter;
DBHandler dbHandler;

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

            LogoutBtn = (Button) findViewById(R.id.Logout_btn);
            textView = (TextView) findViewById(R.id.Email);
            listView = (ListView) findViewById(R.id.idListView);
            imageView = (ImageView) findViewById(R.id.userProfile);
            arrayList = new ArrayList<>();


            sessionManager = new SessionManager(getApplicationContext());
            dbHandler =new DBHandler(this);

            String email = sessionManager.getUseremail();
            textView.setText(email);

            loadDataInListView();


            LogoutBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // sessionManager.logoutUser();
                    sessionManager.editor.clear();
                    sessionManager.editor.commit();
                    Intent intent = new Intent(getApplicationContext(), Login_Page.class);
                    startActivity(intent);
                    finish();

                }
            });

        }

        private void loadDataInListView()
        {
            arrayList = dbHandler.getAllData();
            adapter = new UserAdapter(this,arrayList);
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }}

User Class

public class user {
String FirstName,LastName,Email;
public user(String firstName, String lastName, String email) {
    FirstName = firstName;
    LastName = lastName;
    Email = email;
}

public user(){}

public String getFirstName() {
    return FirstName;
}

public void setFirstName(String firstName) {
    FirstName = firstName;
}

public String getLastName() {
    return LastName;
}

public void setLastName(String lastName) {
    LastName = lastName;
}

public String getEmail() {
    return Email;
}

public void setEmail(String email) {
    Email = email;
}}

UserAdapter

public class UserAdapter extends BaseAdapter {

Context context;
ArrayList<user> arrayList;

public UserAdapter(Context context,ArrayList<user> arrayList){
    this.context=context;
    this.arrayList=arrayList;
}
@Override
public int getCount() {
    return this.arrayList.size();
}

@Override
public Object getItem(int position) {
    return arrayList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.user_listview,null);
    TextView textView1 = (TextView) convertView.findViewById(R.id.Firstname);
    TextView textView2 = (TextView) convertView.findViewById(R.id.Lastname);
    TextView textView3 = (TextView) convertView.findViewById(R.id.email);

    user user= arrayList.get(position);
    textView1.setText(user.getFirstName());
    textView2.setText(user.getLastName());
    textView3.setText(user.getEmail());

    return convertView;
}}

I want Something Like this Result

  • Does this answer your question? [How to store image in SQLite database](https://stackoverflow.com/questions/9357668/how-to-store-image-in-sqlite-database) – Tyler V Dec 13 '21 at 05:21

0 Answers0