Saturday, 22 March 2014

How To Create Application Folder in SD Card ?

No comments :
Android framework create your application folder in internal space when you install any of app. it is located at data/data/package-name folder. if you have rooted emulator or smart phone you can check it out. but it has one disadvantage once user remove your app this folder will also be removed but if you want to store data after it also so you can use it if user again install your app or you want to store some info related to your app on SD card then you can create it using this tutorial.  just follow the steps of this tutorial.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option. put this below code in your mainactivity so once user start your app it will be created so you can use it further in your app.
MainActivity.java
package com.androprogrammer.tutorialsamples;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

import java.io.File;


public class MainActivity extends ActionBarActivity {

    String folderPath;
    File folder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sdcard_folder_demo);
        folderPath = createFolder();
    }

    private String createFolder()
    {
            String extStorageDirectory = Environment
                    .getExternalStorageDirectory().toString();
            folder = new File(extStorageDirectory, "/Android/data/" + getPackageName());
            if(!folder.exists())
            {
                folder.mkdir();
                Toast.makeText(MainActivity.this, "Folder Created At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Folder Already At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            return folder.getPath().toString();
    }
}
Step -2 : i have created createFolder() method it will also check if folder is already created or not. if it is there it return path to the folder. the above code will create folder with your package name so to check out run your application. one more thing in order to create or write in SD card you required to add below permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Screen Shots
androprogrammer.comandroprogrammer.com

That's it check out your application folder in SD card at Android/data/package-name folder. now you can store any data in or file in this folder using string returned by that method.

Keep coding.. 
Read More

Thursday, 13 March 2014

Create Android Dynamic view with Fragments...

No comments :
In Android Application to Perform multiple task you have to create different activities or services or both but using fragments you can use multiple views in single fragment activity. The Concept of Fragments comes from Android 3.0 (Honeycomb) but now developers have created many API so you can use it in below android version also. In this tutorial i am going to explain you how you can implements fragment in your application easily. The Fragment concept is quit confusing and from documentation you can not understand it properly. 

So Go through the full tutorial and don't miss any steps because it is confusing so you may miss some of the main points. In this tutorial i am going to create List of Website and When user clicks on it. it will open that site in web view. so these are the files i am going to create in my project. i am clarifying it because their are many tutorials but in many of them you get confuse between those files so have a look it.

Java (Class) Files
1. MainActivity.java
2.FragmentListview.java
3.FragmentWebview.java
4.FragmentSupport.java

Xml (Layout) Files
1.activity_main.xml
2.fragmentlistview.xml
3.fragmentwebview.xml
4.fragment_support.xml


Fragments in android



This is how it looks in portrait view. When mobile is in Portrait view only one view is display to the user. when user click on list item then new view is get created and display to the user. you can add view in back stack of fragment. further read about back stack navigation.
Below image is of fragment in landscape view. in order to work your application in landscape mode you have to create folder name as layout-land. 


Fragments in android

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option.
Step-2 : in your activity_main.xml file add fragment in it. when you add it in eclipse you have option to create fragment class but in android studio you will see below popup box then select any of them we will change it later.

Fragments in android

Now below coding is of activity_main.xml file you can put it in your code.
activity_main.xml



    


Now Create New Layout File For List view and add list view in it and Layout for Web view also. this layouts are use to create dynamically view.
fragmentlistview.xml


    
    


fragmentwebview.xml


    

Step-3 : Create New Activity and name it fragmentSupport.jave and fragment_support.xml. Below one is layout for fragment support activity. this activity is for take index of list item and pass it to the web fragment. in landscape view both layout is in view so you are not require to call or create web view again.
fragment_support.xml


    
    


now create layout-land folder in res folder and create new layout file and give same name as activity_main.xml. android will automatically use this view when user rotate mobile to landscape view. then copy below code in it. it have both fragment listview and webview. 
now all your layout is done. make sure name of fragments are same in portrait view layout file and landscape view file. 

Step-4 : All layout is set so now i proceed to coding so copy below code in MainActivity.java file. the MaiActivity.java file implements interface that is created in FragmentListview.java class. this interface is connector between two views. 
MainActivity.java
package com.androprogrammer.democollection;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.app.FragmentManager;


public class MainActivity extends Activity implements FragmentListview.OnSiteSelectedListener{

    FragmentWebview web;
    FragmentListview list;
    FragmentManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = getFragmentManager();
        list = (FragmentListview) manager.findFragmentById(R.id.fragment1);
        list.setRefrence(this);
    }

    @Override
    public void onSiteSelected(int i) {
        // TODO Auto-generated method stub

        web = (FragmentWebview) manager.findFragmentById(R.id.fragment2);
        // Check for landscape mode
        if (web!= null && web.isVisible())
        {
            web.setNewPage(i);
        }
        else
        {
            Intent intent = new Intent(this , Fragmentsupport.class);
            intent.putExtra("index", i);
            startActivity(intent);
        }
    }

}
onSiteselected method is implemented in OnSiteSelectedListener interface. this method will take index from main view weather it is portrait view or landscape view and then send it to the Fragmentwebview class to get website from String array and then load it in Web view. now put below code in FragmentListview.java file.
FragmentListview.java
package com.androprogrammer.democollection;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FragmentListview extends Fragment implements AdapterView.OnItemClickListener
{
    ListView list;
 String [] websites = {"Google","Facebook","Twitter","Xda-developer"};
 
 
 OnSiteSelectedListener SiteListener;

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  View v = inflater.inflate(R.layout.fragmentlistview, container, false);
        list = (ListView) v.findViewById(R.id.list);
        list.setAdapter(new ArrayAdapter(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1,websites));
        list.setOnItemClickListener(this);
        return v;
 }

    @Override
    public void onItemClick(AdapterView adapterView, View view, int position, long l)
    {
        SiteListener.onSiteSelected(position);
    }

    // Container Activity must implement this interface
    public interface OnSiteSelectedListener {
        public void onSiteSelected(int i);
    }

    public void setRefrence(OnSiteSelectedListener siteListener)
    {
        this.SiteListener = siteListener;
    }

}
Fragmentwebview.java
package com.androprogrammer.democollection;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

public class FragmentWebview extends Fragment {

 WebView webView;
 String [] links = {"http://www.google.com","http://www.facebook.com","http://www.twitter.com" , "http://www.xda-developers.com"};
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragmentwebview, container, false);
  webView = (WebView) v.findViewById(R.id.webView1);
        webView.loadUrl(links[0].toString());
        return v;
 }

 public void setNewPage(int i) 
 {
  //webView = (WebView) getView().findViewById(R.id.webView1);
  Log.d("webveiw", "called");
  webView.loadUrl(links[i].toString());
 }
}
FragmentSupport.java
package com.androprogrammer.democollection;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class Fragmentsupport extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_support);
        Intent intent = getIntent();
        int index = intent.getIntExtra("index",0);
        FragmentWebview web = (FragmentWebview) getFragmentManager().findFragmentById(R.id.fragment2);
        if (web != null)
            web.setNewPage(index);

    }
}

the above four class file is not activity only MainActivity and FragmentSupport is activity so make sure you have added entry in manifest file. one more thing add below permission also in manifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
that's it. you have created fragment project successfully. so now customize it as you require.
you can download full source code from here.
Keep Coding...
Read More

Tuesday, 18 February 2014

Check Internet Connectivity Status in Android.

No comments :
To Access Web Services or Internet connection you required to check weather connection is available or not. so to check how you can do this read my this article in which i will help you to get connection status in your application. there are no of ways to get connectivity status like broadcast receiver , back ground service etc. but in this example i am using connectivity manager class which allow to use connection service in our application. 

Step -1  : Create New Android application and give name ConnectivityDemo to main activity and same name for layout file. minSdkVersion="17” and targetSdkVersion="17".you can use below android version also for compilation and build option.

Step-2 : in your connectivitydemo.xml file put the below code in it. in this layout file i have used two buttons but if you won't require it you can skip this step.
ConnectivityDemo.xml


      

    


Step-3 : Above layout File having one button for checking mobile data connection and one is for wifi connection.  now put below code in ConnectivityDemo.java file.
ConnectivityDemo.java
package com.example.samplecollection;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ConnectivityDemo extends Activity implements OnClickListener{

 Button MobileData,wifi;
 boolean status;
 CheckForConnection cf;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.connectivity_demo);
  setRef();
 }

 private void setRef()
 {
  // TO set Refrence to the xml button object.
  MobileData = (Button) findViewById(R.id.CD_bt_mdata);
  wifi = (Button) findViewById(R.id.CD_bt_wifi);
  MobileData.setOnClickListener(this);
  wifi.setOnClickListener(this);
  
 }

 @Override
 public void onClick(View v)
 {
  // Get Which button is clicked by user
  switch (v.getId())
  {
   case R.id.CD_bt_mdata:
    cf = new CheckForConnection();
    status = cf.getMobileDataStatus(ConnectivityDemo.this);
    if(status)
     Toast.makeText(ConnectivityDemo.this,"Data Connection is On.", Toast.LENGTH_LONG).show();
    else
     Toast.makeText(ConnectivityDemo.this,"Data Connection is Off", Toast.LENGTH_LONG).show();
   break;

   case R.id.CD_bt_wifi:
    cf= new CheckForConnection();
    status = cf.getWifiStatus(ConnectivityDemo.this);
    if(status)
     Toast.makeText(ConnectivityDemo.this,"Wifi Connection is On.", Toast.LENGTH_LONG).show();
    else
     Toast.makeText(ConnectivityDemo.this,"Wifi Connection is Off.", Toast.LENGTH_LONG).show();
   break;
   
  default:
   break;
  }
  
 }

}
Step-4 : i have created another class CheckForConnection which actually check weather mobile data or wifi is on or not. in android you can not do network connectivity task on main thread so to perform network task i have created this class. this is the main and handy point because if you create Broad cast Receiver you have to register it and you have to add entry in manifest file also but if you forget any of this its like a burden for you. and if you create service in your application it runs continuously. so that's why i choose this way  to make yor work easy. now create new class CheckForConnection.java. and copy below code in it.
CheckForConnection.java
package com.example.samplecollection;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class CheckForConnection
{
 
    public static boolean getWifiStatus(Context context) 
    {
        // To get System Connectivity status
     ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork)
        {
         // Check For Wifi Status 
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return true;
            else
             return false;
        } 
        
        return false;
    }

    public static boolean getMobileDataStatus(Context context) 
    {
        // To get System Connectivity status
     ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork)
        {
         // Check For Mobile Data Status  
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return true;
            else
             return false;
        } 
        
        return false;
    }
    
 
}


Screen Shots
androprogrammer
androprogrammer.com

Now just run your application and check weather it works.  i hope you understand the way i have done this so you can implement in your application. if you have any query or problem ask in below comment box.

Keep coding...
Read More

Friday, 7 February 2014

Add Searching in List View.

No comments :
Search Functionality the best thing we use to find information fast and easy. well in your application if you have long list of information and you want provide search function in your application. it may affect your application credits. user get bored after so much scroll in list. So to add search functionality you have two option One is using Action bar search functionality and Second is alert box that ask for query and then you search on the basis of that. one main thing about this Search function is you have to use in built layout of list view in order to work it (My opinion). 

Steps
  • Create New Application and give name it ListViewSearch and Do next. 
    • minSdkVersion="17” 
    • targetSdkVersion="17". 
  • Give activity name – Main.java and main.xml. 
  • Go to main.xml and paste the below code.
Main.xml


    
    


Now Go to menu > main.xml file and put below cost in it.
 
 

Action bar was introduce in Android 3.0 version so if you are creating app that works on gingerbread and all version you have to add search view above list view or you can use action bar sherlock. you can check out my tutorial on action bar sherlock for more.now go to your class file and put below code.
Main.java
package com.androprogrammer.app3;

import android.os.Bundle;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.text.TextUtils;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class Main extends Activity implements OnQueryTextListener{

 ListView lv;
 CustomAdapter adapter;
 String temp[] = {"Gplus","Facebook","Instagram","Linkdin","Pintrest","Twitter","Snapchat","Skype"};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  lv = (ListView) findViewById(R.id.listView1);
  lv.setAdapter(new ArrayAdapter < string >(getApplicationContext(),android.R.layout.simple_list_item_1,temp));
  lv.setTextFilterEnabled(true);
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
        SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return super.onCreateOptionsMenu(menu);
 }

 @Override
 public boolean onQueryTextChange(String newText)
 {
  // this is your adapter that will be filtered
      if (TextUtils.isEmpty(newText))
      {
            lv.clearTextFilter();
        }
      else
      {
            lv.setFilterText(newText.toString());
        }
        
      return true;
 }

 @Override
 public boolean onQueryTextSubmit(String query) {
  // TODO Auto-generated method stub
  return false;
 }

}
Screen Shot

As you can see your query display in below Box and it also filter your list view adapter. that's it now run your application and see it works with your tweak or not. if you have any query or problem with it post it in below comment box. i have solved many problems that are still on stack overflow and many forums. you can suggest or share this link with your friends.
if you like the blog subscribe to our blog or like us on facebook or Google+.
Keep coding..
Read More

Saturday, 1 February 2014

Add Gesture in Image switcher to swipe Images

No comments :
In Gallery Application I hope you have used images it to swipe all images in your smartphone.Today in this tutorial how you can achieve this in your application. To add Gesture in your image switcher you have to override onTouchEvent method. this will allow you to get how and what gesture performed. i am using Cursor adapter to fetch all images from SD card. if you don't know about it check out My Tutorial on How to Fetch Images From Storage ? 

Steps
  1. Create New Application and give name it ImageSwitcher and Do next. 
    1. minSdkVersion="17” 
    2. targetSdkVersion="17". 
  2. Give activity name – Main.java and main.xml. 
  3. Go to main.xml and paste the below code.

Main.xml


    

        
       
        
    


Now your layout is set. Now Copy paste below Code in your Main.java file. in java file i have overridden onTouchEvent Method. that will accept parameter as event that user have done. In create method i have created cursor that will fetch images from SD card. some time it won't work. if you have same problem you have to add onfilling method.in image view i have set scale type as center crop that will stretch images from center and display but you can set different parameters in it .that will also accept Touch event as parameter and then you can do swipe operation.
Main.java
package com.example.samplecollection;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;

public class ViewFlipper_Demo extends Activity {

 ImageSwitcher Switch;
 ImageView images;
 float initialX;
 private Cursor cursor;
 private  int columnIndex, position = 0;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.view_flipper);
  Switch = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
  images = (ImageView) findViewById(R.id.imageView1);
  String[] projection = {MediaStore.Images.Thumbnails._ID};
     cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Thumbnails._ID + "");
     columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.view_flipper__demo, menu);
  return true;
 }
 
 @Override
 public boolean onTouchEvent(MotionEvent event) {
  // TODO Auto-generated method stub
  switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            initialX = event.getX();
            break;
        case MotionEvent.ACTION_UP:
            float finalX = event.getX();
            if (initialX > finalX)
            {
             cursor.moveToPosition(position);
             int imageID = cursor.getInt(columnIndex);
             images.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
             //images.setBackgroundResource(R.drawable.mb__messagebar_divider);
                 Switch.showNext();
                 Toast.makeText(getApplicationContext(), "Next Image", 
                       Toast.LENGTH_LONG).show();
                 position++;
            } 
            else
            {
             if(position > 0)
             {
              cursor.moveToPosition(position);
              int imageID = cursor.getInt(columnIndex);
              images.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
              //images.setBackgroundResource(R.drawable.ic_launcher);
              Toast.makeText(getApplicationContext(), "previous Image", 
                     Toast.LENGTH_LONG).show();
              Switch.showPrevious();
              position= position-1;
             }
             else
             {
              Toast.makeText(getApplicationContext(), "No More Images To Swipe", 
                      Toast.LENGTH_LONG).show();
             }
            }
            break;
        }
        return false;
 }

}

Screen Shots

As you can see toast message will display when you swipe gesture on image switcher. copy paste all above code and change name as per your project. if you like this tutorial subscribe to my blog for future updates and best tutorials on android.
Keep Coding.. 
Read More