So friends, today in this tutorial we will create such app in which “set image as wallpaper, share image and save or download image on button click.” This tutorial is about to show you the different and unique functionality that we often see in many applications.
Here we used SQLite database to store images and EditText data, after that we used RecyclerView to show data GridView.
We are talking about “set wallpaper, share image and save image with current date and time.” step by step.
We will create following functionality app using SQLite database.
Which we understand by the following queries.
- SQLite Database GridView Image
- Set image as wallpaper on click button in android
- Save image by current date and time wise
- How to save GridView image in android studio?
- Share image on click button
All the above topics we will cover in this tutorial.
We will cover all the topics step by step.
Pick Image from Gallery and show GridView
In this topic, we have already discussed the topic “GridView Image Sharing App“. If you want to save or download a GridView image or you want to set an image as wallpaper, then this tutorial will help you a lot.
Set image as wallpaper on click button
With on click of a button in android, we will set an image as wallpaper. You can change android wallpaper using GridView image.
Save or download the image as per current date and time
When clicking on the button, save or download the image as per the current date and time. We will add such a button on the GridView image which will save or download the image by name, date and time by clicking on the button.
Share image on click button
GridView Share Image, We have already covered this topic and will cover it in this tutorial as well.
Using this functionality, you can easily share any image you want.
Now let us look at examples above each topic.
Let’s start with the example step by step
Step: 1
Create a new android studio project
Step: 2
Click on AndroidManifest.xml
App⇾manifests⇾AndroidManifest.xml
First, add the following permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Step 3:
Open activity_main.xml
App⇾res⇾layout
We will use ImageView, EditText, as well as two buttons in this which we will submit data to SQLite database and other, will display data on click button.
Add following code in activity_main.xml
activity_main.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"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_marginTop="20dp"
android:id="@+id/avatar"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@mipmap/ic_launcher"
android:layout_gravity="center_horizontal"/>
<EditText
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:hint="Name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="@+id/submit"
android:text="submit"
android:textAllCaps="false"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="@+id/display"
android:text="display"
android:textAllCaps="false"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
Step: 4
Create a single view data XML recourse file
Res ⇾right click on layout ⇾new ⇾Layout Resource file
Named singledata.xml
Here we set the image view, wallpaper, share image and save image buttons as well as the text view.
The complete code of singledata.xml file is given below
Singledata.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="6dp"
app:cardUseCompatPadding="true"
app:cardPreventCornerOverlap="true"
app:cardCornerRadius="12dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:elevation="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:src="@drawable/ic_baseline_settings_system_daydream_24"
android:layout_alignLeft="@+id/avatarview"
android:elevation="18dp"
android:id="@+id/setw"/>
<ImageButton
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:src="@drawable/ic_baseline_share_24"
android:layout_alignRight="@+id/avatarview"
android:elevation="18dp"
android:id="@+id/share"/>
<ImageButton
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:src="@drawable/ic_baseline_save_alt_24"
android:layout_centerHorizontal="true"
android:elevation="18dp"
android:id="@+id/save"/>
</LinearLayout>
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:id="@+id/avatarview"
android:scaleType="fitCenter"
android:src="@mipmap/ic_launcher_round"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/avatarview"
android:text="@string/app_name"
android:layout_centerInParent="true"
android:textStyle="bold"
android:id="@+id/nameview"
android:textSize="24dp"/>
</RelativeLayout>
<ProgressBar
android:visibility="gone"
android:id="@+id/prog"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content" />
</androidx.cardview.widget.CardView>
Step: 5
We want to use the SQLite database, so create the SQLite database.
Create a new class named DBmain.
App⇾java⇾right click on package name ⇾new ⇾java class
Here we create the SQLite database which we have already discussed.
The complete code of DBmain.java file is given below
DBmain.java
package com.example.gridimageshare;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBmain extends SQLiteOpenHelper {
public static final String SHARE="share.db";
public static final String IMAGETABLE="image";
public static final int VER=1;
public DBmain(@Nullable Context context) {
super(context, SHARE, null, VER);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query="create table "+IMAGETABLE+"(id integer primary key, avatar blob, name text)";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query="drop table if exists "+IMAGETABLE+"";
db.execSQL(query);
}
}
Step: 6
Create a model class named Model
App⇾java⇾right click on package name⇾new ⇾java class
The complete code of the Model.java file is given below.
Model.java
package com.example.gridimageshare;
public class Model {
private int id;
private byte[]avataru;
private String nameu;
//generate constructor
public Model(int id, byte[] avataru, String nameu) {
this.id = id;
this.avataru = avataru;
this.nameu = nameu;
}
//generate getter and setter method
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public byte[] getAvataru() {
return avataru;
}
public void setAvataru(byte[] avataru) {
this.avataru = avataru;
}
public String getNameu() {
return nameu;
}
public void setNameu(String nameu) {
this.nameu = nameu;
}
}
Step: 7
Create an adapter class named Adapter to display SQLite single view data in RecyclerView
App⇾java⇾right click on package name⇾new ⇾java class
Here we will add all functionality like share image, set image as wallpaper and save or download image.
How to Share Image on click button
If you want to share the GridView image on the click button, then add the following code inside the adapter class:
holder.share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmapshare=((BitmapDrawable)holder.avatarview.getDrawable()).getBitmap();
Intent intentshare=new Intent();
intentshare.setAction(Intent.ACTION_SEND);
intentshare.setType("image/jpg/png");
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmapshare.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
String path= MediaStore.Images.Media.insertImage(context.getContentResolver(),bitmapshare,"Title",null);
Uri uri=Uri.parse(path);
intentshare.putExtra(Intent.EXTRA_STREAM,uri);
intentshare.putExtra(Intent.EXTRA_TEXT,"Quote:-"+model.getNameu());
intentshare.putExtra(Intent.EXTRA_SUBJECT,"Quotes");
context.startActivity(Intent.createChooser(intentshare,"Send your Image"));
}
});
How to set the image as wallpaper on click button
Now if you want to set an image as wallpaper on the click button then add the following code inside the adapter class.
We are about to set the GridView image as wallpaper. Also, show an alert dialog to confirm that you really want to change the wallpaper image in your Android phone.
Add the following code inside the adapter to set GridView image as wallpaper in android.
holder.setwa.setOnClickListener(new View.OnClickListener() {
@SuppressLint("WrongConstant")
@Override
public void onClick(View v) {
/////////////
AlertDialog.Builder wallpaper=new AlertDialog.Builder(context);
wallpaper.setTitle("do you want to set wallpaper?");
wallpaper.setPositiveButton("Set", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Bitmap setbitmap=((BitmapDrawable)holder.avatarview.getDrawable()).getBitmap();
if (setbitmap == null) {
Toast.makeText(context, "Set Wallpaper error! Please connect internet", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Set Wallpaper error! Please connect internet", 1).show();
} else {
try {
WallpaperManager.getInstance(context).setBitmap(setbitmap);
Toast.makeText(context, "Set Wallpaper successful", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
}
}
// wallpaper.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// })
}
});
wallpaper.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
wallpaper.create().show();
// holder.setwa.callOnClick();
// Toast.makeText(context, "Set Wallpaper successful!", 0).show();
}
});
How to save or download image current TimeStamp
Finally, we’ll download or save the GridView image in the phone’s external storage. Also, we’ll create a new directory and Gridview image save current date and time-wise
If you want to save the GridView image name with the timestamp, then add the following code inside the adapter class.
holder.save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
////////////////
BitmapDrawable drawable=(BitmapDrawable)holder.avatarview.getDrawable();
Bitmap bitmap1=drawable.getBitmap();
File sdcard=Environment.getExternalStorageDirectory();
/////////
File file = new File(sdcard.getAbsolutePath() + "/Quotes image");
file.mkdirs();
// context pagerImageActivity = context;
////////////////////////save by timestamp
// Calendar instance = Calendar.getInstance();
// String format = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()).format(instance.getTime());
// String format2 = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(instance.getTime());
// String[] split = format.split("/");
// String[] split2 = format2.split(":");
// String str =holder.nameview.getText().toString()+"_"+(split[0] + split[1] + split[2]) + (split2[0] + split2[1] + split2[2]);
/////////////
String str=holder.nameview.getText().toString();
boolean succss=false;
FileOutputStream outputStream;
try {
String img=".jpg";
outputStream=new FileOutputStream(new File(file,str+img));
bitmap1.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
outputStream.flush();
outputStream.close();
/////////
ProgressDialog progressDialog;
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("saving..."+str);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressDialog.cancel();
}
},2000);
progressDialog.show();
/////////
// Toast.makeText(context, "downloaded\n"+holder.nameview.getText().toString(), Toast.LENGTH_SHORT).show();
succss=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Save image with EditText name
Note:- Uncomment line to save Image current timestamp
The full code of the Adapter.java file is given below
Adatper.java
package com.example.gridimageshare;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
int singledata;
ArrayList<Model>arrayList;
SQLiteDatabase sqLiteDatabase;
//generate constructor
public Adapter(Context context, int singledata, ArrayList<Model> arrayList, SQLiteDatabase sqLiteDatabase) {
this.context = context;
this.singledata = singledata;
this.arrayList = arrayList;
this.sqLiteDatabase = sqLiteDatabase;
}
@NonNull
@Override
public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater= LayoutInflater.from(context);
View view=inflater.inflate(R.layout.singledata,null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) {
final Model model=arrayList.get(position);
byte[]bytes=model.getAvataru();
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
holder.avatarview.setImageBitmap(bitmap);
holder.nameview.setText(model.getNameu());
//share image
holder.share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmapshare=((BitmapDrawable)holder.avatarview.getDrawable()).getBitmap();
Intent intentshare=new Intent();
intentshare.setAction(Intent.ACTION_SEND);
intentshare.setType("image/jpg/png");
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmapshare.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
String path= MediaStore.Images.Media.insertImage(context.getContentResolver(),bitmapshare,"Title",null);
Uri uri=Uri.parse(path);
intentshare.putExtra(Intent.EXTRA_STREAM,uri);
intentshare.putExtra(Intent.EXTRA_TEXT,"Quote:-"+model.getNameu());
intentshare.putExtra(Intent.EXTRA_SUBJECT,"Quotes");
context.startActivity(Intent.createChooser(intentshare,"Send your Image"));
}
});
//set image wallpaper
holder.setwa.setOnClickListener(new View.OnClickListener() {
@SuppressLint("WrongConstant")
@Override
public void onClick(View v) {
/////////////
AlertDialog.Builder wallpaper=new AlertDialog.Builder(context);
wallpaper.setTitle("do you want to set wallpaper?");
wallpaper.setPositiveButton("Set", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Bitmap setbitmap=((BitmapDrawable)holder.avatarview.getDrawable()).getBitmap();
if (setbitmap == null) {
Toast.makeText(context, "Set Wallpaper error! Please connect internet", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Set Wallpaper error! Please connect internet", 1).show();
} else {
try {
WallpaperManager.getInstance(context).setBitmap(setbitmap);
Toast.makeText(context, "Set Wallpaper successful", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
}
}
// wallpaper.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// })
}
});
wallpaper.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
wallpaper.create().show();
// holder.setwa.callOnClick();
// Toast.makeText(context, "Set Wallpaper successful!", 0).show();
}
});
//save image
holder.save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
////////////////
BitmapDrawable drawable=(BitmapDrawable)holder.avatarview.getDrawable();
Bitmap bitmap1=drawable.getBitmap();
File sdcard=Environment.getExternalStorageDirectory();
/////////
File file = new File(sdcard.getAbsolutePath() + "/Quotes image");
file.mkdirs();
// context pagerImageActivity = context;
////////////////////////save by timestamp
// Calendar instance = Calendar.getInstance();
// String format = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()).format(instance.getTime());
// String format2 = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(instance.getTime());
// String[] split = format.split("/");
// String[] split2 = format2.split(":");
// String str =holder.nameview.getText().toString()+"_"+(split[0] + split[1] + split[2]) + (split2[0] + split2[1] + split2[2]);
/////////////
String str=holder.nameview.getText().toString();
boolean succss=false;
FileOutputStream outputStream;
try {
String img=".jpg";
outputStream=new FileOutputStream(new File(file,str+img));
bitmap1.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
outputStream.flush();
outputStream.close();
/////////
ProgressDialog progressDialog;
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("saving..."+str);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressDialog.cancel();
}
},2000);
progressDialog.show();
/////////
// Toast.makeText(context, "downloaded\n"+holder.nameview.getText().toString(), Toast.LENGTH_SHORT).show();
succss=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView avatarview;
TextView nameview;
ImageButton share,setwa,save;
ProgressBar progressBar;
public ViewHolder(@NonNull View itemView) {
super(itemView);
avatarview=(ImageView)itemView.findViewById(R.id.avatarview);
nameview=(TextView)itemView.findViewById(R.id.nameview);
share=(ImageButton)itemView.findViewById(R.id.share);
setwa=(ImageButton)itemView.findViewById(R.id.setw);
save=(ImageButton)itemView.findViewById(R.id.save);
progressBar=itemView.findViewById(R.id.prog);
}
}
}
Step: 8
Now we want to show all data in a new activity.
To create a new empty activity named MaimActivity2.java
App⇾java⇾right click on package name ⇾new ⇾Activity ⇾Empty Activity
Step: 9
First, we’ll add a recyclerview inside activity_main2.xml
The code of activity_main2.xml given below
Activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv"/>
</RelativeLayout>
Step: 10
Now we fetch data from the SQLite database and display it as GridView’s second activity, which means MainActivity2.java.
Finally, we will display all user edit data in MainActivity2.java using the cursor.
The full code of MainActivity2.java file is given below
MainActivity2.java
package com.example.gridimageshare;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import java.util.ArrayList;
import static com.example.gridimageshare.DBmain.IMAGETABLE;
public class MainActivity2 extends AppCompatActivity {
SQLiteDatabase sqLiteDatabase;
DBmain dBmain;
RecyclerView recyclerView;
Adapter myadater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dBmain=new DBmain(this);
//create method
findId();
dispalyData();
recyclerView.setLayoutManager(new GridLayoutManager(this,3));
}
private void dispalyData() {
sqLiteDatabase=dBmain.getReadableDatabase();
Cursor cursor=sqLiteDatabase.rawQuery("select *from "+IMAGETABLE+"",null);
ArrayList<Model>arrayList=new ArrayList<>();
while (cursor.moveToNext()){
int id=cursor.getInt(0);
byte[]avatar=cursor.getBlob(1);
String name=cursor.getString(2);
arrayList.add(new Model(id,avatar,name));
}
cursor.close();
myadater=new Adapter(this,R.layout.singledata,arrayList,sqLiteDatabase);
recyclerView.setAdapter(myadater);
}
private void findId() {
recyclerView=findViewById(R.id.rv);
}
}
Lastly, we will see at the outputs what see like.
The output looks like the screenshot below.
Note:-If you have any queries regarding this tutorial or any tutorial, then feel free to contact us.