How to get today’s exact day and 1 day ago ?

Hey,
Joda Time library provides us almost every situation of date-time components.
Firstly, add this library to your :
// Joda Time
compile 'net.danlew:android.joda:2.9.5.1'
Markdown:
// Get the today's time as start of the day : 06:00:00
DateTime startTime = new DateTime().withHourOfDay(6).withMinuteOfHour(0).withSecondOfMinute(0);
Gist:
// Get the today's time as start of the day : 06:00:00
DateTime startTime = new DateTime().withHourOfDay(6).withMinuteOfHour(0).withSecondOfMinute(0);

How to stop refreshing fragments on tab is changed?

Hey,
Sometimes fragment tabs are just pain.. They just reload each tab changes and it causes the lag and screen frozen. Fortunately, solution is simple :)
Markdown:
int limit = (mSectionsPagerAdapter.getCount() > 1 ? mSectionsPagerAdapter.getCount() - 1 : 1);
mViewPager.setOffscreenPageLimit(limit);
Gist:
/* DO NOT FORGET! The ViewPager requires at least “1” minimum OffscreenPageLimit */
int limit = (mSectionsPagerAdapter.getCount() > 1 ? mSectionsPagerAdapter.getCount() - 1 : 1);
mViewPager.setOffscreenPageLimit(limit);

We just set the setOffscreenPageLimit through the ViewPager..
DO NOT FORGET! The ViewPager requires at least “1” minimum OffscreenPageLimit.
The limit variable algorithm is simple. That’s it :)
Have fun, If you have any question, ask me !

How to convert Bitmap to Uri?

Working on Bitmap is so popular on Android, sometimes we need to play on Bitmap object and here is how to convert Bitmap to Uri :)
Updated & Working Kotlin Version
Markdown:
fun getImageUriFromBitmap(context: Context, bitmap: Bitmap): Uri{
    val bytes = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(context.contentResolver, bitmap, "Title", null)
    return Uri.parse(path.toString())
 }
Gist:kotlin:
fun getImageUriFromBitmap(context: Context, bitmap: Bitmap): Uri{
    val bytes = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(context.contentResolver, bitmap, "Title", null)
    return Uri.parse(path.toString())
 }
So simple, so easy :)
If you have any question, ask me!
Have fun!

How to get Real Path from Uri?

Hey,
If you had a headache to get the real path for your file like me, don’t worry! I have your medicine :)
Here is how to get real path of the file from Uri via MediaStore:
Markdown:
private String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
        return "";
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}


Gist:
 private String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
        return "";
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

How to extract filename from Uri?

Now, we can extract filename with and without extension :)
You will convert your bitmap to uri and get the real path of your file. Now we have a path.
Here is how to extract filename :
Markdown:
Uri uri = getImageUri(bitmap);
String path = getRealPathFromURI(uri);
String filename = path.substring(path.lastIndexOf("/")+1);
String file;
if (filename.indexOf(".") > 0) {
    file = filename.substring(0, filename.lastIndexOf("."));
} else {
    file =  filename;
}
Log.d(TAG, "Real Path: " + path);
Log.d(TAG, "Filename With Extension: " + filename);
Log.d(TAG, "File Without Extension: " + file);
Gist:
Uri uri = getImageUri(bitmap);
String path = getRealPathFromURI(uri);
String filename = path.substring(path.lastIndexOf("/")+1);
String fileWOExtension;
if (filename.indexOf(".") > 0) {
    fileWOExtension = filename.substring(0, filename.lastIndexOf("."));
} else {
    fileWOExtension =  filename;
}
Log.d(TAG, "Real Path: " + path);
Log.d(TAG, "Filename With Extension: " + filename);
Log.d(TAG, "File Without Extension: " + fileWOExtension);

How to convert timestamp to formatted date

Hey,
Converting timestamp is really simple to get the formatted date as you want. You just need to create a Calendar object and set your timestamp data on it.
Then you got the timestamp data into your calendar object and you can turn it as a string via “DateFormat.format” method.
Calendar cal = Calendar.getInstance(Locale.ENGLISH);cal.setTimeInMillis(timestamp);String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
Note: If your result always returns 1970, try this way :
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
You need to multiple your TS value by 1000 :)
It’s so easy to use it.
If you have a question, ask me :)


How to delay with a specific time

Hey,

I’m going to show you how to delay a method or a code segment on Android with a piece of code particle. It’s very easy and useable as you need.

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // Magic here
            }
        }, 1000); // Millisecond 1000 = 1 sec



First you need to create a Handler object and use its own method which is “postDelayed” and override the Runnable object’s run method. If you need a specific time to delay like 1000 millisecond (1 second), this method is great to use.
Important Note : After using this postdelayed method, never forget to stop runnable and more importantly, NEVER use it for UI Staff. Otherwise, your UI or your whole app may crash. Thank you Wayne May for this note.

How to save and get HashMap into SharedPreference

Hey,
I’m gonna show you how to save and get HashMap into SharedPreference. It is the same logic as How to save and get ArrayList into SharedPreference.
Markdown:
/**
     *     Save and get HashMap in SharedPreference
     */

    public void saveHashMap(String key , Object obj) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(obj);
        editor.putString(key,json);
        editor.apply();     // This line is IMPORTANT !!!
    }


    public HashMap<Integer,YourObject> getHashMap(String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key,"");
        java.lang.reflect.Type type = new TypeToken<HashMap<Integer,YourObject>>(){}.getType();
        HashMap<Integer,YourObject> obj = gson.fromJson(json, type);
        return obj;
    }
Gist:

    /**
     *     Save and get HashMap in SharedPreference
     */

    public void saveHashMap(String key , Object obj) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(obj);
        editor.putString(key,json);
        editor.apply();     // This line is IMPORTANT !!!
    }


    public HashMap<Integer,YourObject> getHashMap(String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key,"");
        java.lang.reflect.Type type = new TypeToken<HashMap<Integer,YourObject>>(){}.getType();
        HashMap<Integer,YourObject> obj = gson.fromJson(json, type);
        return obj;
    }

First of all, we can use this save method as many as we need. You just need to change the key and save it into the SharedPreference.
You just need to be careful about your HashMap’s types. I just use “Integer, Object” as an example. You can change it and use your own Object, or even use String, Double etc. It’s all up to your need.
Do not forget to change your own HashMap type while using it :)
If you have a question, ask me :)

How to save and get ArrayList into SharedPreference

Hey,
I’m gonna show you very basic but useful way to save and get ArrayList from SharedPreference.
Markdown:
    /**
     *     Save and get ArrayList in SharedPreference
     */

    public void saveArrayList(ArrayList<String> list, String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!
    }

    public ArrayList<String> getArrayList(String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        return gson.fromJson(json, type);
    }
Gist:

    /**
     *     Save and get ArrayList in SharedPreference
     */

    public void saveArrayList(ArrayList<String> list, String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!
    }

    public ArrayList<String> getArrayList(String key){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        return gson.fromJson(json, type);
    }

We have two methods to save and get ArrayList from SharedPreference. First, we need to save our ArrayList, we have two parameters which are our own ArrayList and our key. We need to get that key as a parameter because it lets us to use this method more than one ArrayList. Therefore, we won’t need to write one than one Shared method to save each array. We just need to change key’s name and save that arraylist as a new one.
Second, we just need the same key to get and return that ArrayList from SharedPreference. Actually this is so simple because GSON makes the whole job for us.
Actually this method did not save your ArrayList as itself, it converts the ArrayList to the JSON format and when you want to get it, you just re-convert to the ArrayList.
Ta-daa :P That’s it, so simple so elegant :P

GSON Library

If you’re getting error for GSON. Here is how to solve it. You need to implement the GSON library from Google.
dependencies {        implementation 'com.google.code.gson:gson:2.8.5'}
If you have question, ask me :)

Retrofit GET Example

I’m going to show an basic example on usage of Retrofit. Retrofit lets you amazing simple and clean GET and POST methods. You do not need long and complex asynchronous task in Android anymore :O

1. ApiInterface



First we need to create an interface which names it as ApiInterface.


public interface ApiInterface {

    @GET("user/{Id}")
    Call<List<User>> userData(@Path("Id") String Id);

    
}

2. ApiClient

Second, we need to create an ApiClient class to determine our BASE URL.

public class ApiClient {

    public final static String BASE_URL = "https://api.github.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}


3. Get Data from Server

Now, we will send the specific user id from the server to get its data.
Firstly, we use our ApiInterface to create an ApiClient service. After that, we have to use “Call” class to receive data from server and we will enqueue its call to use that data. in “onResponse” part. There is also an onFailure method to check your server and link works totally correct.
   
    public void getData(){
        // sends the user id 
        String user_id = "69";
        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<List<User> > call =
                apiService.userData(user_id);

        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                List<User> userInfo = response.body();
                for(int i = 0; i<userInfo.size(); i++){
                    // Magic here
                }
            }

            @Override
            public void onFailure(Call<List<Junction>> call, Throwable t) {
                Log.e("MyApp", "getData ERROR :" + t.toString());
            }
        });
    }

After using asynchronous task to use @GET and @POST methods, Retrofit is the new cure for me :) I’m a bit late to learn Retrofit but better than never :P
If you have any question, ask me :)

FreakyCoder Software Blog

Software Annotations

How to setup OSM

Hey,
I’m gonna show you how to initialize and setup OSM.
First we need to configure our build.gradle part.

Gradle

In your root build.gradle file, add mavenLocal() if not present.
allprojects {
    repositories {
            mavenCentral()
            mavenLocal()    //add this if it's missing
    }
}
Then, add OSM’s gradle link :
compile 'org.osmdroid:osmdroid-android:5.5-SNAPSHOT:debug@aar'

Manifest

In most cases, you will have to set the following authorizations in your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
OSM wants these user permissions, we have to add these on our Manifest

Layout

Create a “src/main/res/layouts/main.xml” layout like this one. With Android Studio, it probably created one already called. The default is “src/main/res/layouts/activity_main.xml”:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <org.osmdroid.views.MapView android:id="@+id/map"
                android:layout_width="fill_parent" 
                android:layout_height="fill_parent" />
</LinearLayout>
Note: It does not have to be LinearLayout, you can use whatever layout you want

Main Activity

After we configure OSM, we need to initialize our OSM map in @onCreate method:
 public class MainActivity extends Activity {
        @Override public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            MapView mMapView = (MapView) findViewById(R.id.map);


            // OSM Map Initialize
            //important! set your user agent to prevent getting banned from the osm servers
            org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants.setUserAgentValue(BuildConfig.APPLICATION_ID);
            mMapView.setTileSource(TileSourceFactory.MAPNIK);
            // Setup MapView
            setupMapView();
        }
    }

Setup OSM Method

After we’ve done onCreate method, we need to determine our map’s properties such as; zoom buttons, multi touch control, default zoom and default point.
As you can see the last two (2) lines of code setting the default map’s coordinates.
 // Setup the mapView controller:
    public void setupMapView(){
        // Zoom buttons
        mMapView.setBuiltInZoomControls(true);
        // Multitouch Controls Activation
        mMapView.setMultiTouchControls(true);
        mMapView.setClickable(true);
        // Default map zoom level:
        //private int MAP_DEFAULT_ZOOM = 20;
        mMapView.getController().setZoom(MAP_DEFAULT_ZOOM);
        // Default Point
        GeoPoint startPoint = new GeoPoint(37779300, -122419200);
        mMapView.getController().setCenter(startPoint);
    }

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...