Sunday, September 21, 2014

Android ViewPager Tab bar | Android ActionBar Tab bar | Android Scroll + Tab

Hello Friends,

Today I am going to share demo application for Viewpager+Tab Bar in android. For this I am using minimum android version 11 because android fragment support above version 11. you can use support fragment also.

For more detail follow the blow link


1)MainActivity

package com.androidhub4you.viewpager;

import java.util.Locale;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends FragmentActivity implements
              ActionBar.TabListener {

       SectionsPagerAdapter mSectionsPagerAdapter;

       /**
        * The {@link ViewPager} that will host the section contents.
        */
       ViewPager mViewPager;

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

              // Set up the action bar.
              final ActionBar actionBar = getActionBar();
              actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

              // Create the adapter that will return a fragment for each of the three
              // primary sections of the app.
              mSectionsPagerAdapter = new SectionsPagerAdapter(
                           getSupportFragmentManager());

              // Set up the ViewPager with the sections adapter.
              mViewPager = (ViewPager) findViewById(R.id.pager);
              mViewPager.setAdapter(mSectionsPagerAdapter);

              // When swiping between different sections, select the corresponding
              // tab. We can also use ActionBar.Tab#select() to do this if we have
              // a reference to the Tab.
              mViewPager
                           .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                                  @Override
                                  public void onPageSelected(int position) {
                                         actionBar.setSelectedNavigationItem(position);
                                  }
                           });

              // For each of the sections in the app, add a tab to the action bar.
              for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
                     // Create a tab with text corresponding to the page title defined by
                     // the adapter. Also specify this Activity object, which implements
                     // the TabListener interface, as the callback (listener) for when
                     // this tab is selected.
                     actionBar.addTab(actionBar.newTab()
                                  .setText(mSectionsPagerAdapter.getPageTitle(i))
                                  .setTabListener(this));
              }
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }

       @Override
       public void onTabSelected(ActionBar.Tab tab,
                     FragmentTransaction fragmentTransaction) {
              // When the given tab is selected, switch to the corresponding page in
              // the ViewPager.
              mViewPager.setCurrentItem(tab.getPosition());
       }

       @Override
       public void onTabUnselected(ActionBar.Tab tab,
                     FragmentTransaction fragmentTransaction) {
       }

       @Override
       public void onTabReselected(ActionBar.Tab tab,
                     FragmentTransaction fragmentTransaction) {
       }

       /**
        * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
        * one of the sections/tabs/pages.
        */
       public class SectionsPagerAdapter extends FragmentPagerAdapter {

              public SectionsPagerAdapter(FragmentManager fm) {
                     super(fm);
              }

              @Override
              public Fragment getItem(int position) {
                     // getItem is called to instantiate the fragment for the given page.
                     // Return a DummySectionFragment (defined as a static inner class
                     // below) with the page number as its lone argument.
                     Fragment fragment=null;
                     if(position==0){
                           fragment = new HomeFragment();
                     }
                     else if(position==1){
                           fragment=new AboutFragment();
                     }
                     else if(position==2){
                           fragment=new ContactsFragment();
                     }
                     return fragment;
              }

              @Override
              public int getCount() {
                     // Show 3 total pages.
                     return 3;
              }

              @Override
              public CharSequence getPageTitle(int position) {
                     Locale l = Locale.getDefault();
                     switch (position) {
                     case 0:
                           return getString(R.string.title_section1).toUpperCase(l);
                     case 1:
                           return getString(R.string.title_section2).toUpperCase(l);
                     case 2:
                           return getString(R.string.title_section3).toUpperCase(l);
                     }
                     return null;
              }
       }


}


2)HomeFragment

package com.androidhub4you.viewpager;

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

public class HomeFragment extends Fragment {
      
       public HomeFragment() {
       }

       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
              View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                           container, false);
              TextView dummyTextView = (TextView) rootView
                           .findViewById(R.id.section_label);
              dummyTextView.setText("HOME PAGE");
              return rootView;
       }
}





Thanks,
Manish




Monday, September 1, 2014

android camera: onActivityResult() intent is null | android camera data.getData()==null

Hi Friends,

Today I am sharing code for camera crash in android. Its happen in case of if your data is null inside onActivityResult(). For this issue I created a temporary file path and then save captured image on that location and after that inside onActivityResult() we get the URI form that patrh. Try below code hope it will help you- 



1)MainActivity.java

package camera.nullpointer.androidhub4you.solution;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
 *
 * @author manishs
 *
 */
public class MainActivity extends Activity implements OnClickListener {

       private Button btnCamera;
       private ImageView imageView;
       private String _imageCapturedName = null;
       private File fileName = null;
       private final int TAKE_FRONT_PHOTO = 1;

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              btnCamera = (Button) findViewById(R.id.button_camera);
              imageView = (ImageView) findViewById(R.id.imageView1);

              btnCamera.setOnClickListener(this);

       }

       @Override
       public void onClick(View arg0) {
              // TODO Auto-generated method stub
              switch (arg0.getId()) {
              case R.id.button_camera:
                     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                     _imageCapturedName = "Image_"
                                  + String.valueOf(System.currentTimeMillis());
                     fileName = Helper.createFileInSDCard(Helper.getTempFile()
                                  + "=TestFolder/", _imageCapturedName + ".JPG");

                     intent = new Intent("android.media.action.IMAGE_CAPTURE").putExtra(
                                  android.provider.MediaStore.EXTRA_OUTPUT,
                                  Uri.fromFile(new File(fileName.toString())));
                     // ******** code for crop image
                     intent.putExtra("crop", "true");
                     intent.putExtra("aspectX", 0);
                     intent.putExtra("aspectY", 0);
                     intent.putExtra("outputX", 200);
                     intent.putExtra("outputY", 150);
                     //Read more: http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html#ixzz3C3ka12wl
                     startActivityForResult(intent, TAKE_FRONT_PHOTO);
                     break;
             
              }

       }

       @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              super.onActivityResult(requestCode, resultCode, data);
              if (resultCode == RESULT_OK) {
                     switch (requestCode) {
                     case TAKE_FRONT_PHOTO:
                           saveImage(TAKE_FRONT_PHOTO);
                           break;
                    
                     }
              }
       }


       private void saveImage(int requestCode) {
              try {

                     Bitmap bitmap = Helper.decodeFile(fileName);
                     bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true);
                     ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                     bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);

                     File f = new File(fileName.toString());
                     FileOutputStream fo = new FileOutputStream(f);
                     fo.write(bytes.toByteArray());

                     fo.flush();
                     fo.close();

                     // _bcardFront=fileName.toString();
                     imageView.setImageBitmap(bitmap);

              } catch (Exception e) {
                     e.printStackTrace();
              } catch (OutOfMemoryError o) {
                     o.printStackTrace();

              }

       }


}


2)Helper.java

package camera.nullpointer.androidhub4you.solution;

import java.io.File;
import java.io.FileInputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class Helper {

       public static String getTempFile() {
              return Environment.getExternalStorageDirectory().getPath()    + "/Androidhub4you/";

       }
      
       public static File createFileInSDCard(String path,String fileName){
              File dir = new File(path);
              try{
                     if(!dir.exists() && dir.mkdirs()) {
                           System.out.println("Directory created");
                     } else {
                           System.out.println("Directory is not created");
                     }
              }catch(Exception e){
                     e.printStackTrace();
              }
              File file = null;
              try {
                     if(dir.exists()){
                           file=new File(dir, fileName);
                           file.createNewFile();
                     }else{

                     }
              }catch (Exception e1) {
                     e1.printStackTrace();
              }
              return file;
       }
      
       public static Bitmap decodeFile(File f) {
              Bitmap b = null;
              final int IMAGE_MAX_SIZE = 400;
              try {
                     BitmapFactory.Options o = new BitmapFactory.Options();
                     o.inJustDecodeBounds = true;
                     FileInputStream fis = new FileInputStream(f);
                     BitmapFactory.decodeStream(fis, null, o);
                     fis.close();
                     int scale = 1;
                     if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                           scale = (int) Math.pow(2.0, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
                     }
                     BitmapFactory.Options o2 = new BitmapFactory.Options();
                     o2.inSampleSize = scale;
                     fis = new FileInputStream(f);
                     b = BitmapFactory.decodeStream(fis, null, o2);
                     fis.close();
              } catch (Exception e) {
              }
              return b;
       }
}



Thanks,
Manish