Showing posts with label Android. Show all posts

Example of Firebase.push() in Java.

Google firebase push

Prerequisite


Push
Add to a list of data in the database. Every time you push a new node onto a list, your database generates a unique key, like items/<unique-item-id>/<data>

Push is basically used when you have collection of data like items, users, notifications and you want to generate unique id for each record in collection.

In previous example we've seen How to save data in Firebase?, It saves data as you provided within given path where push will generate unique id as root node of your data.

Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Source code (FirebasePushObject.java)
package com.javaquery.google.firebase;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.javaquery.bean.Item;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;

/**
 * Example of Firebase push.
 *
 * @author javaQuery
 * @date 22nd September, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class FirebasePushObject {
    
    public static void main(String[] args) {
        Item item = new Item();
        item.setId(1L);
        item.setName("MotoG");
        item.setPrice(100.12);
        
        // You can use List<Item> also.
        new FirebasePushObject().saveUsingPush(item);
    }
    
    private FirebaseDatabase firebaseDatabase;

    /**
     * initialize firebase.
     */
    private void initFirebase() {
        try {
            // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.
            // .setServiceAccount(new FileInputStream(new File("filepath"))) - Firebase private key file path.
            FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                    .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                    .setServiceAccount(new FileInputStream(new File("C:\\Users\\Vicky\\Documents\\NetBeansProjects\\Examples\\src\\com\\javaquery\\google\\firebase\\Firebase-30f95674f4d5.json")))
                    .build();

            FirebaseApp.initializeApp(firebaseOptions);
            firebaseDatabase = FirebaseDatabase.getInstance();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Save item object in Firebase.
     * @param item 
     */
    private void saveUsingPush(Item item) {
        if (item != null) {
            initFirebase();
            
            /* Get database root reference */
            DatabaseReference databaseReference = firebaseDatabase.getReference("/");
            
            /* Get existing child or will be created new child. */
            DatabaseReference childReference = databaseReference.child("items");

            /**
             * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting.
             * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value
             * using `countDownLatch.countDown()` and application will continues its execution.
             */
            CountDownLatch countDownLatch = new CountDownLatch(1);
            
            /**
             * push()
             * Add to a list of data in the database. Every time you push a new node onto a list, 
             * your database generates a unique key, like items/unique-item-id/data
             */
            childReference.push().setValue(item, new DatabaseReference.CompletionListener() {

                @Override
                public void onComplete(DatabaseError de, DatabaseReference dr) {
                    System.out.println("Record saved!");
                    // decrement countDownLatch value and application will be continues its execution.
                    countDownLatch.countDown();
                }
            });
            try {
                //wait for firebase to saves record.
                countDownLatch.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Output
Record saved!
Check Database in Firebase console.



How to save data in Firebase?

Firebase + Google

Prerequisite


Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Source code (FirebaseSaveObject.java)
package com.javaquery.google.firebase;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.javaquery.bean.Item;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;

/**
 * Example of Firebase save.
 *
 * @author javaQuery
 * @date 7th September, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class FirebaseSaveObject {

    public static void main(String[] args) {
        Item item = new Item();
        item.setId(1L);
        item.setName("MotoG");
        item.setPrice(100.12);

        // save item objec to firebase.
        new FirebaseSaveObject().save(item);
    }

    private FirebaseDatabase firebaseDatabase;

    /**
     * initialize firebase.
     */
    private void initFirebase() {
        try {
            // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.

            // Firebase private key(Generated while creating service account) file path.
            // .setServiceAccount(new FileInputStream(new File("filepath")))
            FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                    .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                    .setServiceAccount(new FileInputStream(new File("filepath\30f95674f4d5.json")))
                    .build();

            FirebaseApp.initializeApp(firebaseOptions);
            firebaseDatabase = FirebaseDatabase.getInstance();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Save item object in Firebase.
     * @param item 
     */
    private void save(Item item) {
        if (item != null) {
            initFirebase();
            
            /* Get database root reference */
            DatabaseReference databaseReference = firebaseDatabase.getReference("/");
            
            /* Get existing child or will be created new child. */
            DatabaseReference childReference = databaseReference.child("item");

            /**
             * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting.
             * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value
             * using `countDownLatch.countDown()` and application will continues its execution.
             */
            CountDownLatch countDownLatch = new CountDownLatch(1);
            childReference.setValue(item, new DatabaseReference.CompletionListener() {

                @Override
                public void onComplete(DatabaseError de, DatabaseReference dr) {
                    System.out.println("Record saved!");
                    // decrement countDownLatch value and application will be continues its execution.
                    countDownLatch.countDown();
                }
            });
            try {
                //wait for firebase to saves record.
                countDownLatch.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Output
Record saved!
Check Database in Firebase console.

Non-Android Runtimes
https://www.firebase.com/docs/android/guide/saving-data.html#section-other-runtimes
The Firebase Java client does not require the Android Runtime and can be used in any Java Runtime, including server-side Java processes or Java desktop applications.

The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting. When running on a non-Android runtime we may need to take extra steps to make sure that data is written to the server before our process exits. We can attach a CompletionListener to write operations and use a Semaphore or CountDownLatch object to prevent the process from exiting, as shown in the example below.

Reference
If you have collection of data to save in Firebase then you might me interested in reading Firebase.push(). - Example of Firebase.push() in Java.

How to get Latitude - Longitude without GPS in mobile device?

radar

What is GPS?
GPS stands for Global Positioning System. Its a hardware used to get the accurate location of device. It gives the Latitude - Longitude of the device.

What if there ain't GPS?
You might used Google Maps in non GPS device. They are still able to get the perfect location of your device. So we'll look into that situation how they target the mobile device. All you need is get below details from mobile device.

1. Mobile Country Code (MCC) - To detect current country of device.
2. Mobile Network Code (MNC)- Te delete current service provide.
3. Local Area Code (LAC)- To detect device in which region.
4. Cell ID - Unique id of that region.

I created GeoLocation class in javaQuery API 8.1 . I'm using free service to get the latitude and longitude. Sometime you may get 0.0 for Latitude and Longitude. It says that there is no record available for that details. This API is for testing purpose. If you are creating the paid application or Official application, buy service to get the latitude and longitude using mcc, mnc, lac and cellid. Let's take a look at code snippet.
/*
 * MAPTargetByMobile(int, int, int, int);
 * MAPTargetByMobile(mcc, mnc, lac, cellid);
 * It'll only give you Latitude and Longitude
*/
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;

public class Demo {
    public static void main(String[] args) throws IOException{
        GeoLocation Target = javaQueryBundle.createGeoLocation();
        Target.MAPTargetByMobile(404, 58, 1339, 9029);
        System.out.println(Target.Latitude);
        System.out.println(Target.Longitude);
    }
}
Now what next? 
Use Google Maps to get location of mobile device using Latitude and Longitude.

Related Article:
How to create mobile tracking application? [http://www.javaquery.com/2011/09/how-to-create-mobile-tracking.html]

How to download file with Progress bar in Android?

Today in this tutorial I'm going to demonstrate the file download example in Android. I've Googled everything about it. There are examples available on the Internet. However you'll find some difficulties when you integrate in your code. So lets see how they implemented...

Source Code (ContextBean.java)
ContextBean used to access application context in any class.
import android.content.Context;
/*
 * This will help you to use application context in any file with in project.
 */
public final class ContextBean {
  private static Context localContext;
  public static Context getLocalContext() {
        return localContext;
  }
  public static void setLocalContext(Context localContext) {
        ContextBean.localContext = localContext;
  }
}

Source Code (MainActivity Class)
//In your main activity file.
protected void onCreate(Bundle savedInstanceState) {
...
ContextBean.setLocalContext(getApplicationContext());
...
}

Source Code (DownloadFile.java)
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;

public final class DownloadFile extends AsyncTask {
      // Progress Dialog
      private ProgressDialog pDialog;
       // Progress dialog type (0 - for Horizontal progress bar)
       public static final int progress_bar_type = 0;
       private Activity mainActivity = null;
       private Context mainContext = null;

       public DownloadFile(Activity a,Context c){
        this.mainActivity = a;
        this.mainContext = c;
        pDialog = new ProgressDialog(mainContext);
       }
       protected void onPreExecute() {
        super.onPreExecute();
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(false);
        pDialog.show();
       }
       @Override
       protected String doInBackground(String... params) {
              int count;
              try {
               URL url = new URL(params[0]);
               URLConnection conection = url.openConnection();
               conection.connect();
               // this will be useful so that you can show a typical 0-100%
               int lenghtOfFile = conection.getContentLength();
               // download the file
               InputStream input = new BufferedInputStream(url.openStream(),8192);
               /* Output stream
                * Folder path : http://www.javaquery.com/2013/06/how-to-get-data-directory-path-in.html
                */
               String dataDirPath = ContextBean.getLocalContext().getPackageManager().getPackageInfo(
                 ContextBean.getLocalContext().getPackageName(), 0).applicationInfo.dataDir;
               OutputStream output = new FileOutputStream(dataDirPath);
               byte data[] = new byte[1024];
               long total = 0;
               while ((count = input.read(data)) != -1) {
                      total += count;
                      // publishing the progress....
                      // After this onProgressUpdate will be called
                      publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                      // writing data to file
                     output.write(data, 0, count);
               }
               output.flush();
               output.close();
               input.close();
              } catch (Exception e) {
               Log.w("Your_Tag","Download Error", e);
              }
        return null;
       }
       /**
        * Updating progress bar
        * */
       protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        this.pDialog.setProgress(Integer.parseInt(progress[0]));
       }
       /**
        * After completing background task Dismiss the progress dialog
        * **/
       @SuppressWarnings("deprecation")
       @Override
       protected void onPostExecute(String file_url) {
              // dismiss the dialog after the file was downloaded
              pDialog.dismiss();
              AlertDialog alertDialog = new AlertDialog.Builder(mainActivity).create();
              // Setting Dialog Title
              alertDialog.setTitle("Title of Box");
              // Setting Dialog Message
              alertDialog.setMessage("Download Complete");
              // Setting OK Button
              alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog,
                 final int which) {
               }
              });
              // Showing Alert Message
              alertDialog.show();
       }
}

Now let see how you can access the class. You can use this class with on click event , Menu item click event, etc... It depends on you how you want to access. I'm accessing this class in Main Activity with
protected void onCreate(Bundle savedInstanceState) {...}
/*
 * You have to pass Activity and Context of the application to class
 * this : Activity (1st)
 * this : Context (2nd)
 */
DownloadFile objDownloadFile = new DownloadDatabase(this, this);
objDownloadFile.execute("http://www.example.com/abc.mp3");
Sometime you may got the exception Cannot execute task : the task has already been executed. Its because if you are dealing with AsyncTask . Its one time use class with one Object/Instance.

Solution
Create new object every time if you want to use DownloadFile.java more than one time.

How to get data directory path in Android?

What is data directory in Android?
Android generates private directory on Internal Memory for each application installed on device. Its not accessible using any explorer until the device is rooted. This private directory allocated to store important files for your application. Path of private directory is like /data/data/com.example.application.

Source Code (ContextBean.java)
ContextBean used to access application context in any class.
import android.content.Context;
/*
 * This will help you to use application context in any file with in project.
 */
public final class ContextBean {
  private static Context localContext;
  public static Context getLocalContext() {
   return localContext;
  }
  public static void setLocalContext(Context localContext) {
   ContextBean.localContext = localContext;
  }
}

Source Code (MainActivity Class)
//In your main activity file.
protected void onCreate(Bundle savedInstanceState) {
...
ContextBean.setLocalContext(getApplicationContext());
...
}

Source Code (CommonUtil.java)
Now create CommonUtil.java (change class name as you wish). That will return the Data Directory path in String. This code also has the code to get the Application path on External Storage.
import android.os.Environment;
import android.util.Log;
public class CommonUtil {
  public String getDataDir() {
              try {
     return ContextBean.getLocalContext().getPackageManager().getPackageInfo(
      ContextBean.getLocalContext().getPackageName(), 0).applicationInfo.dataDir;
       } catch (Exception e) {
     Log.w("Your Tag", "Data Directory error:", e);
     return null;
              }
  }
  // read more about Environment class : http://developer.android.com/reference/android/os/Environment.html
  public String getDownloadFolder() {
    return ContextBean.getLocalContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
   .toString();
  }
}

getDownloadFolder() method gives you the path /Android/data/package_name/files/Downloads. You can change the path as per your requirement like...
  • DIRECTORY_ALARMS
  • DIRECTORY_DCIM
  • DIRECTORY_DOWNLOADS
  • DIRECTORY_MOVIES
  • DIRECTORY_MUSIC
  • DIRECTORY_NOTIFICATIONS
  • DIRECTORY_PICTURES
  • DIRECTORY_PODCASTS
  • DIRECTORY_RINGTONES

Source Code
CommonUtil objCommonUtil = new CommonUtil();
String path_to_data = objCommonUtil.getDataDir();

For further enhancement read developers guide: http://developer.android.com/guide/topics/data/data-storage.html

How to zip align your android application?

Its first time i was working around android application. I created application for my blog feed. Its working fine in my device and other as well. I was uploading my application to Google Developer Console and got the error...
You uploaded an APK that is not zip aligned. You will need to run a zip align tool on your APK and upload it again.
Error states you have to bind the application using android sdk.

Solution
Step 1: Copy your .apk file in Tools folder of Android SDK. Tools folder in my computer.(i.e: E:\Software\adt-bundle-windows-x86\adt-bundle-windows-x86\sdk\tools)

Step 2: Open command prompt and navigate to folder tools.

Step 3: Execute following command zipalign.exe -v 4 my.apk output.apk

Now you are ready to upload your .apk file to Google Developer Console.