Tuesday, 19 January 2016

Navigate to particular app in play store in android programatically?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=you package name"));
startActivity(intent);

Wednesday, 13 January 2016

sample JSON file Writing and Reading from that file in android

Sample JSON File which is stored in internal memory 

{"STUDENTS":
       [
           {"SID":"123","NAME":"mahesh","ADDRESS":
                                                                     {"STREET":"4-      4","VILLAGE":"velgodu"}
            }
        ]
}


Similar file  in XML for above json:

<STUDENTS>
    <STUDENT>
       <SID>123</SID>
       <NAME>mahesh</NAME>
       <ADDRESS>
           <STREET>4-4</STREET>
           <VILLAGE>velgodu</VILLAGE>    
       </ADDRESS>
     </STUDENT>
</STUDENTS>



Write into internal memory:

    public void write(View v)
    {
         JSONObject obj=new JSONObject();
   
         JSONArray arr=new JSONArray();
   
    try
    {
          JSONObject objsid=new JSONObject();
        objsid.put("SID", "123");
            objsid.put("NAME", "mahesh");
       
        JSONObject objadd=new JSONObject();
            objadd.put("STREET", "4-4");
        objadd.put("VILLAGE", "velgodu");
     
        objsid.put("ADDRESS", objadd);
       
            arr.put(objsid);
       
           obj.put("STUDENTS", arr);
       
        FileWriter write=new FileWriter("storage/sdcard0/jsontext.txt");
        write.write(obj.toString());
           write.flush();
           write.close();
}
     catch (Exception e)
    {
}
}


OUTPUT:

You can see this file in the local storage   in following location     storage/sdcard0/jsontext.txt

{"STUDENTS":
       [
           {"SID":"123","NAME":"mahesh","ADDRESS":
                                                                     {"STREET":"4-      4","VILLAGE":"velgodu"}
            }
        ]
}


Reading JSON File:

 public void read(View v)
 {
    try
    {
    FileReader read=new FileReader("storage/sdcard0/jsontext.txt");
     
         int i=read.read();
    String msg="";
   
    while(i!=-1)
    {
    msg=msg+(char)i;  
    i=read.read();
    }
   
JSONObject obj=new JSONObject(msg);

    JSONArray arr=obj.getJSONArray("STUDENTS");

      int sid=0;
    String sname="";
    String address="";

    for (int j = 0; j  < arr.length(); j ++)
    {
JSONObject objsid=arr.getJSONObject(j);
sid=objsid.getInt("SID");
sname=objsid.getString("NAME");
address=objsid.getString("ADDRESS");

JSONObject objad=new JSONObject(address);
String street=objad.getString("STREET");
String vill=objad.getString("VILLAGE");
/ /Toast.makeText(getApplicationContext(), sid+"\n name:"+sname+"\n                                                   address:"+street+", "+vill, 2000).show();
}
   
}
    catch (Exception e)
    {
// TODO: handle exception
    }
}








Monday, 11 January 2016

Shared Preferences in Android

Shared Preferences is one of the storage method. By using this we can store the data in phone internal storage. when ever we need to store small/less size data then we can go for this concept.

--> We can access the SharedPreference data base using "getSharedPreferences" method. The following syntax is used to access the Shared Preference data.

SharedPreferences spf=activity.getSharedPreferences("Specify Your Own Database name",Context.MODE_PRIVATE);


---> If we need to do some modifications in above SharedPrefence, we can achieve with the help of   SharedPreferences.Editor


SharedPreferences.Editor spe=spf.edit();


--> We can insert a record using following syntax.

spe.putString("UserName", "Srikanth");
spe.putString("Password", "Patel");



Example for storing UserName and Password in SharedPreference.


/// Write the below code in Button Click to store Username and Password

public void storeData(View v)
{
    SharedPreferences spf=activity.getSharedPreferences("MyDataBase",Context.MODE_PRIVATE);
    SharedPreferences.Editor spe=spf.edit();
    spe.putString("UserName", "Srikanth");
    spe.putString("Password", "Patel");

    spe.commit();
}

// commit() returns true if the save works, false otherwise.



// this below code is used to read data from the shared Preference.

public void getData(View v)
{
    SharedPreferences spf=activity.getSharedPreferences("MyDataBase",Context.MODE_PRIVATE);
 
    String uname=spf.getString("UserName", "nodata");
    String pass=spf.getString("Password", "nodata");
   
}
 





Friday, 8 January 2016

Difference between two date time in java?

package Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestCalss
{
public static void main(String[] args)
{
            SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

            Date d1=null;
            Date d2=null;
           try
            {
                 d2=sdf.parse("01/09/2015 1:12:56 AM");
                 d1=sdf.parse("01/06/2015 11:34:11 PM");
             }
             catch (Exception e)
            {

             }
    long diff=d2.getTime()-d1.getTime();

             long diffSeconds = diff / 1000 % 60;
              long diffMinutes = diff / (60 * 1000) % 60;
              long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);


             System.out.println("Days:"+diffDays+"  Hours:"+diffHours+"  Minutes:"+diffMinutes+"  seconds:"+diffSeconds);

}
}



Output : Days:2 Hours: 49  Minutes: 38  seconds: 45






Tuesday, 5 January 2016

Example for sliding multiple images in android

Step 1> create a xml file with a name of android_main.xml and paste fillowing code.


<?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" android:background="#ffffff">
 
 
    <ImageView android:id="@+id/imgView"
        android:layout_height="100dp"
        android:layout_width="100dp"
        android:src="@drawable/ic_launcher"
        />
    <TextView
        android:id="@+id/tv1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:textColor="#000000"
        android:textSize="30dp"
        />

</LinearLayout>



Step 2> write the below logic in MainActivity.java class

package com.example.sampleproject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

ImageView imgView;
TextView tv1;
int[] a={R.drawable.a,R.drawable.b, R.drawable.c, R.drawable.d,R.drawable.e,R.drawable.f,R.drawable.g};
Handler myhHandler=new Handler();
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgView=(ImageView)findViewById(R.id.imgView);
        tv1=(TextView)findViewById(R.id.tv1);
        slide();
    }
    public void slide()
    {
             if(i<7)
             {
imgView.setImageResource(a[i]);
myhHandler.postDelayed(run, 2000);
i++;
             }
    }
    Runnable run=new Runnable()
    {
@Override
public void run()
{
              slide();
}
};
 
}


Monday, 4 January 2016

Simple View Pager Example in android

Step 1> Create a .xml file with the name of main.xml and paste the below code.


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical" >
          <!-- ViewPager -->
          <android.support.v4.view.ViewPager
                 android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/viewPager" />
         <!-- Footer -->
         <include layout="@layout/footer"  />
</FrameLayout>




Step 2> Create a  new .xml file with  the name of footer.xml and paste the below code



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="15dip"
    android:background="@color/d_blue"
    android:layout_gravity="bottom"
    android:orientation="vertical" >
 
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content"
    android:id="@+id/btn1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@drawable/rounded_celll" />
     
     <Button android:layout_height="wrap_content" android:layout_width="wrap_content"
    android:id="@+id/btn2"
    android:layout_toRightOf="@id/btn1"
    android:layout_marginLeft="5dip"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@drawable/rounded_celll" />
   
   <Button android:layout_height="wrap_content" android:layout_width="wrap_content"
    android:id="@+id/btn3"
    android:layout_toRightOf="@id/btn2"
    android:layout_marginLeft="5dip"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@drawable/rounded_celll" />

</RelativeLayout>




Step 3>  Create a class with the name of ViewPagerStyleActivity.java which extends FragmentActivity  and paste the following code.


package com.manishkpr.viewpager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.Button;

public class ViewPagerStyleActivity extends FragmentActivity {
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
private Button _btn1,_btn2,_btn3;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpView();
        setTab();
    }
    private void setUpView()
    {    
     _mViewPager = (ViewPager) findViewById(R.id.viewPager);
    _adapter = new ViewPagerAdapter(getApplicationContext(),getSupportFragmentManager());
    _mViewPager.setAdapter(_adapter);
_mViewPager.setCurrentItem(0);
initButton();
    }
 
    private void setTab()
    {
_mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
@Override
public void onPageScrollStateChanged(int position) {}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
@Override
public void onPageSelected(int position)
{
// TODO Auto-generated method stub
btnAction(position);
}

});
    }
    private void btnAction(int action){
    switch(action){
     case 0: setButton(_btn1,"1",40,40); setButton(_btn2,"",20,20); setButton(_btn3,"",20,20);  break;
   
     case 1: setButton(_btn2,"2",40,40); setButton(_btn1,"",20,20); setButton(_btn3,"",20,20); break;
   
     case 2: setButton(_btn3,"3",40,40); setButton(_btn1,"",20,20); setButton(_btn2,"",20,20); break;
    }
    }
    private void initButton()
    {
    _btn1=(Button)findViewById(R.id.btn1);
    _btn2=(Button)findViewById(R.id.btn2);
    _btn3=(Button)findViewById(R.id.btn3);
   
    setButton(_btn1,"1",40,40);
    setButton(_btn2,"",20,20);
   
    setButton(_btn3,"",20,20);
    }
    private void setButton(Button btn,String text,int h, int w)
    {
    btn.setWidth(w);
    btn.setHeight(h);
    btn.setText(text);
    }
}





Step 4>  Create a class with the name of ViewPagerAdapter which extends FragmentPagerAdapter and paste the following code.


package com.manishkpr.viewpager;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context _context;
public static int totalPage=3;
public ViewPagerAdapter(Context context, FragmentManager fm) {
super(fm);
_context=context;

}
@Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch(position)
{
case 0:
f=LayoutOne.newInstance(_context);
break;
case 1:
f=LayoutTwo.newInstance(_context);
break;
case 2:
f=LayoutThree.newInstance(_context);
break;
}
return f;
}
@Override
public int getCount()
{
return totalPage;
}
}





Step 5> Here i have created 3 fragments which i need to replace in view pager. Those are   fragment name are      LayoutOne.java,      LayoutTwo.java   and    LayoutThree.java



Step 6> create three xml files for three individual fragments those are layout_one.xml, layout_two.xml



Step 7> paste the following code in layout_one.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:gravity="center|center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Layout" />

</LinearLayout>




Step 8>    paste the following code in LayoutOne.java


package com.manishkpr.viewpager;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LayoutOne extends Fragment {


public static Fragment newInstance(Context context) {
LayoutOne f = new LayoutOne();

return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
return root;
}

}




Step 9> paste the following code in layout_two.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:gravity="center|center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Layout" />

</LinearLayout>




Step 10>  paste the following code in LayoutTwo.java


package com.manishkpr.viewpager;

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

public class LayoutTwo extends Fragment {


public static Fragment newInstance(Context context) {
LayoutTwo f = new LayoutTwo();

return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_two, null);
return root;
}

}


Step 11> Paste the following code in LayoutThree.java


package com.manishkpr.viewpager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LayoutThree  extends Fragment {


public static Fragment newInstance(Context context) {
LayoutThree f = new LayoutThree();

return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
return root;
}
}