Wednesday, December 14, 2016

Best Inspirational Story I have ever read..

Story of Life..

There was once a man who got lost in the desert. The water in his flask ran out two days ago, and he was on his last legs. He knew that if he didn't get some water soon, he would surely perish. The man saw a shack ahead of him. He thought it might be a mirage or hallucination, but having no other option, he moved toward it. As he got closer he realized it was quite real, so he dragged his weary body to the door with the last of his strength.
The shack was not occupied and seemed like it had been abandoned for quite some time. The man gained entrance, hoping against hope that he might find water inside.His heart skipped a beat when he saw what was in the shack: a water pump..It had a pipe going down through the floor, perhaps tapping a source of water deep under-ground.
He began working the pump, but no water came out. He kept at it and still nothing happened. Finally he gave up from exhaustion and frustration. He threw up his hands in despair. It looked as if he was going to die after all.Then the man noticed a bottle in one corner of the shack. It was filled with water and corked up to prevent evaporation.
He uncorked the bottle and was about to gulp down the sweet life-giving water when he noticed a piece of paper attached to it. Handwriting on the paper read: "Use this water to start the pump. Don't forget to fill the bottle when you're done."
He had a dilemma. He could follow the instruction and pour the water into the pump, or he could ignore it and just drink the water.What to do? If he let the water go into the pump, what assurance did he have that it would work? What if the pump malfunctioned? What if the pipe had a leak? What if the underground reservoir had long dried up?
But then... maybe the instruction was correct. Should he risk it? If it turned out to be false, he would be throwing away the last water he would ever see.Hands trembling, he poured the water into the pump. Then he closed his eyes, said a prayer, and started working the pump.He heard a gurgling sound, and then water came gushing out, more than he could possibly use. He luxuriated in the cool and refreshing stream. He was going to live!
After drinking his fill and feeling much better, he looked around the shack. He found a pencil and a map of the region. The map showed that he was still far away from civilization, but at least now he knew where he was and which direction to go.
He filled his flask for the journey ahead. He also filled the bottle and put the cork back in. Before leaving the shack, he added his own writing below the instruction: "Believe me, it works!"
This story is all about life. It teaches us that we must give before we can receive abundantly. More importantly, it also teaches that faith plays an important role in giving. The man did not know if his action would be rewarded, but he proceeded regardless. Without knowing what to expect, he made a leap of faith. Water in this story represents the good things in life. Something that brings a smile to your face. It can be intangible knowledge or it can represent money, love, family, friendship, happiness, respect, or any number of other things you value. Whatever it is that you would like to get out of life, that's water.
The water pump represents the workings of the karmic mechanism. Give it some water to work with, and it will return far more than you put in.

Tuesday, December 6, 2016

Application level shared preference

A single class of shared preference which can store any type of data and objects at application level.

Example Code :

Shared Prefrence Class.

public class AppSharedPrefs
{

    private static AppSharedPrefs sharedPrefs = null;
    private SharedPreferences sf;


    public AppSharedPrefs(Context context)
    {
        sf = context.getSharedPreferences("key_shared_preference", Context.MODE_PRIVATE);
    }

    public static AppSharedPrefs getInstance(Context context)
    {
        if(sharedPrefs == null)
        {
            sharedPrefs = new AppSharedPrefs(context);
        }

        return sharedPrefs;
    }


    public Object get(String key)
    {
        Map<String, ?> map = sf.getAll();
        return map.get((String)key);
    }


    public void put(String key, Object value)
    {
        SharedPreferences.Editor edit = sf.edit();

        if(value == null)
        {
            edit.putString(key, null);
        }
        else if(value instanceof Boolean)
        {
            edit.putBoolean(key, (boolean)value);
        }
        else if(value instanceof Float)
        {
            edit.putFloat(key, (float)value);
        }
        else if(value instanceof Integer)
        {
            edit.putInt(key, (int)value);
        }
        else if(value instanceof Long)
        {
            edit.putLong(key, (long) value);
        }
        else if(value instanceof String)
        {
            edit.putString(key, (String)value);
        }
       else if(value instanceof  Model)
        {
            edit.putString(key, (Model)value);
        }
        else if(value instanceof Set)
        {
            edit.putStringSet(key, (Set)value);
        }

        edit.commit();
    }

    public void clearAll()
    {
        sf.edit().clear().commit();
    }

    public void clear(String key)
    {
        sf.edit().remove(key).commit();
    }
}


store various type of data in shared preference from any class as shown below.

public class RegisterActivity extends AppCompatActivity {

    private AppSharedPrefs sharedPrefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        //initialise shared prefs manager
        sharedPrefs = AppSharedPrefs.getInstance(RegisterActivity.this);

        sharedPrefs.put("KeyName", "Zafar Imam");//stroing string value
        sharedPrefs.put("KeyAge", 24); //storing integer value
        sharedPrefs.put("IsRegister", true); //storing boolean value

        ModelClass model = new ModelClass();
        model.setFirstName("Zafar");
        model.setLastName("Imam");
        model.setRollNumber(512);

        //here you can store object of model class inside prefrence to transfer from one class to other
        sharedPrefs.put("Key_Serializable_Object", model);

    }
}

Model class of getter and setter: 

public class ModelClass implements Serializable {

    private String firstName;
    private String lastName;
    private int rollNumber;

    public int getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

Get the data from shared preference in other class as :


public class ProfileActivity extends AppCompatActivity {
    ModelClass modelClass;
    private AppSharedPrefs sharedPrefs;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);

        //initialise shared prefs manager
        sharedPrefs = AppSharedPrefs.getInstance(ProfileActivity.this);

        Boolean isRegister = (Boolean) sharedPrefs.get("IsRegister");//getting stored data

        String name = (String) sharedPrefs.get("KeyName");//getting stored data

        int age = (Integer) sharedPrefs.get("KeyAge");//getting stored data

         modelClass = (ModelClass) sharedPrefs.get("Key_Serializable_Object");//getting object 

        if (isRegister){

            String firstName = modelClass.getFirstName();
            int rollNumber = modelClass.getRollNumber();
        }

    }
}

Note: for transferring Object from one class to other class, respected class(like ModelClass) must have implemented Serializable or Parcelable interface.

Wednesday, March 30, 2016

Out of memory in Android Studio

Hi,
I am here with the solution of an error of Android Studio which i faced today and a lot of time and energy of mine, So i am publishing this for all of you so that you could not face problem like me.

Out of memory Error.

Screen shot of the error is as follows :


To Solve this error you just need to go to : 
/Applications/Android\ Studio.app/Contents/bin/studio.vmoptions and increase MaxPermSize as per your requirement as shown below.
-Xms128m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops

Friday, March 25, 2016

Change or Replace Fragments Inside ViewPager

MainActivity.java

package android.zafar.viewpager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;

/**
 * Example about replacing fragments inside a ViewPager. I'm using
 * android-support-v7 to maximize the compatibility.
 *
 * @author Zafar Imam
 *
 */
public class MainActivity extends ActionBarActivity {

// For this example, only two pages
static final int NUM_ITEMS = 2;

ViewPager mPager;
SlidePagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/* Instantiate a ViewPager and a PagerAdapter. */
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new SlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);

}

/* PagerAdapter class */
public class SlidePagerAdapter extends FragmentPagerAdapter {
public SlidePagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}

@Override
public int getCount() {
return NUM_ITEMS;
}
}


}

Then Create Three different Fragments As :

FirstFragemt.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {

private static final String TAG = "FirstFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.first_fragment, container, false);

Button btn = (Button) view.findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());

/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);

trans.commit();
}
});

return view;
}


}

SecondFragment .java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;


public class SecondFragment extends Fragment {

private static final String TAG = "SecondFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater
.inflate(R.layout.second_fragment, container, false);

Button btn = (Button) view.findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
trans.replace(R.id.root_frame, new StaticFragment());
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});

return view;
}


}


StaticFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class StaticFragment extends Fragment {

private static final String TAG = "StaticFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater
.inflate(R.layout.static_fragment, container, false);

return view;
}

}

Then create a root fragment which contains Framelayout as

RootFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class RootFragment extends Fragment {

private static final String TAG = "RootFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment, container, false);

FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, new FirstFragment());

transaction.commit();

return view;
}

}


Now create the respected layout files for each one as : 

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#d6b90512"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:textColor="#fff"
        android:text="Fragmet One" />
    <Button 
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:text="@string/to_second_fragment"/>

</RelativeLayout>



second_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d6b90512">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:text="Fragment Second" />
    <Button 
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:text="@string/to_static_fragment"/>

</RelativeLayout>



static_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#d6b90512"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:text="Static Fragment" />

</RelativeLayout>


root_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#000"
    android:layout_height="match_parent"
    android:id="@+id/root_frame" >

</FrameLayout>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.zafar.viewpager"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar" >
        <activity
            android:name="com.pineappslab.frcontainer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Output Screen Shots :







Friday, March 11, 2016

Progress Bar with Custom Color

Create one xml folder in layout and put the my_progress.xml file in it .

my_porgress.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360">
    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false">
        <size
            android:width="76dip"
            android:height="76dip" />
        <gradient
            android:angle="0"
            android:endColor="#447a29"
            android:startColor="#447a29"
            android:type="sweep"
            android:useLevel="false" />
    </shape>
</rotate>

Set startColor and endColor as per your choice and 
Create a progress bar insile your main layout as 

<ProgressBar
  android:id="@+id/ProgressBar01" 
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background ="@layout/my_progress">


Thursday, March 10, 2016

WebView or WebViewClient with Fragment

package zafar.learnandroid.webviewdemo;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainFragmentActivity extends Fragment {
 WebView myWebView;
 final static String myBlogAddr = "http://learnandroidwithzafar.blogspot.in";
 String myUrl;
 public MainFragmentActivity() {
    }
 @SuppressLint("SetJavaScriptEnabled")
 @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_blog, container, false);
        myWebView = (WebView) view.findViewById(R.id.home_webview);

        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new MyWebViewClient());

        if (myUrl == null) {
            myUrl = myBlogAddr;
        }
        myWebView.loadUrl(myUrl);
        return view;
    }
private class MyWebViewClient extends WebViewClient {
@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {
            myUrl = url;
            view.loadUrl(url);
            return true;
        }
   }
}
Now Create xml layout as :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:id="@+id/home_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>
Note: Don't Forget to give Internet permission in manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

Screenshot