Latest News

Android Sqlite Crud And Listview - Android Studio Tutorial

      DESCRIPTION      

✔Enter data(Text , Image) in SQLite
✔Read data(Text , Image) from SQLite in Custom ListView
✔Custom obrolan to update record
✔Update data(Text , Image) by onLongClicking the row of ListView
✔Delete data(Text , Image) by onLongClicking the row of ListView
✔Select Image from gallery using Library , crop/rotate image.
Link of image library used: https://github.com/ArthurHub/Android-Image-Cropper

      VIDEO      


      SOURCE CODE      

Step 1: Create a new project OR Open your project

Step 2: Create New Activity File>New>Activity>EmptyActivity

Step 3: Add following libraries in build.gradle(Module:app) 

implementation 'com.android.support:design:27.1.0'
/*cardview library for our row.xml*/
implementation 'com.android.support:cardview-v7:27.1.0'
/*image choosing/cropping library*/
implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.+'


Step 4: Code

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.blogspot.devofandroid.myapplication"><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activityandroid:name="com.theartofdev.edmodo.cropper.CropImageActivity"android:theme="@style/Base.Theme.AppCompat" /><activity android:name=".RecordListActivity"android:parentActivityName=".MainActivity"/></application></manifest>

build.gradle(Module:app)
apply plugin: 'com.android.application'android {compileSdkVersion 27defaultConfig {applicationId "com.blogspot.devofandroid.myapplication"minSdkVersion 16targetSdkVersion 27versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt') , 'proguard-rules.pro'}}}dependencies {implementation fileTree(dir: 'libs' , include: ['*.jar'])implementation 'com.android.support:appcompat-v7:27.1.0'implementation 'com.android.support.constraint:constraint-layout:1.0.2'testImplementation 'junit:junit:4.12'androidTestImplementation 'com.android.support.test:runner:1.0.1'androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'implementation 'com.android.support:design:27.1.0'/*cardview library for our row.xml*/implementation 'com.android.support:cardview-v7:27.1.0'/*image choosing/cropping library*/implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.+'}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?><ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:padding="10dp"><ImageViewandroid:id="@+id/imageView"android:layout_alignParentTop="true"android:background="@color/colorPrimaryDark"android:layout_width="160dp"android:layout_height="160dp"android:src="@drawable/addphoto"android:layout_centerHorizontal="true"android:layout_marginTop="18dp"/><EditTextandroid:id="@+id/edtName"android:layout_below="@id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="Name"android:layout_centerHorizontal="true"android:ems="10"/><EditTextandroid:id="@+id/edtAge"android:layout_below="@id/edtName"android:hint="Age"android:layout_centerHorizontal="true"android:ems="10"android:layout_width="wrap_content"android:layout_height="wrap_content" /><EditTextandroid:id="@+id/edtPhone"android:layout_below="@id/edtAge"android:hint="Phone"android:layout_centerHorizontal="true"android:ems="10"android:layout_width="wrap_content"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btnAdd"android:layout_below="@id/edtPhone"android:layout_centerHorizontal="true"android:minWidth="160dp"android:text="Save Record"style="@style/Base.Widget.AppCompat.Button.Colored"android:layout_width="wrap_content"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btnList"android:layout_below="@id/btnAdd"android:layout_centerHorizontal="true"android:minWidth="160dp"android:text="Record List"style="@style/Base.Widget.AppCompat.Button.Colored"android:layout_width="wrap_content"android:layout_height="wrap_content" /></RelativeLayout></ScrollView>

MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.net.Uri;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.Toast;import com.theartofdev.edmodo.cropper.CropImage;import com.theartofdev.edmodo.cropper.CropImageView;import java.io.ByteArrayOutputStream;public class MainActivity extends AppCompatActivity {EditText mEdtName , mEdtAge , mEdtPhone;Button mBtnAdd , mBtnList;ImageView mImageView;final int REQUEST_CODE_GALLERY = 999;public static SQLiteHelper mSQLiteHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ActionBar actionBar = getSupportActionBar();actionBar.setTitle("New Record");mEdtName = findViewById(R.id.edtName);mEdtAge = findViewById(R.id.edtAge);mEdtPhone = findViewById(R.id.edtPhone);mBtnAdd = findViewById(R.id.btnAdd);mBtnList = findViewById(R.id.btnList);mImageView = findViewById(R.id.imageView);//creating databasemSQLiteHelper = new SQLiteHelper(this , "RECORDDB.sqlite" , null , 1);//creating table in databasemSQLiteHelper.queryData("CREATE TABLE IF NOT EXISTS RECORD(id INTEGER PRIMARY KEY AUTOINCREMENT , name VARCHAR , age VARCHAR , phone VARCHAR , image BLOB)");//select image by on imageview clickmImageView.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//read external storage permission to select image from gallery//runtime permission for devices android 6.0 and aboveActivityCompat.requestPermissions(MainActivity.this ,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE} ,REQUEST_CODE_GALLERY);}});//add record to sqlitemBtnAdd.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {try {mSQLiteHelper.insertData(mEdtName.getText().toString().trim() ,mEdtAge.getText().toString().trim() ,mEdtPhone.getText().toString().trim() ,imageViewToByte(mImageView));Toast.makeText(MainActivity.this , "Added successfully" , Toast.LENGTH_SHORT).show();//reset viewsmEdtName.setText("");mEdtAge.setText("");mEdtPhone.setText("");mImageView.setImageResource(R.drawable.addphoto);}catch (Exception e){e.printStackTrace();}}});//show record listmBtnList.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//start recordlist activitystartActivity(new Intent(MainActivity.this , RecordListActivity.class));}});}public static byte[] imageViewToByte(ImageView image) {Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();ByteArrayOutputStream stream = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG , 100 , stream);byte[] byteArray = stream.toByteArray();return byteArray;}@Overridepublic void onRequestPermissionsResult(int requestCode , @NonNull String[] permissions , @NonNull int[] grantResults) {if (requestCode == REQUEST_CODE_GALLERY){if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){//gallery intentIntent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);galleryIntent.setType("image/*");startActivityForResult(galleryIntent , REQUEST_CODE_GALLERY);}else {Toast.makeText(this , "Don't have permission to access file location" , Toast.LENGTH_SHORT).show();}return;}super.onRequestPermissionsResult(requestCode , permissions , grantResults);}@Overrideprotected void onActivityResult(int requestCode , int resultCode , Intent data) {if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK){Uri imageUri = data.getData();CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON) //enable image guidlines.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 viewmImageView.setImageURI(resultUri);}else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){Exception error = result.getError();}}super.onActivityResult(requestCode , resultCode , data);}}

row.xml
<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"xmlns:app="http://schemas.android.com/apk/res-auto"app:cardElevation="3dp"app:cardUseCompatPadding="true"app:cardCornerRadius="3dp"app:cardBackgroundColor="#fff"app:contentPadding="5dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_gravity="center_vertical"><ImageViewandroid:id="@+id/imgIcon"android:layout_width="100dp"android:layout_height="100dp"android:src="@mipmap/ic_launcher"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"android:layout_marginLeft="5dp"android:layout_marginStart="5dp"><TableLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><TableRow><TextViewandroid:text="Name: "android:textSize="20sp"android:textColor="#000"android:textStyle="bold"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:id="@+id/txtName"android:text="Name Here"android:textSize="20sp"android:textColor="#000"android:layout_width="match_parent"android:layout_height="wrap_content"/></TableRow><TableRow><TextViewandroid:text="Age: "android:textSize="20sp"android:textColor="#000"android:textStyle="bold"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:id="@+id/txtAge"android:text="Age Here"android:textSize="20sp"android:textColor="#000"android:layout_width="match_parent"android:layout_height="wrap_content"/></TableRow><TableRow><TextViewandroid:text="Phone: "android:textSize="20sp"android:textColor="#000"android:textStyle="bold"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:id="@+id/txtPhone"android:text="Phone Here"android:textSize="20sp"android:textColor="#000"android:layout_width="match_parent"android:layout_height="wrap_content"/></TableRow></TableLayout></LinearLayout></LinearLayout></android.support.v7.widget.CardView>

update_dialog.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"android:padding="10dp"><ImageViewandroid:id="@+id/imageViewRecord"android:layout_width="100dp"android:layout_height="100dp"android:background="@color/colorPrimaryDark"android:src="@drawable/addphoto"/><EditTextandroid:id="@+id/edtName"android:hint="Name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:ems="10"/><EditTextandroid:id="@+id/edtAge"android:hint="Age"android:layout_width="wrap_content"android:layout_height="wrap_content"android:ems="10"/><EditTextandroid:id="@+id/edtPhone"android:hint="Phone"android:layout_width="wrap_content"android:layout_height="wrap_content"android:ems="10"/><Buttonandroid:id="@+id/btnUpdate"style="@style/Base.Widget.AppCompat.Button.Colored"android:text="Update"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>

Model.java
package com.blogspot.devofandroid.myapplication;public class Model {private int id;private String name;private String age;private String phone;private byte[] image;public Model(int id , String name , String age , String phone , byte[] image) {this.id = id;this.name = name;this.age = age;this.phone = phone;this.image = image;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public byte[] getImage() {return image;}public void setImage(byte[] image) {this.image = image;}}

SQLiteHelper.java
package com.blogspot.devofandroid.myapplication;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteStatement;public class SQLiteHelper extends SQLiteOpenHelper{//constructorSQLiteHelper(Context context , String name , SQLiteDatabase.CursorFactory factory , int version){super(context , name , factory , version);}public void queryData(String sql){SQLiteDatabase database = getWritableDatabase();database.execSQL(sql);}//insertDatapublic void insertData(String name , String age , String phone , byte[] image){SQLiteDatabase database = getWritableDatabase();//query to insert record in database tableString sql = "INSERT INTO RECORD VALUES(NULL , ? , ? , ? , ?)"; //where "RECORD" is table name in database we will create in mainActivitySQLiteStatement statement = database.compileStatement(sql);statement.clearBindings();statement.bindString(1 , name);statement.bindString(2 , age);statement.bindString(3 , phone);statement.bindBlob(4 , image);statement.executeInsert();}//updateDatapublic void updateData(String name , String age , String phone , byte[] image , int id){SQLiteDatabase database = getWritableDatabase();//query to update recordString sql = "UPDATE RECORD SET name=? , age=? , phone=? , image=? WHERE id=?";SQLiteStatement statement = database.compileStatement(sql);statement.bindString(1 , name);statement.bindString(2 , age);statement.bindString(3 , phone);statement.bindBlob(4 , image);statement.bindDouble(5 , (double)id);statement.execute();database.close();}//deleteDatapublic void deleteData(int id){SQLiteDatabase database = getWritableDatabase();//query to delete record using idString sql = "DELETE FROM RECORD WHERE id=?";SQLiteStatement statement = database.compileStatement(sql);statement.clearBindings();statement.bindDouble(1 , (double)id);statement.execute();database.close();}public Cursor getData(String sql){SQLiteDatabase database = getReadableDatabase();return database.rawQuery(sql , null);}@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {}@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase , int i , int i1) {}}

RecordListAdapter.java
package com.blogspot.devofandroid.myapplication;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;import java.util.ArrayList;public class RecordListAdapter extends BaseAdapter {private Context context;private int layout;private ArrayList<Model> recordList;public RecordListAdapter(Context context , int layout , ArrayList<Model> recordList) {this.context = context;this.layout = layout;this.recordList = recordList;}@Overridepublic int getCount() {return recordList.size();}@Overridepublic Object getItem(int i) {return recordList.get(i);}@Overridepublic long getItemId(int i) {return i;}private class ViewHolder{ImageView imageView;TextView txtName , txtAge , txtPhone;}@Overridepublic View getView(int i , View view , ViewGroup viewGroup) {View row = view;ViewHolder holder = new ViewHolder();if (row==null){LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);row = inflater.inflate(layout , null);holder.txtName = row.findViewById(R.id.txtName);holder.txtAge = row.findViewById(R.id.txtAge);holder.txtPhone = row.findViewById(R.id.txtPhone);holder.imageView = row.findViewById(R.id.imgIcon);row.setTag(holder);}else {holder = (ViewHolder)row.getTag();}Model model = recordList.get(i);holder.txtName.setText(model.getName());holder.txtAge.setText(model.getAge());holder.txtPhone.setText(model.getPhone());byte[] recordImage = model.getImage();Bitmap bitmap = BitmapFactory.decodeByteArray(recordImage , 0 , recordImage.length);holder.imageView.setImageBitmap(bitmap);return row;}}

activity_record_list.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".RecordListActivity"><ListViewandroid:id="@+id/listView"android:layout_width="match_parent"android:layout_height="match_parent"></ListView></LinearLayout>

RecordListActivity.java
package com.blogspot.devofandroid.myapplication;import android.Manifest;import android.app.Activity;import android.app.Dialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.net.Uri;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v7.app.ActionBar;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.ListView;import android.widget.Toast;import com.theartofdev.edmodo.cropper.CropImage;import com.theartofdev.edmodo.cropper.CropImageView;import java.io.ByteArrayOutputStream;import java.util.ArrayList;public class RecordListActivity extends AppCompatActivity {ListView mListView;ArrayList<Model> mList;RecordListAdapter mAdapter = null;ImageView imageViewIcon;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_record_list);ActionBar actionBar = getSupportActionBar();actionBar.setTitle("Record List");mListView = findViewById(R.id.listView);mList = new ArrayList<>();mAdapter = new RecordListAdapter(this , R.layout.row , mList);mListView.setAdapter(mAdapter);//get all data from sqliteCursor cursor = MainActivity.mSQLiteHelper.getData("SELECT * FROM RECORD");mList.clear();while (cursor.moveToNext()){int id = cursor.getInt(0);String name = cursor.getString(1);String age = cursor.getString(2);String phone = cursor.getString(3);byte[] image  = cursor.getBlob(4);//add to listmList.add(new Model(id , name , age , phone , image));}mAdapter.notifyDataSetChanged();if (mList.size()==0){//if there is no record in table of database which means listview is emptyToast.makeText(this , "No record found..." , Toast.LENGTH_SHORT).show();}mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> adapterView , View view , final int position , long l) {//alert obrolan to display options of update and deletefinal CharSequence[] items = {"Update" , "Delete"};AlertDialog.Builder obrolan = new AlertDialog.Builder(RecordListActivity.this);dialog.setTitle("Choose an action");dialog.setItems(items , new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface , int i) {if (i == 0){//updateCursor c = MainActivity.mSQLiteHelper.getData("SELECT id FROM RECORD");ArrayList<Integer> arrID = new ArrayList<Integer>();while (c.moveToNext()){  arrID.add(c.getInt(0));}//show update dialogshowDialogUpdate(RecordListActivity.this , arrID.get(position));}if (i==1){//deleteCursor c = MainActivity.mSQLiteHelper.getData("SELECT id FROM RECORD");ArrayList<Integer> arrID = new ArrayList<Integer>();while (c.moveToNext()){  arrID.add(c.getInt(0));}showDialogDelete(arrID.get(position));}}});dialog.show();return true;}});}private void showDialogDelete(final int idRecord) {AlertDialog.Builder dialogDelete = new AlertDialog.Builder(RecordListActivity.this);dialogDelete.setTitle("Warning!!");dialogDelete.setMessage("Are you sure to delete?");dialogDelete.setPositiveButton("OK" , new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface , int i) {try {MainActivity.mSQLiteHelper.deleteData(idRecord);Toast.makeText(RecordListActivity.this , "Delete successfully" , Toast.LENGTH_SHORT).show();}catch (Exception e){Log.e("error" , e.getMessage());}updateRecordList();}});dialogDelete.setNegativeButton("Cancel" , new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface , int i) {dialogInterface.dismiss();}});dialogDelete.show();}private void showDialogUpdate(Activity activity , final int position){final Dialog obrolan = new Dialog(activity);dialog.setContentView(R.layout.update_dialog);dialog.setTitle("Update");imageViewIcon = dialog.findViewById(R.id.imageViewRecord);final EditText edtName = dialog.findViewById(R.id.edtName);final EditText edtAge = dialog.findViewById(R.id.edtAge);final EditText edtPhone = dialog.findViewById(R.id.edtPhone);Button btnUpdate = dialog.findViewById(R.id.btnUpdate);//set width of dialogint width = (int)(activity.getResources().getDisplayMetrics().widthPixels*0.95);//set hieght of dialogint height = (int)(activity.getResources().getDisplayMetrics().heightPixels*0.7);dialog.getWindow().setLayout(width ,height);dialog.show();//in update obrolan click image view to update imageimageViewIcon.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//check external storage permissionActivityCompat.requestPermissions(RecordListActivity.this ,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE} ,888);}});btnUpdate.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {try {MainActivity.mSQLiteHelper.updateData(edtName.getText().toString().trim() ,edtAge.getText().toString().trim() ,edtPhone.getText().toString().trim() ,MainActivity.imageViewToByte(imageViewIcon) ,position);dialog.dismiss();Toast.makeText(getApplicationContext() , "Update Successfull" , Toast.LENGTH_SHORT).show();}catch (Exception error){Log.e("Update error" , error.getMessage());}updateRecordList();}});}private void updateRecordList() {//get all data from sqliteCursor cursor = MainActivity.mSQLiteHelper.getData("SELECT * FROM RECORD");mList.clear();while (cursor.moveToNext()){int id = cursor.getInt(0);String name = cursor.getString(1);String age = cursor.getString(2);String phone = cursor.getString(3);byte[] image = cursor.getBlob(4);mList.add(new Model(id ,name ,age ,phone ,image));}mAdapter.notifyDataSetChanged();}public static byte[] imageViewToByte(ImageView image) {Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();ByteArrayOutputStream stream = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG , 100 , stream);byte[] byteArray = stream.toByteArray();return byteArray;}@Overridepublic void onRequestPermissionsResult(int requestCode , @NonNull String[] permissions , @NonNull int[] grantResults) {if (requestCode == 888){if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){//gallery intentIntent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);galleryIntent.setType("image/*");startActivityForResult(galleryIntent , 888);}else {Toast.makeText(this , "Don't have permission to access file location" , Toast.LENGTH_SHORT).show();}return;}super.onRequestPermissionsResult(requestCode , permissions , grantResults);}@Overrideprotected void onActivityResult(int requestCode , int resultCode , Intent data) {if (requestCode == 888 && resultCode == RESULT_OK){Uri imageUri = data.getData();CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON) //enable image guidlines.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 viewimageViewIcon.setImageURI(resultUri);}else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){Exception error = result.getError();}}super.onActivityResult(requestCode , resultCode , data);}}

Step 5: Run Project

Output
Android SQLite CRUD and ListView - Android Studio Tutorial

0 Response to "Android Sqlite Crud And Listview - Android Studio Tutorial"