Tuesday, 15 March 2016

Drawer in material design

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="@dimen/margin_10dp"
            >

            
        </FrameLayout>

    </LinearLayout>
     <!-- The navigation drawer -->
    <ListView
        android:id="@+id/navdrawer"
        android:layout_width="@dimen/navdrawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0.5dp"
        android:drawSelectorOnTop="false"
        android:layerType="software"></ListView>


</android.support.v4.widget.DrawerLayout>



public class DrawerItems {

    String titel;
    String nmae;
    int image;
    String headerTitle;
    int headerIcon;
    String count="0";
    int jj;
    String add="";
    private boolean isCounterVisible = false;


    public String getAdd() {
        return add;
    }

    public void setAdd(String add) {
        this.add = add;
    }

    public String getHeaderTitle() {
        return headerTitle;
    }

    public void setHeaderTitle(String headerTitle) {
        this.headerTitle = headerTitle;
    }

    public int getHeaderIcon() {
        return headerIcon;
    }

    public void setHeaderIcon(int headerIcon) {
        this.headerIcon = headerIcon;
    }

    public int getJj() {
        return jj;
    }

    public void setJj(int jj) {
        this.jj = jj;
    }

    public boolean getCounterVisibility(){
        return this.isCounterVisible;
    }

    public void setCounterVisibility(boolean isCounterVisible){
        this.isCounterVisible = isCounterVisible;
    }
    public DrawerItems() {
        // TODO Auto-generated constructor stub
    }
    public DrawerItems(String title) {
        // TODO Auto-generated constructor stub
        titel=title;

    }

    public DrawerItems(String name, int imag) {
        // TODO Auto-generated constructor stub
        nmae=name;
        image=imag;
    }

    public DrawerItems(String name, int imag, Boolean b, String mString) {
        // TODO Auto-generated constructor stub
        nmae=name;
        image=imag;
        count=mString;
    }
    public DrawerItems(String name, Boolean b, String mString) {
        // TODO Auto-generated constructor stub
        nmae=name;
        count=mString;
    }

    public DrawerItems(String name, int imag, String mString, String add) {
        // TODO Auto-generated constructor stub
        nmae=name;
        image=imag;
        count=mString;
        this.add=add;
    }

    public DrawerItems(String string, int i, int btnSearch) {
        // TODO Auto-generated constructor stub
        jj=i;
        headerTitle=string;
        headerIcon=btnSearch;

    }



    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    public String getTitel() {
        return titel;
    }
    public void setTitel(String titel) {
        this.titel = titel;
    }
    public String getNmae() {
        return nmae;
    }
    public void setNmae(String nmae) {
        this.nmae = nmae;
    }
    public int getImage() {
        return image;
    }
    public void setImage(int image) {
        this.image = image;
    }

}

public class ActionBarDrawerToggle extends android.support.v4.app.ActionBarDrawerToggle {

    private static final String TAG = ActionBarDrawerToggle.class.getName();

    protected Activity mActivity;
    protected DrawerLayout mDrawerLayout;

    protected int mOpenDrawerContentDescRes;
    protected int mCloseDrawerContentDescRes;
    protected DrawerArrowDrawable mDrawerImage;
    protected boolean animateEnabled;

    public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int drawerImageRes, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
        super(activity, drawerLayout, drawerImageRes, openDrawerContentDescRes, closeDrawerContentDescRes);
    }

    public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, DrawerArrowDrawable drawerImage, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
        super(activity, drawerLayout, R.drawable.ic_launcher , openDrawerContentDescRes, closeDrawerContentDescRes);
        mActivity = activity;
        mDrawerLayout = drawerLayout;
        mOpenDrawerContentDescRes = openDrawerContentDescRes;
        mCloseDrawerContentDescRes = closeDrawerContentDescRes;
        mDrawerImage = drawerImage;
        animateEnabled = true;
    }

    public void syncState() {
        if (mDrawerImage == null) {
            super.syncState();
            return;
        }
        if (animateEnabled) {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerImage.setProgress(1.f);
            } else {
                mDrawerImage.setProgress(0.f);
            }
        }
        setActionBarUpIndicator();
        setActionBarDescription();
    }

    public void setDrawerIndicatorEnabled(boolean enable) {
        if (mDrawerImage == null) {
            super.setDrawerIndicatorEnabled(enable);
            return;
        }
        setActionBarUpIndicator();
        setActionBarDescription();
    }

    public boolean isDrawerIndicatorEnabled() {
        if (mDrawerImage == null) {
            return super.isDrawerIndicatorEnabled();
        }
        return true;
    }

    public void onConfigurationChanged(Configuration newConfig) {
        if (mDrawerImage == null) {
            super.onConfigurationChanged(newConfig);
            return;
        }
        syncState();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override    public void onDrawerSlide(View drawerView, float slideOffset) {
        if (mDrawerImage == null) {
            super.onDrawerSlide(drawerView, slideOffset);
            return;
        }
        if (animateEnabled) {
            mDrawerImage.setVerticalMirror(!mDrawerLayout.isDrawerOpen(GravityCompat.START));
            mDrawerImage.setProgress(slideOffset);
        }
    }

    @Override    public void onDrawerOpened(View drawerView) {
        if (mDrawerImage == null) {
            super.onDrawerOpened(drawerView);
            return;
        }
        if (animateEnabled) {
            mDrawerImage.setProgress(1.f);
        }
        setActionBarDescription();
    }

    @Override    public void onDrawerClosed(View drawerView) {
        if (mDrawerImage == null) {
            super.onDrawerClosed(drawerView);
            return;
        }
        if (animateEnabled) {
            mDrawerImage.setProgress(0.f);
        }
        setActionBarDescription();
    }

    protected void setActionBarUpIndicator() {
        if (mActivity != null) {
            try {
                Method setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator",
                        Drawable.class);
                setHomeAsUpIndicator.invoke(mActivity.getActionBar(), mDrawerImage);
                return;
            } catch (Exception e) {
                Log.e(TAG, "setActionBarUpIndicator error", e);
            }

            final View home = mActivity.findViewById(android.R.id.home);
            if (home == null) {
                return;
            }

            final ViewGroup parent = (ViewGroup) home.getParent();
            final int childCount = parent.getChildCount();
            if (childCount != 2) {
                return;
            }

            final View first = parent.getChildAt(0);
            final View second = parent.getChildAt(1);
            final View up = first.getId() == android.R.id.home ? second : first;

            if (up instanceof ImageView) {
                ImageView upV = (ImageView) up;
                upV.setImageDrawable(mDrawerImage);
            }
        }
    }

    protected void setActionBarDescription() {
        if (mActivity != null && mActivity.getActionBar() != null) {
            try {
                Method setHomeActionContentDescription = ActionBar.class.getDeclaredMethod(
                        "setHomeActionContentDescription", Integer.TYPE);
                setHomeActionContentDescription.invoke(mActivity.getActionBar(),
                        mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mOpenDrawerContentDescRes : mCloseDrawerContentDescRes);
                if (Build.VERSION.SDK_INT <= 19) {
                    mActivity.getActionBar().setSubtitle(mActivity.getActionBar().getSubtitle());
                }
            } catch (Exception e) {
                Log.e(TAG, "setActionBarUpIndicator", e);
            }
        }
    }

    public void setAnimateEnabled(boolean enabled) {
        this.animateEnabled = enabled;
    }

    public boolean isAnimateEnabled() {
        return this.animateEnabled;
    }

}


public abstract class DrawerArrowDrawable extends Drawable {
    private static final float ARROW_HEAD_ANGLE = (float) Math.toRadians(45.0D);
    protected float mBarGap;
    protected float mBarSize;
    protected float mBarThickness;
    protected float mMiddleArrowSize;
    protected final Paint mPaint = new Paint();
    protected final Path mPath = new Path();
    protected float mProgress;
    protected int mSize;
    protected float mVerticalMirror = 1f;
    protected float mTopBottomArrowSize;
    protected Context context;

    public DrawerArrowDrawable(Context context) {
        this.context = context;
        this.mPaint.setAntiAlias(true);
        this.mPaint.setColor(context.getResources().getColor(R.color.ldrawer_color));
        this.mSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_drawableSize);
        this.mBarSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_barSize);
        this.mTopBottomArrowSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_topBottomBarArrowSize);
        this.mBarThickness = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_thickness);
        this.mBarGap = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_gapBetweenBars);
        this.mMiddleArrowSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_middleBarArrowSize);
        this.mPaint.setStyle(Paint.Style.STROKE);
        this.mPaint.setStrokeJoin(Paint.Join.ROUND);
        this.mPaint.setStrokeCap(Paint.Cap.SQUARE);
        this.mPaint.setStrokeWidth(this.mBarThickness);
    }

    protected float lerp(float paramFloat1, float paramFloat2, float paramFloat3) {
        return paramFloat1 + paramFloat3 * (paramFloat2 - paramFloat1);
    }

    public void draw(Canvas canvas) {
        Rect localRect = getBounds();
        float f1 = lerp(this.mBarSize, this.mTopBottomArrowSize, this.mProgress);
        float f2 = lerp(this.mBarSize, this.mMiddleArrowSize, this.mProgress);
        float f3 = lerp(0.0F, this.mBarThickness / 2.0F, this.mProgress);
        float f4 = lerp(0.0F, ARROW_HEAD_ANGLE, this.mProgress);
        float f5 = 0.0F;
        float f6 = 180.0F;
        float f7 = lerp(f5, f6, this.mProgress);
        float f8 = lerp(this.mBarGap + this.mBarThickness, 0.0F, this.mProgress);
        this.mPath.rewind();
        float f9 = -f2 / 2.0F;
        this.mPath.moveTo(f9 + f3, 0.0F);
        this.mPath.rLineTo(f2 - f3, 0.0F);
        float f10 = (float) Math.round(f1 * Math.cos(f4));
        float f11 = (float) Math.round(f1 * Math.sin(f4));
        this.mPath.moveTo(f9, f8);
        this.mPath.rLineTo(f10, f11);
        this.mPath.moveTo(f9, -f8);
        this.mPath.rLineTo(f10, -f11);
        this.mPath.moveTo(0.0F, 0.0F);
        this.mPath.close();
        canvas.save();
        if (!isLayoutRtl())
            canvas.rotate(180.0F, localRect.centerX(), localRect.centerY());
        canvas.rotate(f7 * mVerticalMirror, localRect.centerX(), localRect.centerY());
        canvas.translate(localRect.centerX(), localRect.centerY());
        canvas.drawPath(this.mPath, this.mPaint);
        canvas.restore();
    }

    public int getIntrinsicHeight() {
        return this.mSize;
    }

    public int getIntrinsicWidth() {
        return this.mSize;
    }

    public void setAlpha(int alpha) {
        this.mPaint.setAlpha(alpha);
    }

    @Override    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    public abstract boolean isLayoutRtl();

    public void setColorFilter(ColorFilter colorFilter) {
        this.mPaint.setColorFilter(colorFilter);
    }

    public void setVerticalMirror(boolean mVerticalMirror) {
        this.mVerticalMirror = mVerticalMirror ? 1 : -1;
    }

    public void setProgress(float paramFloat) {
        this.mProgress = paramFloat;
        invalidateSelf();
    }

    public void setColor(int resourceId) {
        this.mPaint.setColor(context.getResources().getColor(resourceId));
    }
}
 
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;

import java.util.ArrayList;
import java.util.Stack;

import adapter.ReviewPager;
import parser.GetUserData;
import slider.SlidingTabLayout;


public class ActivityDrawer extends AppCompatActivity implements ObservableScrollViewCallbacks {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerArrowDrawable drawerArrow;
    private Stack<Fragment> fragmentStack;
    private boolean drawerArrowColor;
    View mViewHeader;
    private View mHeaderView;
    //private View mToolbarView;
    //private ObservableScrollView mScrollView;

    TextView mTextViewHeaderName;
    TextView mTextViewHeaderEmail;
    public ArrayList<DrawerItems> mArrayList;
    ProgressDialog mProgressDialog;
    DrawerListAdapter mDrawerListAdapter;
    Activity mActivity;
    boolean draweropen = false;
    boolean pindone = false;
    LayoutInflater inflater;
    ViewGroup header;
    ViewGroup footer;
    RelativeLayout mRelativeLayoutDraqwerTopHeader;
    ImageView mImageViewMenu;
    Toolbar tb;


    RelativeLayout mRelativeLayoutCart;
    ViewPager pager;
    SlidingTabLayout tabs;
    private ReviewPager adapter;
     ImageView mImageViewAddTour;
    String mStringUName;
    String mStringPassword;
    String mStringEmail;
    String mStringFName;
    String mStringLName;
    PostParseGet mPostParseGet;
    GetUserData mGetUserData;

      @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample2);
        tb = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(tb);
        tb.setTitleTextColor(Color.WHITE);
        android.support.v7.app.ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.navigation);
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CAF50")));
        ab.setTitle("Tour App");
        ab.setDisplayHomeAsUpEnabled(true);
        mActivity = this;
        ab.setHomeButtonEnabled(true);
 
        
         
 
 
         
 
        
         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
         mDrawerList = (ListView) findViewById(R.id.navdrawer);
        inflater = getLayoutInflater();
        mViewHeader = (ViewGroup) inflater.inflate(R.layout.header_drawer, mDrawerList,
                false);
        mDrawerList.addHeaderView(mViewHeader);

         mTextViewHeaderEmail=(TextView)mViewHeader.findViewById(R.id.txt_name);
         mTextViewHeaderName=(TextView)mViewHeader.findViewById(R.id.txt_email);

         mTextViewHeaderEmail.setText(mStringEmail);
         mTextViewHeaderName.setText(mStringFName+ " "+mStringLName);
        /*inflater = getLayoutInflater();
        header = (ViewGroup) inflater.inflate(R.layout.drawer_header, mDrawerList,
                false);
        footer = (ViewGroup) inflater.inflate(R.layout.drawer_footer, mDrawerList,
                false);
        mRelativeLayoutDraqwerTopHeader = (RelativeLayout) header.findViewById(R.id.rel_header);
        mRelativeLayoutDraqwerTopHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                *//*if (draweropen==true)
                {*//*
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                   *//* draweropen=false;

                }*//*
            }

        });
        mDrawerList.addHeaderView(header, null, false);
        mDrawerList.addFooterView(footer, null, false);*/
       /* mDrawerList.setIndicatorBounds(240 - GetDipsFromPixel(35), 240 - GetDipsFromPixel(5));*/

        //mDrawerList.setIndicatorBounds(330-GetDipsFromPixel(35), 330-GetDipsFromPixel(5));

        // mDrawerList.setAdapter(new NewAdapter(this, groupItem, childItem));

        /*if (mAllMethods.check_Internet()==true)
        {
            new getCateList().execute();
        }
        else
        {
            mAllMethods.ShowDialog(DrawerActivity.this, getString(R.string.val_error), getString(R.string.network_not_avl), "OK");
        }*/
        mArrayList = new ArrayList<DrawerItems>();
        //mArrayListCategoryListDatas=new ArrayList<GetCategory.CategoryListData>();
       /* mDrawerListAdapter=new DrawerListAdapter(DrawerActivity.this);
       // mDrawerListAdapter=new DrawerListAdapter(DrawerActivity.this,mArrayListCategoryListDatas);
        mDrawerList.setAdapter(mDrawerListAdapter);*/
        //listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);


        mArrayList = new ArrayList<>();
        mArrayList.add(new DrawerItems("ADD NEW TOUR", R.drawable.icon_drawer_tour, true, "-1"));
        mArrayList.add(new DrawerItems("MY PROFILE", R.drawable.icon_drawer_profile, true, "-1"));
        mArrayList.add(new DrawerItems("LOGOUT", R.drawable.icon_drawer_logout, true, "-1"));
        mDrawerListAdapter = new DrawerListAdapter(ActivityDrawer.this, mArrayList);
        mDrawerList.setAdapter(mDrawerListAdapter);

        drawerArrow = new DrawerArrowDrawable(ActivityDrawer.this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };
        mDrawerToggle = new ActionBarDrawerToggle(ActivityDrawer.this, mDrawerLayout,
                drawerArrow, R.string.drawer_open,
                R.string.drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                draweropen = false;
                // mAllMethods.hideSoftKeyboard(DrawerActivity.this);
                // invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                draweropen = true;
                //mAllMethods.hideSoftKeyboard(DrawerActivity.this);
                // mDrawerListAdapter.loadData();
                //invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
        if (savedInstanceState == null) {
            /*FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, new HomeFragmentTest());
            ft.commit();*/
        }







       /* // Listview Group click listener
        mDrawerList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // Listview Group expanded listener
        mDrawerList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + " Expanded",
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Listview Group collasped listener
        mDrawerList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + " Collapsed",
                        Toast.LENGTH_SHORT).show();

            }
        });

        // Listview on child click listener
        mDrawerList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(
                        getApplicationContext(),
                        listDataHeader.get(groupPosition)
                                + " : "
                                + listDataChild.get(
                                listDataHeader.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });
*/


        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

              /*  Intent mIntent = new Intent(ActivityDrawer.this, ActivityCategoryList.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(mIntent);*/

                mDrawerLayout.closeDrawer(mDrawerList);

                if (position == 1) {
                    Intent mIntent = new Intent(ActivityDrawer.this, ActivityTourAdd.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mIntent);
                } else if (position == 2) {
                    Intent mIntent = new Intent(ActivityDrawer.this, ActivityMyProfile.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mIntent);
                } else if (position == 3) {
                    SharedPreferences myPrefs = getSharedPreferences("tourpref", MODE_WORLD_READABLE);
                    SharedPreferences.Editor prefsEditor = myPrefs.edit();
                    prefsEditor.putBoolean("islogin", false);
                    prefsEditor.commit();

                    Intent mIntent1=new Intent(ActivityDrawer.this,ActivityLogin.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(mIntent1);
                }

                /*if (position==1)
                {
                    FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                    ft.replace(R.id.content_frame, new HomeFragment());
                    ft.commit();
                    mDrawerList.setItemChecked(position, true);
                    mDrawerLayout.closeDrawer(mDrawerList);
                }
                else  if (position==2)
                {
                    Intent mIntent=new Intent(ActivityDrawer.this,ActivityCategory.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mIntent);
                    mDrawerLayout.closeDrawer(mDrawerList);
                }*/
                //selectItem(position);
            }
        });

    }


   /* public class  getCateList extends AsyncTask<Void,Void,Void>    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog=ProgressDialog.show(DrawerActivity.this,"Wait","Loading");
        }


        @Override
        protected Void doInBackground(Void... voids) {
            mGetCategory=(GetCategory)mPostParseGet.categoryList(mGetCategory);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (mProgressDialog!=null)
            {
                mProgressDialog.dismiss();
            }
            if (mGetCategory!=null)
            {
                if (mGetCategory.getRes_obj().getCategorylist().size()>0)
                {
                    mArrayListCategoryListDatas=getData();

                 //   mArrayList.add(new DrawerItems("Dashboard"));
                    System.out.println("mArrayListCategoryListDatas "+mArrayListCategoryListDatas.size());
                    mDrawerListAdapter=new DrawerListAdapter(DrawerActivity.this,mArrayListCategoryListDatas);
                    mDrawerList.setAdapter(mDrawerListAdapter);
                    drawerArrow = new DrawerArrowDrawable(DrawerActivity.this) {
                        @Override
                        public boolean isLayoutRtl() {
                            return false;
                        }
                    };
                    mDrawerToggle = new ActionBarDrawerToggle(DrawerActivity.this, mDrawerLayout,
                            drawerArrow, R.string.drawer_open,
                            R.string.drawer_close) {

                        public void onDrawerClosed(View view) {
                            super.onDrawerClosed(view);
                            mAllMethods.hideSoftKeyboard(DrawerActivity.this);
                            invalidateOptionsMenu();
                        }

                        public void onDrawerOpened(View drawerView) {
                            super.onDrawerOpened(drawerView);
                            mAllMethods.hideSoftKeyboard(DrawerActivity.this);
                            mDrawerListAdapter.loadData();
                            invalidateOptionsMenu();
                        }
                    };
                    mDrawerLayout.setDrawerListener(mDrawerToggle);
                    mDrawerToggle.syncState();


                }
            }

        }


    }*/

    /*public ArrayList<GetCategory.CategoryListData> getData() {

        ArrayList<GetCategory.CategoryListData> mArrayListParserLog = new ArrayList<GetCategory.CategoryListData>();
        String  mString="";
        for (int i = 0; i < mGetCategory.getRes_obj().getCategorylist().size(); i++) {
            GetCategory.CategoryListData mParserLog = new GetCategory.CategoryListData();
            mParserLog.setBusi_count(mGetCategory.getRes_obj().getCategorylist().get(i).getBusi_count());
            mParserLog.setMain_id(mGetCategory.getRes_obj().getCategorylist().get(i).getMain_id());
            mParserLog.setMain_name(String.valueOf(Html.fromHtml(mGetCategory.getRes_obj().getCategorylist().get(i).getMain_name())));
            mParserLog.setParent_id(mGetCategory.getRes_obj().getCategorylist().get(i).getParent_id());
            mArrayListCategoryListDatas.add(mParserLog);

        }
        return mArrayListCategoryListDatas;
    }*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {

            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }


    private void selectItem(int position) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        // Locate Position
        switch (position) {


            default:

                /* ft.replace(R.id.content_frame, new HomeFragmentTest());
                ft.commit();*/
                break;

        }

        mDrawerList.setItemChecked(position, true);
        mDrawerLayout.closeDrawer(mDrawerList);


    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
       /* if (dragging) {
            //int toolbarHeight = mToolbarView.getHeight();
            int toolbarHeight = tb.getHeight();

            if (firstScroll) {
                float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
                if (-toolbarHeight < currentHeaderTranslationY) {
                    mBaseTranslationY = scrollY;
                }
            }
            float headerTranslationY = ScrollUtils.getFloat(-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
            ViewPropertyAnimator.animate(mHeaderView).cancel();
            ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
        }*/
    }

    @Override
    public void onDownMotionEvent() {
    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {


    }

    private boolean toolbarIsShown() {
        return ViewHelper.getTranslationY(mHeaderView) == 0;
    }

    private boolean toolbarIsHidden() {

        return ViewHelper.getTranslationY(mHeaderView) == -tb.getHeight();

    }

    private void showToolbar() {
        float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
        if (headerTranslationY != 0) {
            ViewPropertyAnimator.animate(mHeaderView).cancel();
            ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
        }
    }

    private void hideToolbar() {
        float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
        //int toolbarHeight = mToolbarView.getHeight();
        int toolbarHeight = tb.getHeight();

        if (headerTranslationY != -toolbarHeight) {
            ViewPropertyAnimator.animate(mHeaderView).cancel();
            ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
        }
    }


    public class DrawerListAdapter extends BaseAdapter {


        //      private FragmentActivity context;
        Activity mActivity2;
        private String[] mtitle;
        private String[] msubTitle;
        private int[] micon;
        private LayoutInflater inflater;
        ArrayList<DrawerItems> list;
        int mode;
        AllMethods mAllMethods;
        Activity mActivity;

        public DrawerListAdapter(Activity applicationContext, ArrayList<DrawerItems> dataList) {

            list = dataList;
            mActivity = applicationContext;
            mAllMethods = new AllMethods(mActivity);
        }

        public void loadData() {


            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(final int position, View arg1, ViewGroup parent) {

            TextView title;
            TextView subtitle;
            ImageView icon;
            LinearLayout itemLayouyt;
            ImageView mImageViewHeaderIcon;
            LinearLayout headet;
             DrawerItems dItem = (DrawerItems) this.list.get(position);
            TextView count;

            inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


             View itemView = inflater.inflate(R.layout.drawr_roow, parent, false);
  

            ImageView mImageView = (ImageView) itemView.findViewById(R.id.img_cat);
            if (position == 0) {
                mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_drawer_tour));
            } else if (position == 1) {
                mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_drawer_profile));

            } else if (position == 2) {
                mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_drawer_logout));

            }


 

            title = (TextView) itemView.findViewById(R.id.drawer_itemName);
            title.setText(dItem.getNmae());
            return itemView;

        }


    }

 


     } 

Scan qr code iwth zxing library in android

My gradle file is

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "android.srptl.zxingqrscan"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'//Add dependency
    compile 'com.google.zxing:core:3.2.1'

}

 
 
 content_main.xml 
 
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.pethoalpar.zxingexample.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>







MainActivity.java

public class MainActivity extends AppCompatActivity {
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        button = (Button) this.findViewById(R.id.button);
        final Activity activity = this;
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentIntegrator integrator = new IntentIntegrator(activity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setPrompt("Scan");
                integrator.setCameraId(0);
                integrator.setBeepEnabled(false);
                integrator.setBarcodeImageEnabled(false);
                integrator.initiateScan();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Saturday, 23 January 2016

Display web service data in listview and gridview in android.


For integrating JSON service example you need below jar for that
1. apache-mime4j-0.6.jar
2. gson-2.1.jar
3. httpmime-4.0.1,jar
4. json_simple-1.1.jar

layout_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
        android:id="@+id/rel_tops"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/img_list_grid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/margin_10dp"
            android:layout_alignParentRight="true"
            android:src="@drawable/grid_menu"/>

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/img_list_grid"
            android:cacheColorHint="@android:color/transparent"
            android:divider="@android:color/transparent"
            android:visibility="visible"
            />

        <GridView
            android:id="@+id/grid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:numColumns="2"
            android:layout_below="@+id/img_list_grid"
            android:visibility="gone"

            android:cacheColorHint="@android:color/transparent"
            android:divider="@android:color/transparent"
            />
    </RelativeLayout>



</RelativeLayout>

MainActivity.java
import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import parser.GetPerson; public class MainActivity extends AppCompatActivity {     ImageView mImageViewListGrid;     ListView mListView;     GridView mGridView;     CusTomListAdapter mCusTomListAdapter;     CusTomGridAdapter mCusTomGridAdapter;     PostParseGet mPostParseGet;     GetPerson mGetPerson;     ProgressDialog mProgressDialog;     AllMethods mAllMethods;     ArrayList<GetPerson.PersonDataList>mArrayListPersonDataLists;     boolean isGrid=false;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.layout_main);         /*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);*/         mImageViewListGrid=(ImageView)findViewById(R.id.img_list_grid);         mListView=(ListView)findViewById(R.id.list);         mGridView=(GridView)findViewById(R.id.grid);         mPostParseGet=new PostParseGet(MainActivity.this);         mGetPerson=new GetPerson();         mArrayListPersonDataLists=new ArrayList<>();         mAllMethods=new AllMethods(MainActivity.this);         if (mAllMethods.check_Internet()==true)         {             new getPersonAsyns().execute();         }         else         {             mAllMethods.ShowDialog(MainActivity.this,"",getString(R.string.net_not_available),"OK");         }         mImageViewListGrid.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 if (isGrid==false)                 {                     mImageViewListGrid.setImageDrawable(getResources().getDrawable(R.drawable.list_menu));                      isGrid=true;                     mListView.setVisibility(View.GONE);                     mGridView.setVisibility(View.VISIBLE);                 }                 else if (isGrid==true)                 {                     mImageViewListGrid.setImageDrawable(getResources().getDrawable(R.drawable.grid_menu));                     isGrid=false;                     mListView.setVisibility(View.VISIBLE);                     mGridView.setVisibility(View.GONE);                 }             }         });     }     public class getPersonAsyns extends AsyncTask<Void,Void,Void>     {         @Override         protected void onPreExecute() {             super.onPreExecute();             mProgressDialog=ProgressDialog.show(MainActivity.this,"","Loading..");         }         @Override         protected Void doInBackground(Void... voids) {             mGetPerson=(GetPerson)mPostParseGet.getPersonDetail(mGetPerson);             return null;         }         @Override         protected void onPostExecute(Void aVoid) {             super.onPostExecute(aVoid);             if (mProgressDialog!=null)             {                 mProgressDialog.dismiss();             }             if (mPostParseGet.isNetError)             {                 mAllMethods.ShowDialog(MainActivity.this,"",getString(R.string.net_not_available),"OK");             }             else if(mPostParseGet.isOtherError)             {                 mAllMethods.ShowDialog(MainActivity.this,"",getString(R.string.slow_internet),"Ok");             }             else             {                 mArrayListPersonDataLists=getPersonData();                 mCusTomListAdapter=new CusTomListAdapter(MainActivity.this,mArrayListPersonDataLists);                 mListView.setAdapter(mCusTomListAdapter);                 mCusTomGridAdapter=new CusTomGridAdapter(MainActivity.this,mArrayListPersonDataLists);                 mGridView.setAdapter(mCusTomGridAdapter);             }         }     }     public ArrayList<GetPerson.PersonDataList> getPersonData() {         ArrayList< GetPerson.PersonDataList> mArrayListParserLog = new ArrayList<  GetPerson.PersonDataList   >();         String  mString="";         for (int i = 0; i < mGetPerson.getContacts().size(); i++) {             GetPerson.PersonDataList  mParserLog = new   GetPerson.PersonDataList();             mParserLog.setName(mGetPerson.getContacts().get(i).getName());             mParserLog.setEmail(mGetPerson.getContacts().get(i).getEmail());             mParserLog.setGender(mGetPerson.getContacts().get(i).getGender());             GetPerson.PhoneDetail mPhoneDetail=new GetPerson.PhoneDetail();             mPhoneDetail.setMobile(mGetPerson.getContacts().get(i).getPhone().getMobile());             mParserLog.setPhone(mPhoneDetail);             mArrayListParserLog.add(mParserLog);         }         return mArrayListParserLog;     }     public class CusTomListAdapter extends BaseAdapter     {         Activity mActivity;         ArrayList<GetPerson.PersonDataList> list;         public CusTomListAdapter(MainActivity mainActivity, ArrayList<GetPerson.PersonDataList> mArrayListPersonDataLists) {             list=mArrayListPersonDataLists;             mActivity=mainActivity;         }         @Override         public int getCount() {             return list.size();         }         @Override         public Object getItem(int i) {             return i;         }         @Override         public long getItemId(int i) {             return i;         }         @Override         public View getView(int i, View convertView, ViewGroup viewGroup) {             LayoutInflater inflator = mActivity.getLayoutInflater();             convertView = inflator.inflate(R.layout.row_list_layout, null);             TextView mTextViewName=(TextView)convertView.findViewById(R.id.row_txt_name);             TextView mTextViewEmail=(TextView)convertView.findViewById(R.id.row_txt_email);             TextView mTextViewGender=(TextView)convertView.findViewById(R.id.row_txt_gender);             TextView mTextViewPh=(TextView)convertView.findViewById(R.id.row_txt_ph);             mTextViewEmail.setText(list.get(i).getEmail());             mTextViewGender.setText("Gender: "+list.get(i).getGender());             mTextViewName.setText(list.get(i).getName());             mTextViewPh.setText(list.get(i).getPhone().getMobile());             return convertView;         }     }     public class CusTomGridAdapter extends BaseAdapter     {         Activity mActivity;         ArrayList<GetPerson.PersonDataList> list;         public CusTomGridAdapter(MainActivity mainActivity, ArrayList<GetPerson.PersonDataList> mArrayListPersonDataLists) {             list=mArrayListPersonDataLists;             mActivity=mainActivity;         }         @Override         public int getCount() {             return list.size();         }         @Override         public Object getItem(int i) {             return i;         }         @Override         public long getItemId(int i) {             return i;         }         @Override         public View getView(int i, View convertView, ViewGroup viewGroup) {             LayoutInflater inflator = mActivity.getLayoutInflater();             convertView = inflator.inflate(R.layout.row_list_layout, null);             TextView mTextViewName=(TextView)convertView.findViewById(R.id.row_txt_name);             TextView mTextViewEmail=(TextView)convertView.findViewById(R.id.row_txt_email);             TextView mTextViewGender=(TextView)convertView.findViewById(R.id.row_txt_gender);             TextView mTextViewPh=(TextView)convertView.findViewById(R.id.row_txt_ph);             mTextViewEmail.setText(list.get(i).getEmail());             mTextViewGender.setText("Gender: "+list.get(i).getGender());             mTextViewName.setText(list.get(i).getName());             mTextViewPh.setText(list.get(i).getPhone().getMobile());             return convertView;         }     }     @Override     public boolean onCreateOptionsMenu(Menu menu) {         // Inflate the menu; this adds items to the action bar if it is present.         getMenuInflater().inflate(R.menu.menu_main, menu);         return true;     }     @Override     public boolean onOptionsItemSelected(MenuItem item) {         // Handle action bar item clicks here. The action bar will         // automatically handle clicks on the Home/Up button, so long         // as you specify a parent activity in AndroidManifest.xml.         int id = item.getItemId();         //noinspection SimplifiableIfStatement         if (id == R.id.action_settings) {             return true;         }         return super.onOptionsItemSelected(item);     } }
GetPerson.java
package parser; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; import java.util.List; public class GetPerson implements Parcelable { public List<PersonDataList> contacts; public List<PersonDataList> getContacts() { return contacts; } public void setContacts(List<PersonDataList> contacts) { this.contacts = contacts; } public GetPerson(){ contacts=new ArrayList<PersonDataList>(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { } public static Creator<GetPerson> CREATOR = new Creator<GetPerson>() { @Override public GetPerson[] newArray(int size) { return new GetPerson[size]; } @Override public GetPerson createFromParcel(Parcel source) { return new GetPerson(source); } }; public GetPerson(Parcel in) { contacts=new ArrayList<PersonDataList>(); in.readTypedList(contacts, PersonDataList.CREATOR); } public static class PersonDataList implements Parcelable { String name=""; String email=""; String gender=""; public PhoneDetail phone; public PhoneDetail getPhone() { return phone; } public void setPhone(PhoneDetail phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int i) { dest.writeString(name); dest.writeString(email); dest.writeString(gender); dest.writeParcelable(phone, i); } public static Creator<PersonDataList> CREATOR = new Creator<PersonDataList>() { @Override public PersonDataList[] newArray(int size) { return new PersonDataList[size]; } @Override public PersonDataList createFromParcel(Parcel source) { return new PersonDataList(source); } }; public PersonDataList(Parcel in) { name = in.readString(); email = in.readString(); gender = in.readString(); phone = (PhoneDetail) in.readParcelable(PhoneDetail.class.getClassLoader()); } public PersonDataList(){} } public static class PhoneDetail implements Parcelable { String mobile=""; public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int i) { dest.writeString(mobile); } public static Creator<PhoneDetail> CREATOR = new Creator<PhoneDetail>() { @Override public PhoneDetail[] newArray(int size) { return new PhoneDetail[size]; } @Override public PhoneDetail createFromParcel(Parcel source) { return new PhoneDetail(source); } }; public PhoneDetail (){} public PhoneDetail(Parcel in) { mobile = in.readString(); } } }
import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.FragmentActivity; import com.google.gson.Gson; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import parser.GetPerson; public class PostParseGet { public Activity mContext; public boolean isNetError = false; public boolean isOtherError = false; public boolean isDeviceToken = false; List<NameValuePair> nameValuePairs; Object mFillObject; public static ArrayList<String> mflist; ConnectivityManager mConnectivityManager; NetworkInfo mNetworkInfo; Gson mGson; public PostParseGet(Activity context) { mContext = context; mGson = new Gson(); mflist = new ArrayList<String>(); } public PostParseGet(FragmentActivity context) { mContext = context; mGson = new Gson(); mflist = new ArrayList<String>(); } public Object getmFillObject() { return mFillObject; } public void setmFillObject(Object mFillObject) { this.mFillObject = mFillObject; } public boolean isDeviceToken() { return isDeviceToken; } public void setDeviceToken(boolean isDeviceToken) { this.isDeviceToken = isDeviceToken; } /** * Function checks internet if avail, Post data to particular Url and filled * json object relating to the response. * * @param string * @param nameValuePairs * @param object * @param context * @return object * @throws CustomException */ public Object postHttpURL(String url, List<NameValuePair> nameValuePairs, Object mObject) { HttpPost httppost; HttpParams httpParameters; int timeoutConnection = 60000; HttpClient httpclient = null; HttpResponse response = null; String data = ""; isOtherError = false; System.out.println("Url " + url); mFillObject = null; if (check_Internet()) { try { mFillObject = mObject.getClass().newInstance(); /*HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; DefaultHttpClient client = new DefaultHttpClient(); SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry); DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);*/ // HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); httppost = new HttpPost(url); httpParameters = new BasicHttpParams(); // HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); httpclient = new DefaultHttpClient(httpParameters); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); System.out.println("nameValuePairs " + nameValuePairs.size()); if (nameValuePairs != null) { for (int index = 0; index < nameValuePairs.size(); index++) { String paramName = nameValuePairs.get(index).getName(); String paramValue = nameValuePairs.get(index).getValue(); System.out.println("paramName " + paramName); System.out.println("paramValue " + paramValue); if (paramName.equalsIgnoreCase("docsimage") || paramName.equalsIgnoreCase("faceimage")) { if (paramValue.length() > 0) { /*if (paramValue.equalsIgnoreCase("Female-Avatar.png")||paramValue.equalsIgnoreCase("avatar-man.jpg") ) { entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } else {*/ entity.addPart(paramName, new FileBody(new File(paramValue))); //} } } else { // mflist.clear(); entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } } httppost.setEntity(entity); } response = httpclient.execute(httppost); System.out.println("httppost " + httppost.toString()); data = EntityUtils.toString(response.getEntity()); System.out.println("Final Data " + data); if (data.equalsIgnoreCase("{\"is_device_deleted\":true}")) setDeviceToken(true); mFillObject = mGson.fromJson(data, mFillObject.getClass()); } catch (Exception e) { isOtherError = true; e.printStackTrace(); } } return mFillObject; } /** * Function * Takes and keeps a reference of the passed context in order to Check whether Internet is available or not. * * @param context * @return The return will be true if the internet is available and false if not. */ public boolean check_Internet() { mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting()) { isNetError = false; return true; } else { isNetError = true; return false; } } public Object getPersonDetail(GetPerson mGetFlag) { nameValuePairs = new ArrayList<NameValuePair>(); return postHttpURL("http://api.androidhive.info/contacts/", nameValuePairs, mGetFlag); } }

Manage layout in multiple device in android

First of all create res folder structure as below image.





In above image you can see like for image make drawable folder like below

for mobile

drawable-hdpi (normal size mobile like 480x800, 480x854 etc.. )
drawable-xhdpi (high resolution scree like 1080x1920, 768x1280 etc..)
drawable-xxhdpi (very high resolution 1440x2560)

for 7 inch tablet
drawable-large


for 10 inch tablet
drawable-xlarge


For making layout folder

for Mobile
layout

for 7 inch
layout-sw600dp-port (portrait)
layout-sw600dp-land (landscape)

for 10 inch
layout-sw720dp-port (portrait)
layout-sw720dp-land (landscape)

For making values folder

for Mobile
values-hdpi
values-xhdpi

for Tablet 7 inch
values-large

for Tablet 10 inch
values-xlarge


And inside values/dimens.xml folder set different value for all folder so you can manage in all verison of device as well as tablet