Monday, 18 April 2016

Android navigation drawer with swipe tabs using Design Support Library


In this article we will see how to use the Design Support Library to create an android app with Material design Navigation Drawer and Swipe Tabs. Simplified user navigation is the most important challenge that every developer faces and by the usage of Navigation Drawer and Swipe Tabs it's really cool to do it.

Let start...

*Create the following classes in addition to generated   MainActivity.java:

  • AutoTabFragment.java
  • LifeStyleTabFragment.java
  • ExpoTabFragment.java
  • BookmarkFragment.java
  • HomeFragment.java

*Now add these dependencies to your project:
dependencies {  
   compile fileTree(dir: 'libs', include: ['*.jar'])  
   compile 'com.android.support:appcompat-v7:22.2.1'  
   compile 'com.android.support:design:22.2.1'  
 }  

*Download and extract the icon set to res=>drawable folder DOWNLOAD.

*In addition to 'activity_main.xml',Create the following xml files in res=>layout folder:
  • auto_tab_layout.xml
  • bookmark_layout.xml
  • expo_tab_layout.xml
  • home_tab_layout.xml
  • lifestyle_tab_layout.xml
  • nav_header.xml

*Paste the below code to res=>values=>style.xml
 <resources>  
   <!-- Base application theme. -->  
   <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">  
     <!-- Customize your theme here. -->  
     <item name="colorPrimary">#139D57</item>  
     <item name="colorPrimaryDark">#9CC266</item>  
   </style>  
 </resources>  

*Paste the below code to res=>values=>color.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
   <color name="black">#000</color>  
   <color name="orange">#139D57</color>  
   <color name="white">#FFF</color>  
 </resources>  


*Create navigation_drawer_menu.xml in res=>menu, and paste the below  code to it:
 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:title="Home"  
      android:id="@+id/nav_item_home"  
      android:icon="@drawable/home"/>  
   <item android:title="Bookmarks"  
      android:id="@+id/nav_item_bookmark"  
      android:icon="@drawable/bookmark"/>  
   <item android:title="New Page"  
      android:id="@+id/nav_item_newp"  
      android:icon="@drawable/newp"/>  
   <item android:title="Others">  
     <menu>  
       <item  
         android:title="Backups"  
         android:icon="@drawable/backup"/>  
       <item  
         android:title="Store"  
         android:icon="@drawable/store"/>  
     </menu>  
   </item>  
   <group android:id="@+id/group_settings_id">  
     <item android:title="Notifications"  
        android:icon="@drawable/messages"/>  
     <item android:title="Help"  
        android:icon="@drawable/help"/>  
   </group>  
 </menu>  


*Paste the below code to res=>layout=>activity_main.xml
 <LinearLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:fitsSystemWindows="true"  
   android:orientation="vertical">  
   <android.support.v7.widget.Toolbar  
     xmlns:android="http://schemas.android.com/apk/res/android"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:background="@color/orange"  
     android:id="@+id/toolbar"  
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  
     app:title="MyCreativeCodes.in" />  
   <android.support.v4.widget.DrawerLayout  
     xmlns:android="http://schemas.android.com/apk/res/android"  
     xmlns:app="http://schemas.android.com/apk/res-auto"  
     android:layout_height="match_parent"  
     android:layout_width="match_parent"  
     android:id="@+id/drawerLayout"  
     >  
   <FrameLayout  
     android:orientation="vertical"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:id="@+id/containerView">  
    </FrameLayout>  
   <android.support.design.widget.NavigationView  
     xmlns:android="http://schemas.android.com/apk/res/android"  
     xmlns:app="http://schemas.android.com/apk/res-auto"  
     android:layout_width="wrap_content"  
     android:layout_height="match_parent"  
     android:layout_gravity="start"  
     android:id="@+id/nav_drawer"  
     app:itemTextColor="@color/black"  
     app:headerLayout="@layout/nav_header"  
     app:menu="@menu/navigation_drawer_menu"  
     android:layout_marginTop="-24dp"  
     />  
   </android.support.v4.widget.DrawerLayout>  
   </LinearLayout>


*Paste the below code to res=>layout=>auto_tab_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:background="#fff"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:gravity="center"  
     android:text="Auto Tab"  
     android:textColor="@color/error_color"  
     android:textSize="50dp"  
     android:id="@+id/textView"  
     />  
 </RelativeLayout>  

*Paste the below code to res=>layout=>bookmark_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:background="#fff"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:gravity="center"  
     android:text="Bookmark Tab"  
     android:textColor="@color/error_color"  
     android:textSize="50dp"  
     android:id="@+id/textView"  
     />  
 </RelativeLayout>  


*Paste the below code to res=>layout=>expo_tab_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:background="#fff"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:gravity="center"  
     android:text="Expo Tab"  
     android:textColor="@color/error_color"  
     android:textSize="50dp"  
     android:id="@+id/textView"  
     />  
 </RelativeLayout>  

*Paste the below code to res=>layout=>home_tab_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   android:layout_width="match_parent"  
   android:orientation="vertical"  
   android:layout_height="wrap_content">  
   <android.support.design.widget.TabLayout  
     android:id="@+id/tabs"  
     app:tabGravity="fill"  
     app:tabMode="fixed"  
     android:background="@color/material_blue_grey_800"  
     app:tabIndicatorColor="@color/orange"  
     app:tabSelectedTextColor="@color/orange"  
     app:tabTextColor="@color/white"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
   </android.support.design.widget.TabLayout>  
   <android.support.v4.view.ViewPager  
     android:id="@+id/viewpager"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent">  
   </android.support.v4.view.ViewPager>  
 </LinearLayout>  

*Paste the below code to res=>layout=>lifestyle_tab_layout.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:background="#fff"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:gravity="center"  
     android:text="Life Style Tab"  
     android:textColor="@color/error_color"  
     android:textSize="50dp"  
     android:id="@+id/textView"  
     />  
 </RelativeLayout>  


*Paste the below code to res=>layout=>nav_header.xml
 This is the header section of the navigation drawer.
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:layout_height="150dp"  
   android:background="@drawable/headerbg"  
   android:id="@+id/headerlayout">  
   <ImageView  
     android:layout_width="156dp"  
     android:layout_height="match_parent"  
     android:id="@+id/imageView"  
     android:background="@drawable/account"  
     android:layout_gravity="center_horizontal" />  
 </LinearLayout>  

That's for the res section, now copy and paste the below java codes to corresponding files:

*AutoTabFragment.java
 import android.support.v4.app.Fragment;  
 import android.os.Bundle;  
 import android.support.annotation.Nullable;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 /**  
 * Created by jauhar xlr on 18/4/2016.  
     */  
 public class AutoTabFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     View rootView = inflater.inflate(R.layout.auto_tab_layout,null);  
     return rootView;  
   }  
 }  

*LifeStyleTabFragment.java
 import android.os.Bundle;  
 import android.support.annotation.Nullable;  
 import android.support.v4.app.Fragment;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 /**  
  * Created by Jauhar xlr on 4/18/2016.  
  * mycreativecodes.in  
  */  
 public class LifStyleTabFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     View rootView = inflater.inflate(R.layout.lifestyle_tab_layout,null);  
     return rootView;  
   }  
 }  

*ExpoTabFragment.java
 import android.support.v4.app.Fragment;  
 import android.os.Bundle;  
 import android.support.annotation.Nullable;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 /**  
  * Created by Jauhar xlr on 4/18/2016.  
  * mycreativecodes.in  
  */  
 public class ExpoTabFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     View rootView = inflater.inflate(R.layout.expo_tab_layout,null);  
     return rootView;  
   }  
 }  


*BookmarkFragment.java
 import android.support.v4.app.Fragment;  
 import android.os.Bundle;  
 import android.support.annotation.Nullable;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 /**  
  * Created by Jauhar xlr on 4/18/2016.  
  * mycreativecodes.in  
  */  
 public class BookmarkFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     View rootView = inflater.inflate(R.layout.bookmark_layout,null);  
     return rootView;  
   }  
 }  

*HomeFragment.java
 import android.os.Bundle;  
 import android.support.annotation.Nullable;  
 import android.support.design.widget.TabLayout;  
 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.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 /**  
  * Created by Jauhar xlr on 4/18/2016.  
  * mycreativecodes.in  
  */  
 public class HomeFragment extends Fragment {  
   public static TabLayout tabLayout;  
   public static ViewPager viewPager;  
   public static int int_items = 3 ;  
   @Nullable  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     /**  
      *Inflate tab_layout and setup Views.  
      */  
       View x = inflater.inflate(R.layout.home_tab_layout,null);  
       tabLayout = (TabLayout) x.findViewById(R.id.tabs);  
       viewPager = (ViewPager) x.findViewById(R.id.viewpager);  
     /**  
      *Set an Apater for the View Pager  
      */  
     viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));  
     /**  
      * Now , this is a workaround ,  
      * The setupWithViewPager dose't works without the runnable .  
      * Maybe a Support Library Bug .  
      */  
     tabLayout.post(new Runnable() {  
       @Override  
       public void run() {  
           tabLayout.setupWithViewPager(viewPager);  
           }  
     });  
     return x;  
   }  
   class MyAdapter extends FragmentPagerAdapter{  
     public MyAdapter(FragmentManager fm) {  
       super(fm);  
     }  
     /**  
      * Return fragment with respect to Position .  
      */  
     @Override  
     public Fragment getItem(int position)  
     {  
      switch (position){  
        case 0 : return new LifStyleTabFragment();  
        case 1 : return new AutoTabFragment();  
        case 2 : return new ExpoTabFragment();  
      }  
     return null;  
     }  
     @Override  
     public int getCount() {  
       return int_items;  
     }  
     /**  
      * This method returns the title of the tab according to the position.  
      */  
     @Override  
     public CharSequence getPageTitle(int position) {  
       switch (position){  
         case 0 :  
           return "Life Style";  
         case 1 :  
           return "Auto";  
         case 2 :  
           return "Expo";  
       }  
         return null;  
     }  
   }  
 }  

*MainActivity.java
 import android.os.Bundle;  
 import android.support.design.widget.NavigationView;  
 import android.support.v4.app.FragmentManager;  
 import android.support.v4.app.FragmentTransaction;  
 import android.support.v4.widget.DrawerLayout;  
 import android.support.v7.app.ActionBarDrawerToggle;  
 import android.support.v7.app.AppCompatActivity;  
 import android.view.MenuItem;  
 /**  
  * Created by Jauhar xlr on 4/18/2016.  
  * mycreativecodes.in  
  */  
 public class MainActivity extends AppCompatActivity{  
   DrawerLayout myDrawerLayout;  
   NavigationView myNavigationView;  
   FragmentManager myFragmentManager;  
   FragmentTransaction myFragmentTransaction;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     /**  
      *Setup the DrawerLayout and NavigationView  
      */  
        myDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);  
        myNavigationView = (NavigationView) findViewById(R.id.nav_drawer) ;  
     /**  
      * Lets inflate the very first fragment  
      * Here , we are inflating the HomeFragment as the first Fragment  
      */  
        myFragmentManager = getSupportFragmentManager();  
        myFragmentTransaction = myFragmentManager.beginTransaction();  
        myFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();  
     /**  
      * Setup click events on the Navigation View Items.  
      */  
        myNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {  
          @Override  
          public boolean onNavigationItemSelected(MenuItem selectedMenuItem) {  
            myDrawerLayout.closeDrawers();  
            if (selectedMenuItem.getItemId() == R.id.nav_item_home) {  
              FragmentTransaction fragmentTransaction = myFragmentManager.beginTransaction();  
              fragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();  
            }  
            if (selectedMenuItem.getItemId() == R.id.nav_item_bookmark) {  
              FragmentTransaction xfragmentTransaction = myFragmentManager.beginTransaction();  
              xfragmentTransaction.replace(R.id.containerView, new BookmarkFragment()).commit();  
            }  
            return false;  
          }  
        });  
     /**  
      * Setup Drawer Toggle of the Toolbar  
      */  
         android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);  
         ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, myDrawerLayout, toolbar,R.string.app_name,  
         R.string.app_name);  
         myDrawerLayout.setDrawerListener(mDrawerToggle);  
         mDrawerToggle.syncState();  
   }  
 }  

It's done, run your project to see the magic!

Saturday, 16 April 2016

Android Image Slider

Hello fellas, recently i have to implement an image slider in android. After googling for a while I found a really nice n cool image slider for android, it has a lot of  animations and easily adaptable to any layout. Now its really simple to implement an Image Slider in your android app. Just follow the below steps:

*For eclipse users download this complete project , download.

*For Android Studio users sync the below dependencies:
 dependencies {  
     compile "com.android.support:support-v4:+"  
     compile 'com.squareup.picasso:picasso:2.3.2'  
     compile 'com.nineoldandroids:library:2.4.0'  
     compile 'com.daimajia.slider:library:1.1.5@aar'  
 }  

After Adding the above dependencies( attaching library in Eclipse) follow the below steps:

1.  Add the below code to your MainActivity.java
 public class MainActivity extends ActionBarActivity implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener{  
   private SliderLayout mySlider;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
           mySlider = (SliderLayout)findViewById(R.id.slider);  
     HashMap<String,Integer> file_maps = new HashMap<String, Integer>();  
     file_maps.put("image One",R.drawable.one);  
     file_maps.put("image two",R.drawable.two);  
     file_maps.put("image three",R.drawable.three);  
     file_maps.put("image four", R.drawable.four);  
     for(String name : file_maps.keySet()){  
       TextSliderView textSliderView = new TextSliderView(this);  
       // initialize a SliderLayout  
       textSliderView  
           .description(name)  
           .image(file_maps.get(name))  
           .setScaleType(BaseSliderView.ScaleType.Fit)  
           .setOnSliderClickListener(this);  
       //add your extra information  
       textSliderView.bundle(new Bundle());  
       textSliderView.getBundle()  
             .putString("extra",name);  
       mySlider.addSlider(textSliderView);  
     }  
     mySlider.setPresetTransformer(SliderLayout.Transformer.Accordion);  
     mySlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);  
     mySlider.setCustomAnimation(new DescriptionAnimation());  
     mySlider.setDuration(4000);  
     mySlider.addOnPageChangeListener(this);  
   }  
   @Override  
   protected void onStop() {  
     // To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed  
     mySlider.stopAutoCycle();  
     super.onStop();  
   }  
   @Override  
   public void onSliderClick(BaseSliderView slider) {  
     Toast.makeText(this,slider.getBundle().get("extra") + "",Toast.LENGTH_SHORT).show();  
   }  
   @Override  
   public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}  
   @Override  
   public void onPageSelected(int position) {  
     Log.d("Slider Demo", "Page Changed: " + position);  
   }  
   @Override  
   public void onPageScrollStateChanged(int state) {}  
 }  

Note: You can change the animation by replacing new DescriptionAnimation()    in mySlider.setCustomAnimation(new DescriptionAnimation()); Also You change the duration of animation in mySlider.setDuration(4000);

2. Add the below xml code to your activity_main.xml layout file:


<!--Add the Slider to your layout:-->  
 <com.daimajia.slider.library.SliderLayout  
     android:id="@+id/slider"  
     android:layout_width="match_parent"  
     android:layout_height="200dp"  
 />  
 <!--There are some default indicators. If you want to use a provided indicator:-->  
 <com.daimajia.slider.library.Indicators.PagerIndicator  
     android:id="@+id/custom_indicator"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:gravity="center"  
     />  

Don't forget to add images namely one.png, two.png, three.png, four.png in your res=>drawable folder.

That's all, if everything goes right run app to see the magic!

Wednesday, 13 April 2016

Android upload image / file to server

Their are several occasions when we need to upload a file from android device to server. Today we are gonna build an android app to upload an image and store it in the server. The server side will be powered by PHP.

1.Download and add android-async-http-library to your project.

2.Copy the below Code to your Activity Class:


import java.io.ByteArrayOutputStream;  
 import android.annotation.SuppressLint;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.content.Intent;  
 import android.database.Cursor;  
 import android.graphics.bitmapImage;  
 import android.graphics.bitmapImageFactory;  
 import android.net.Uri;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.provider.MediaStore;  
 import android.util.Base64;  
 import android.view.View;  
 import android.widget.ImageView;  
 import android.widget.Toast;  
 import com.loopj.android.http.AsyncHttpClient;  
 import com.loopj.android.http.AsyncHttpResponseHandler;  
 import com.loopj.android.http.RequestParams;  
 @SuppressLint("NewApi")  
 public class MainActivity extends Activity {  
      ProgressDialog progressDialog;  
      String encodedString;  
      RequestParams params = new RequestParams();  
      String imagePath, fileName;  
      bitmapImage bitmapImage;  
      private static int LOAD_IMG_RESULT = 1;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
           progressDialog = new ProgressDialog(this);  
           // Set Cancelable as False  
           progressDialog.setCancelable(false);  
      }  
      public void loadImagefromGallery(View view) {  
           // Create intent to Open Image applications like Gallery, Google Photos  
           Intent gallary = new Intent(Intent.ACTION_PICK,  
                     android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
           // Start the Intent  
           startActivityForResult(gallary, LOAD_IMG_RESULT);  
      }  
      // When Image is selected from Gallery  
      @Override  
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
           super.onActivityResult(requestCode, resultCode, data);  
           try {  
                // When an Image is picked  
                if (requestCode == LOAD_IMG_RESULT && resultCode == RESULT_OK  
                          && null != data) {  
                     // Get the Image from data  
                     Uri selectedImage = data.getData();  
                     String[] filePathColumn = { MediaStore.Images.Media.DATA };  
                     // Get the cursor  
                     Cursor cursor = getContentResolver().query(selectedImage,  
                               filePathColumn, null, null, null);  
                     // Move to first row  
                     cursor.moveToFirst();  
                     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);  
                     imagePath = cursor.getString(columnIndex);  
                     cursor.close();  
                     ImageView imageView = (ImageView) findViewById(R.id.imageView);  
                     // Set the Image in ImageView  
                     imageView.setImagebitmapImage(bitmapImageFactory  
                               .decodeFile(imagePath));  
                     // Get the Image's file name  
                     String splittedFileName[] = imagePath.split("/");  
                     fileName = splittedFileName[splittedFileName.length - 1];  
                     // Put file name in Async Http Post Param which will used in Php web app  
                     params.put("fileName", fileName);  
                } else {  
                     Toast.makeText(this, "You haven't picked Image",  
                               Toast.LENGTH_LONG).show();  
                }  
           } catch (Exception e) {  
                Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)  
                          .show();  
           }  
      }  
      // When Upload button is clicked  
      public void startUploadImage(View v) {  
           // When Image is selected from Gallery  
           if (imagePath != null && !imagePath.isEmpty()) {  
                progressDialog.setMessage("Converting Image to Binary Data");  
                progressDialog.show();  
                // Convert image to String using Base64  
                encodeImagetoString();  
           // When Image is not selected from Gallery  
           } else {  
                Toast.makeText(  
                          getApplicationContext(),  
                          "You must select image from gallery before you try to upload",  
                          Toast.LENGTH_LONG).show();  
           }  
      }  
      // AsyncTask - To convert Image to String  
      public void encodeImagetoString() {  
           new AsyncTask<Void, Void, String>() {  
                protected void onPreExecute() {  
                };  
                @Override  
                protected String doInBackground(Void... params) {  
                     bitmapImageFactory.Options options = null;  
                     options = new bitmapImageFactory.Options();  
                     options.inSampleSize = 3;  
                     bitmapImage = bitmapImageFactory.decodeFile(imagePath,  
                               options);  
                     ByteArrayOutputStream stream = new ByteArrayOutputStream();  
                     // Must compress the Image to reduce image size to make upload easy  
                     bitmapImage.compress(bitmapImage.CompressFormat.PNG, 50, stream);   
                     byte[] byte_arr = stream.toByteArray();  
                     // Encode Image to String  
                     encodedString = Base64.encodeToString(byte_arr, 0);  
                     return "";  
                }  
                @Override  
                protected void onPostExecute(String msg) {  
                     progressDialog.setMessage("Calling Upload");  
                     // Put converted Image string into Async Http Post param  
                     params.put("image", encodedString);  
                     // Trigger Image upload  
                     triggerImageUpload();  
                }  
           }.execute(null, null, null);  
      }  
      public void triggerImageUpload() {  
           makingHTTPCall();  
      }  
      // Make Http call to upload Image to Php server  
      public void makingHTTPCall() {  
           progressDialog.setMessage("Invoking Php");            
           AsyncHttpClient client = new AsyncHttpClient();  
           // Don't forget to change the IP address to your LAN address. Port no as well.  
           client.post("http://<YOUR WEB URL>/upload_image.php",  
                     params, new AsyncHttpResponseHandler() {  
                          // When the response returned by REST has Http  
                          // response code '200'  
                          @Override  
                          public void onSuccess(String response) {  
                               // Hide Progress Dialog box  
                               progressDialog.hide();  
                               Toast.makeText(getApplicationContext(), response,  
                                         Toast.LENGTH_LONG).show();  
                          }  
                          // When the response returned by REST has Http  
                          // response code other than '200' such as '404',  
                          // '500' or '403' etc  
                          @Override  
                          public void onFailure(int statusCode, Throwable error,  
                                    String content) {  
                               // Hide Progress Dialog Box  
                               progressDialog.hide();  
                               // When Http response code is '404'  
                               if (statusCode == 404) {  
                                    Toast.makeText(getApplicationContext(),  
                                              "Requested resource not found",  
                                              Toast.LENGTH_LONG).show();  
                               }  
                               // When Http response code is '500'  
                               else if (statusCode == 500) {  
                                    Toast.makeText(getApplicationContext(),  
                                              "Something went wrong at server end",  
                                              Toast.LENGTH_LONG).show();  
                               }  
                               // When Http response code other than 404, 500  
                               else {  
                                    Toast.makeText(  
                                              getApplicationContext(),  
                                              "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "  
                                                        + statusCode, Toast.LENGTH_LONG)  
                                              .show();  
                               }  
                          }  
                     });  
      }  
      @Override  
      protected void onDestroy() {  
           // TODO Auto-generated method stub  
           super.onDestroy();  
           // Dismiss the progress bar when application is closed  
           if (progressDialog != null) {  
                progressDialog.dismiss();  
           }  
      }  
 }  

*Don't forget to replace <YOUR WEB URL> with your web address.

3.Now Copy the below code to your activity's layout xml file:


<?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:orientation="vertical" >  
   <ImageView  
     android:id="@+id/imgView"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_weight="1" >  
   </ImageView>  
   <Button  
     android:id="@+id/buttonLoadPicture"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center"  
     android:layout_weight="0"  
     android:onClick="loadImagefromGallery"  
     android:text="Load Image" >  
   </Button>  
   <Button  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_marginTop="25dp"  
     android:onClick="startUploadImage"  
     android:text="Start Upload" />  
 </LinearLayout>  

4.create a folder in your server, namely 'images'.
5.Create a php file(imageupload.php) in the same directory(in server) and Copy the below code to it.

*imageupload.php
 <?php  
   // Get image string posted from Android App  
   $base=$_REQUEST['image'];  
      // Get file name posted from Android App  
      $filename = $_REQUEST['filename'];  
      // Decode Image  
   $binary=base64_decode($base);  
   header('Content-Type: bitmap; charset=utf-8');  
      // Images will be saved under 'www/img/images' folder  
   $file = fopen('images/'.$filename, 'wb');  
      // Create File  
   fwrite($file, $binary);  
   fclose($file);  
   echo 'Image upload complete, Please check your php file directory';  
 ?>  


6. Add Internet and External Storage Permissions to your project manifest
 <uses-permission android:name="android.permission.INTERNET" />  
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

That's all, Now run your project!



How to implement Android Splash Screen

Splash Screens are upcoming trend to showcase you app logo and further information. Android officially does not have any builtin mechanism to show a splash screen as IOS do. Today we are gonna learn how to add a splash screen for you android app. 


Please follow the below steps:
  • Create your android project and rename your MainActivity to SplashScreen and finish building your project.
  • Add one more Activity to your project namely MainActivity .
  • Now simply copy and paste the below code to your SplashScreen.java class.
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.os.Handler;  
 public class SplashScreen extends Activity {  
   // Splash screen timer  
   private static int SPLASH_TIME_OUT = 2500;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_splash);  
     new Handler().postDelayed(new Runnable() {  
         
       @Override  
       public void run() {  
         // This method will be triggered once the timer is over  
         // Start your app MainActivity  
         Intent i = new Intent(SplashScreen.this, MainActivity.class);  
         startActivity(i);  
         // close this activity  
         finish();  
       }  
     }, SPLASH_TIME_OUT);  
   }  
 }  

  • Now u may make changes to res ⇒ layout ⇒ activity_splashscreen.xml to meet your requirement.
That's all, now when ever you open your app a splash screen will be show for 2.5 seconds.


Tuesday, 5 April 2016

How to generate IPA file without Provisioning profile or developers account using xcode 7 for distribution

Hi friends recently I had to build an ios accounting app for one of my client. The ios simulator is great! and by xcode 7 i was also able to test the app in real device. But after successful completion of the project I was really shocked that I had to pay $99 to generate an IPA file for distribution. The overall price that i charged from my client is only $60 and how come it be feasible to pay such a huge amount for a simple app. And finally I was able generate ipa without spending even a single dollar.


How I Generated IPA file: 
1> Connect Your Iphone to To Your Mac.
2> Open your ios Xcode project(mine is XCode 7).
3> change products-Destination to your connected device(i not connected change it to 'ios device').
4> press cmd+B to build your project.
** After Completion of Build Task you will find YourAppName.app file under the Products folder in your XCode project navigator.
5> Right click on the YourAppName.app and click on show in finder option. Finder will appear with the particular file, Just copy it.
6> Create a new folder in your desktop and rename it to Payload and paste the particular file it.
7> Compress zip the folder(Payload.zip) and rename it to Payload.ipa.
** Now You have the IPA file in your hand, and now you could distribute it to as many clients you want without any restriction.

How I Installed it in my Client's Iphone:
1> Download ifunbox in addition to iTunes
2> Connect your Device to your Computer
3> Open ifunbox, select your device, then click on install app and select the previously generated IPA file.
Done

Its Not Completed Yet! when you try to open your app in  your Iphone you will get this Untrested App Developer notification,

How to Avoid Untrested App Developer Notification:

For ios version less than 9.2:
Goto settings-general-profile, select the developer Apple Id and click on trust.

For ios version 9.2:
Goto Settings-General-Device Management and click on your Apple ID and tap on Trust option.

Thats all Now you could use your app as usual!