In this example we are going to see how we can insert and view data with image in firebase console.
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="com.example.malik.malikhimani.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="browseImages"
android:text="Browse Image" />
<ImageView
android:id="@+id/insertImages"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@mipmap/ic_launcher" />
<EditText
android:id="@+id/insertName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name" />
<EditText
android:id="@+id/insertEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="uploadData"
android:text="Upload Data" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="viewAllData"
android:text="View All Data" />
</LinearLayout>
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="com.example.malik.malikhimani.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="browseImages"
android:text="Browse Image" />
<ImageView
android:id="@+id/insertImages"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@mipmap/ic_launcher" />
<EditText
android:id="@+id/insertName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name" />
<EditText
android:id="@+id/insertEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="uploadData"
android:text="Upload Data" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="viewAllData"
android:text="View All Data" />
</LinearLayout>
MainActivity.java
package com.example.malik.malikhimani;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
EditText name, email;
private StorageReference storageReference;
private DatabaseReference databaseReference;
public static final String STORAGE_PATH = "images/";
public static final String DATABASE_PATH = "mainObject";
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.insertImages);
name = (EditText) findViewById(R.id.insertName);
email = (EditText) findViewById(R.id.insertEmail);
storageReference = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference(DATABASE_PATH);
}
public void browseImages(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"),0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == RESULT_OK){
imageUri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getActualImage(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
public void uploadData(View view){
if(imageUri != null){
// insert data
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference reference = storageReference.child(STORAGE_PATH + System.currentTimeMillis() + "." + getActualImage(imageUri));
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String NAME = name.getText().toString();
String EMAIl = email.getText().toString();
Person person = new Person(NAME,EMAIl,taskSnapshot.getDownloadUrl().toString());
String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(person);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Data uploaded",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@SuppressWarnings("VisibleForTests")
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double totalProgress = (100*taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded % " + (int)totalProgress);
}
});
} else {
// show message
Toast.makeText(getApplicationContext(),"Please select data first",Toast.LENGTH_LONG).show();
}
}
public void viewAllData(View view){
Intent intent = new Intent(MainActivity.this, ViewDataActivity.class);
startActivity(intent);
}
}
data_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/getImages"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/getName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Name here"
android:textSize="22sp" />
<TextView
android:id="@+id/getEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Email here"
android:textSize="22sp" />
</LinearLayout>
Person.java
package com.example.malik.malikhimani;
/**
* Created by malik on 30/10/2017.
*/
public class Person {
String name;
String email;
String imageUri;
public Person(String name, String email, String imageUri) {
this.name = name;
this.email = email;
this.imageUri = imageUri;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
}
MyAdapter.java
package com.example.malik.malikhimani;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
/**
* Created by malik on 30/10/2017.
*/
public class MyAdapter extends ArrayAdapter<Person> {
Activity activity;
int resource;
List<Person> list;
public MyAdapter(Activity activity, int resource, List<Person> list) {
super(activity, resource,list);
this.activity = activity;
this.resource = resource;
this.list = list;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
View view = layoutInflater.inflate(resource,null);
ImageView imageView = (ImageView) view.findViewById(R.id.getImages);
TextView name = (TextView) view.findViewById(R.id.getName);
TextView email = (TextView) view.findViewById(R.id.getEmail);
name.setText(list.get(position).getName());
email.setText(list.get(position).getEmail());
Glide.with(activity).load(list.get(position).getImageUri()).into(imageView);
return view;
}
}
activity_view_data.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="com.example.malik.malikhimani.ViewDataActivity">
<ListView
android:id="@+id/list1"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
ViewDataActivity.java
package com.example.malik.malikhimani;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ViewDataActivity extends AppCompatActivity {
ListView listView;
List<Person> list;
ProgressDialog progressDialog;
MyAdapter myAdapter;
private DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
listView = (ListView) findViewById(R.id.list1);
list = new ArrayList<>();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Fetching Please wait");
progressDialog.show();
databaseReference = FirebaseDatabase.getInstance().getReference(MainActivity.DATABASE_PATH);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
list.clear();
for(DataSnapshot snap : dataSnapshot.getChildren()){
Person person = snap.getValue(Person.class);
list.add(person);
}
myAdapter = new MyAdapter(ViewDataActivity.this,R.layout.data_items,list);
listView.setAdapter(myAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.malik.malikhimani">
<application
android: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>
<activity android:name=".ViewDataActivity"></activity>
</application>
</manifest>
build(module app).gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.example.malik.malikhimani"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
compile 'com.github.bumptech.glide:glide:3.8.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
build(Project).gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}