Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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.


Wednesday, 13 January 2016

Android Barcode Scanning Application Source Code

  Today I'm gonna point you to a bar code scanner app source code, which works with ZBar library. It is a really lightweight, high speed, cross platform and easy to use library available to deal with barcode and QR Code.

The Zbar library supports variety of bar code standards and also QR codes : 

  • EAN-13/UPC-A
  • UPC-E, EAN-8
  • Code 128
  • Code 39
  • Interleaved 2 of 5
  • QR Code
Download The Application Source

Saturday, 24 October 2015

JavaMail Tutorial | How to read received mail

     JavaMail helps you to connect your mailing service with your custom software! In this tutorial  you are gonna use javamail to fetch the revieved mails and once received the mail is set to read.


Steps:
1.Download and add javamail library to your project!
2.Copy past the below java code to your class file.


Java:
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.util.Properties;  
 import java.util.concurrent.Executors;  
 import java.util.concurrent.ScheduledExecutorService;  
 import java.util.concurrent.TimeUnit;  
 import java.util.logging.Handler;  
 import javax.mail.Address;  
 import javax.mail.BodyPart;  
 import javax.mail.Flags;  
 import javax.mail.Folder;  
 import javax.mail.Message;  
 import javax.mail.MessagingException;  
 import javax.mail.Multipart;  
 import javax.mail.NoSuchProviderException;  
 import javax.mail.PasswordAuthentication;  
 import javax.mail.Session;  
 import javax.mail.Store;  
 import javax.mail.Flags.Flag;  
 import javax.mail.search.FlagTerm;  
 public class ReceiveMail {  
   Properties properties = null;  
   private Session session = null;  
   private Store store = null;  
   private Folder inbox = null;  
   private String userName = "XXXXXX@XXXXXX.com";// provide user name  
   private String password = "XXXXXXXXXX";// provide password  
   public ReceiveMail() {  
   }  
   public void readMails() {  
     properties = new Properties();  
     properties.setProperty("mail.host", "imap.gmail.com");  
     properties.setProperty("mail.port", "995");  
     properties.setProperty("mail.transport.protocol", "imaps");  
     session = Session.getInstance(properties,  
         new javax.mail.Authenticator() {  
           protected PasswordAuthentication getPasswordAuthentication() {  
             return new PasswordAuthentication(userName, password);  
           }  
         });  
     try {  
       store = session.getStore("imaps");  
       store.connect();  
       inbox = store.getFolder("INBOX");  
       inbox.open(Folder.READ_WRITE);  
       // search for all "unseen" messages  
       Flags seen = new Flags(Flags.Flag.SEEN);  
       FlagTerm unseenFlagTerm = new FlagTerm(seen, false);  
       Message messages[] = inbox.search(unseenFlagTerm);  
 //      Message messages[] = inbox.search(new FlagTerm(  
 //          new Flags(Flag.RECENT), false));  
 //        
       System.out.println("Number of mails = " + messages.length);  
                      for (int i = 0; i < messages.length; i++) {  
         Message message = messages[i];  
         Address[] from = message.getFrom();  
         System.out.println("-------------------------------");  
         System.out.println("Date : " + message.getSentDate());  
         System.out.println("From : " + from[0]);  
         System.out.println("Subject: " + message.getSubject());  
         System.out.println("Content : ");  
         processMessageBody(message);  
         System.out.println("--------------------------------");  
       }  
       inbox.close(true);  
       store.close();  
     } catch (NoSuchProviderException e) {  
       e.printStackTrace();  
     } catch (MessagingException e) {  
       //e.printStackTrace();  
          System.out.println("please connect to internet!");  
     }  
   }  
   public void processMessageBody(Message message) {  
     try {  
       Object content = message.getContent();  
       // check for string  
       // then check for multipart  
       if (content instanceof String) {  
         System.out.println(content);  
       } else if (content instanceof Multipart) {  
         Multipart multiPart = (Multipart) content;  
         procesMultiPart(multiPart);  
       } else if (content instanceof InputStream) {  
         InputStream inStream = (InputStream) content;  
         int ch;  
         while ((ch = inStream.read()) != -1) {  
           System.out.write(ch);  
         }      }  
     } catch (IOException e) {  
       e.printStackTrace();  
     } catch (MessagingException e) {  
       e.printStackTrace();  
     }  
   }  
   public void procesMultiPart(Multipart content) {  
     try {  
       int multiPartCount = content.getCount();  
       for (int i = 0; i < multiPartCount; i++) {  
         BodyPart bodyPart = content.getBodyPart(i);  
         Object o;  
         o = bodyPart.getContent();  
         if (o instanceof String) {  
              String[] splited = o.toString().split("<div");  
                       String msg = splited[0];  
                       if(!msg.equals(""))  
           System.out.println(msg);  
         } else if (o instanceof Multipart) {  
           procesMultiPart((Multipart) o);  
         }  
       }  
     } catch (IOException e) {  
       e.printStackTrace();  
     } catch (MessagingException e) {  
       e.printStackTrace();  
     }  
   }  
   public static void notifier(){  
        Runnable helloRunnable = new Runnable() {  
          public void run() {  
            // System.out.println("Hello world");  
                ReceiveMail sample = new ReceiveMail();  
             sample.readMails();  
          }  
        };  
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
        executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);   
   }  
   public static void main(String[] args) {  
        notifier();  
   }  
 }  




Sunday, 18 October 2015

Android restful webservice call and get and parse json data : Login example with php mysql

Most of the mobile apps requires user registration and login. In this tutorial I'm gonna guide you to create a login system for android using the android-async-http-library, which will also store the user login information in local sqlite database.


android login tutorial with php mysql




Steps included are:
1.Creating an xml layout file.
2.Download and add android-async-http-library  to your project.
3.Writing java codes for getting and sending the username and         password from user to server.
4.Writing PHP codes to manage server-side.

copy and paste the below xml to your layout xml file.

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:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin" >  
   <Button  
     android:id="@+id/resetbtn"  
     android:layout_width="100dp"  
     android:layout_height="55dp"  
     android:background="@drawable/bluebutton"  
     android:textColor="#fff"  
     android:textStyle="bold"   
     android:layout_below="@+id/password"  
     android:layout_centerHorizontal="true"  
     android:onClick="register"  
     android:text="Signup" />  
   <EditText  
     android:id="@+id/username"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="78dp"  
     android:ems="10"  
     android:hint="Username" >  
       <EditText  
     android:id="@+id/password"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="78dp"  
       android:inputType="numberPassword"  
     android:ems="10"  
     android:hint="Password" >  
     <requestFocus />  
   </EditText>  
 </RelativeLayout>  


Java:
 package in.creativecodes.loginExample;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import com.loopj.android.http.AsyncHttpClient;  
 import com.loopj.android.http.AsyncHttpResponseHandler;  
 import com.loopj.android.http.RequestParams;  
 import in.wizzo.dataflasher.R;  
 import in.wizzo.dataflasher.R.layout;  
 import in.wizzo.dataflasher.R.menu;  
 import android.os.Bundle;  
 import android.app.Activity;  
 import android.content.Intent;  
 import android.database.sqlite.SQLiteDatabase;  
 import android.view.Menu;  
 import android.view.View;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 public class Login extends Activity {  
      private static String DBNAME = "myCreativeCodes.db";  
      SQLiteDatabase mydb;  
      String username,password;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_login);  
      }  
      public void login(View v) {  
           EditText editText = (EditText) findViewById(R.id.username);  
           username = editText.getText().toString();  
           EditText editText2 = (EditText) findViewById(R.id.password);  
           password = editText2.getText().toString();  
           check();  
      }  
      public void check() {  
           // Create AsycHttpClient object  
           AsyncHttpClient client = new AsyncHttpClient();  
           RequestParams params;  
           // prgDialog.show();  
           params = new RequestParams();  
           params.put("username", username);  
           params.put("password", password);  
           client.post("MYDOMAIN.COM/LOGIN.PHP", params,  
                     new AsyncHttpResponseHandler() {  
                          @Override  
                          public void onSuccess(String response) {  
                               System.out.println(response);  
                               // prgDialog.hide();  
                               try {  
                                    JSONObject arr = new JSONObject(response);  
                                    System.out.println(arr.getInt("success"));  
                                    if (arr.getInt("success") == 1) {  
                                         try {  
                                              mydb = openOrCreateDatabase(DBNAME, 0, null);  
                                              mydb.execSQL("CREATE TABLE IF NOT EXISTS INFO (ID INTEGER PRIMARY KEY, PASSWORD TEXT, USERNAME TEXT);");  
                                              mydb.close();  
                                              mydb = openOrCreateDatabase(DBNAME, 0, null);  
                                              mydb.execSQL("INSERT INTO INFO(USERNAME, PASSWORD) VALUES('"  
                                                        + username + "' , '"+password+"')");  
                                              mydb.close();  
                                              Toast.makeText(getApplicationContext(),  
                                                        "You Had Successfully Registered!",  
                                                        1).show();  
                                              finish();  
                                         } catch (Exception var10_10) {  
                                              Toast.makeText(getApplicationContext(),  
                                                        var10_10.toString(), 1).show();  
                                              return;  
                                         }  
                                    } else {  
                                         Toast.makeText(getApplicationContext(),  
                                                   "Invalid UserName Or Password!", Toast.LENGTH_LONG)  
                                                   .show();  
                                    }  
                               } catch (JSONException e) {  
                                    // TODO Auto-generated catch block  
                                    Toast.makeText(  
                                              getApplicationContext(),  
                                              "Error Occured [Server's JSON response might be invalid]!",  
                                              Toast.LENGTH_LONG).show();  
                                    e.printStackTrace();  
                               }  
                          }  
                          @Override  
                          public void onFailure(int statusCode, Throwable error,  
                                    String content) {  
                               // TODO Auto-generated method stub  
                               // prgDialog.hide();  
                               if (statusCode == 404) {  
                                    Toast.makeText(getApplicationContext(),  
                                              "Requested resource not found",  
                                              Toast.LENGTH_LONG).show();  
                               } else if (statusCode == 500) {  
                                    Toast.makeText(getApplicationContext(),  
                                              "Something went wrong at server end",  
                                              Toast.LENGTH_LONG).show();  
                               } else {  
                                    Toast.makeText(  
                                              getApplicationContext(),  
                                              "Please connect to Internet and try again!",  
                                              Toast.LENGTH_LONG).show();  
                               }  
                          }  
                     });  
      }  
 }  

PHP:

login.php

 <?php  
 // array for JSON response  
 $response = array();  
 // include db connect class  
 require_once __DIR__ . '/db_connect.php';  
 // connecting to db  
 $db = new DB_CONNECT();  
 // check for post data  
 if (isset($_POST['username']) && isset($_POST['password'])) {  
   $username = $_POST['username'];  
   $password = $_POST['password'];  
   // get a product from products table  
   $result = mysql_query("SELECT * FROM users WHERE USERNAME = '$username' AND PASSWORD = '$password'");  
   if (!empty($result)) {  
     // check for empty result  
     if (mysql_num_rows($result) > 0) {  
       $response["success"] = 1;  
       // echoing JSON response  
       echo json_encode($response);  
     } else {  
       // no product found  
       $response["success"] = 0;  
       $response["message"] = "No user found";  
       // echo no users JSON  
       echo json_encode($response);  
     }  
   } else {  
     // no product found  
     $response["success"] = 0;  
     $response["message"] = "No user found";  
     // echo no users JSON  
     echo json_encode($response);  
   }  
 } else {  
   // required field is missing  
   $response["success"] = 0;  
   $response["message"] = "Required field(s) is missing";  
   // echoing JSON response  
   echo json_encode($response);  
 }  
 ?>  

db_connect.php
 <?php  
 /*  
 we are connecting to the database using the information in db_config.php file  
 */  
 class DB_CONNECT {  
   function __construct() {  
     $this->connect();  
   }  
   function __destruct() {  
     $this->close();  
   }  
   function connect() {  
     require_once __DIR__ . '/db_config.php';  
     $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());  
     $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());  
     return $con;  
   }  
   function close() {  
     mysql_close();  
   }  
 }  
 ?>  

db_config.php
 <?php  
 /*  
  * All database connection details  
  */  
 define('DB_USER', "root"); // your database username  
 define('DB_PASSWORD', "root"); // your database password  
 define('DB_DATABASE', "mydb"); // your database name  
 define('DB_SERVER', "localhost"); // your database server  
 ?>  

That's all, the login system is completed. Your questions maybe dropped as comments. Thankyou!




Saturday, 17 October 2015

Android: Alert using 'Toast' and 'Alert Dialogue'

   Alert has a wide number of uses in every app such as to show 'exit confirmation', 'do you want to continue', to show offers, etc... the endless uses of alert continues.. In android platform we have mainly to kinds of alert which are 'toast' and  alert using 'Builder'

Alert Dialogue 
   Its a bit advanced alert which popups and disappears after user action. You could have a title, message and buttons
in it.



   Consider the below code! Replace the MainActivity with your activity, "Confirm Exit..." with your title and "Are you sure to exit?" with your description. "YES" and "NO" are the texts to be shown on the buttons.

In the below code you could also call your methods which you want to trigger on pressing respective buttons.


Java:
 public void rYouSureToExit() {  
           Builder var6 = new Builder(MainActivity.this);  
           var6.setTitle("Confirm Exit...");  
           var6.setMessage("Are you sure to exit?");  
           var6.setPositiveButton("YES",  
                     new android.content.DialogInterface.OnClickListener() {  
                          public void onClick(DialogInterface var1, int var2) {  
                               finish();  
                          }  
                     });  
           var6.setNegativeButton("NO",  
                     new android.content.DialogInterface.OnClickListener() {  
                          public void onClick(DialogInterface var1, int var2) {  
                               var1.cancel();  
                          }  
                     });  
           var6.show();  
      }  

Toast
 Its a simple alert which popups and disappears after a fixed time. You could add a message body to it.


Java:
 Toast.makeText(getApplicationContext(),"This is a toast!", 1).show();  


Thursday, 15 October 2015

Android Custom ListView with SimpleAdapter – creating a table in android using listview

       Most of your application will be having a table or a table model listview. With the availability of a simple adapter you could achieve it in a simple manner. This tutorial will guide you to create a well arranged tabular listview with the help of a simpleAdapter for you android application.
.

Java:
        *Add the below code to your activity class; and call it to update the list view
public void LoadData() {  
     ListView listview1;  
     ArrayList arraylist = new ArrayList();  
     arraylist.clear();  
     listview1 = (ListView) findViewById(R.id.listview1);  
     HashMap<String, String> country;  
         For(intx=0;x<10;x++){  
             String title = cursor.getString(4);  
             String desc = cursor.getString(3);  
             String value = cursor.getString(2);  
             country = new HashMap<String, String>();  
             country.put("title", title);  
             country.put("desc", desc);  
             country.put("value", value);  
             arraylist.add(country);  
                     }  
     listview1.setAdapter(new SimpleAdapter(this, arraylist, R.layout. custom_row.xml, new String[] { "title", "desc","value” }, new int[] { R.id.title, R.id.desc, R.id.value }));  
     }  
       
XML:
        *create a custom_row.xml in layout directory and copy past the below code. This layout contains the custom resources to hold the values.

 <?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="wrap_content"  
   android:orientation="horizontal"  
   android:paddingBottom="6.0dip"  
   android:paddingTop="4.0dip" >  
   <TextView  
     android:id="@+id/title"  
     android:layout_width="36dp"  
     android:layout_height="wrap_content"  
     android:text="title"  
     android:textSize="17dp" />  
   <TextView  
     android:id="@+id/desc"  
     android:layout_width="81dp"  
     android:layout_height="wrap_content"  
     android:layout_marginLeft="5dp"  
     android:text="desc"  
     android:textSize="17dp" />  
   <TextView  
     android:id="@+id/value"  
     android:layout_width="70dp"  
     android:layout_height="wrap_content"  
     android:layout_marginLeft="3dp"  
     android:text="value"  
     android:textSize="17dp" />  
 </LinearLayout>  


         * And finally add a listview to your activity layout file. copy past the below code to you layout xml file.
 <ListView  
     android:id="@+id/listview1"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content" >