Wednesday 20 June 2018

How to Generate Dynamic Tab in Android

- First create MainActivity.class and activity_main.xml

- Add following code in MainActivity.java class

  public class MainActivity extends FragmentActivity {

    ViewPager viewPager;
    TabLayout tabLayout;
    TabsPagerAdapter tabsPagerAdapter;


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

    //Reference of Components
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        viewPager = (ViewPager) findViewById(R.id.pager);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    setTabData();
     }
  }

- Add following code in activity_main.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:layout_height="match_parent"
    android:orientation="vertical">

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

             <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="0.08"
                android:background="@color/btn_login"
                android:elevation="6dp"
                android:minHeight="?attr/actionBarSize"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:tabIndicatorColor="@android:color/white"
                app:tabMode="fixed" />

             <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="0.92" />
     </LinearLayout>
</LinearLayout>

- To Add this method in your Class and call this method in your class

    public void setTabData() {
        String[] str_tab_name = {"Test", "Test 1","Test 2"};
        //Set Tab Data
        ArrayList<Fragment> list = new ArrayList<Fragment>();
        tabLayout.removeAllTabs();
        for (int i = 0; i < str_tab_name.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setText("" + str_tab_name[i]));
            TestFragment testFragment = new TestFragment();
            list.add(testFragment);
            Bundle bundle = new Bundle();
            bundle.putInt("tab_position", i);
            testFragment.setArguments(bundle);
        
        }

        //viewPager.setOffscreenPageLimit(1);
        tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(tabsPagerAdapter);
        viewPager.setOffscreenPageLimit(1);
        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {

            }
        });

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
     
    }

- To Create Fragment Class For Example "TestFragment" and create xml file according it is fragment_test

   public class TestFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_test, container, false);
    }
  }


- Add Following code in fragment_test.xml file

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

  </LinearLayout>

How to Add CircleImageView in Android

- First make Class CircleImageView and Add following code in that

 import android.content.Context;
  import android.content.res.TypedArray;
  import android.graphics.Bitmap;
  import android.graphics.BitmapShader;
  import android.graphics.Canvas;
  import android.graphics.Color;
  import android.graphics.ColorFilter;
  import android.graphics.Matrix;
  import android.graphics.Paint;
  import android.graphics.RectF;
  import android.graphics.Shader;
  import android.graphics.drawable.BitmapDrawable;
  import android.graphics.drawable.ColorDrawable;
  import android.graphics.drawable.Drawable;
  import android.net.Uri;
  import android.support.annotation.ColorInt;
  import android.support.annotation.ColorRes;
  import android.support.annotation.DrawableRes;
  import android.util.AttributeSet;
  import android.widget.ImageView;

  public class CircleImageView extends ImageView {

    private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;

    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    private static final int COLORDRAWABLE_DIMENSION = 2;

    private static final int DEFAULT_BORDER_WIDTH = 0;
    private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
    private static final int DEFAULT_FILL_COLOR = Color.TRANSPARENT;
    private static final boolean DEFAULT_BORDER_OVERLAY = false;

    private final RectF mDrawableRect = new RectF();
    private final RectF mBorderRect = new RectF();

    private final Matrix mShaderMatrix = new Matrix();
    private final Paint mBitmapPaint = new Paint();
    private final Paint mBorderPaint = new Paint();
    private final Paint mFillPaint = new Paint();

    private int mBorderColor = DEFAULT_BORDER_COLOR;
    private int mBorderWidth = DEFAULT_BORDER_WIDTH;
    private int mFillColor = DEFAULT_FILL_COLOR;

    private Bitmap mBitmap;
    private BitmapShader mBitmapShader;
    private int mBitmapWidth;
    private int mBitmapHeight;

    private float mDrawableRadius;
    private float mBorderRadius;

    private ColorFilter mColorFilter;

    private boolean mReady;
    private boolean mSetupPending;
    private boolean mBorderOverlay;
    private boolean mDisableCircularTransformation;

    public CircleImageView(Context context) {
        super(context);

        init();
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);

        mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_civ_border_width, DEFAULT_BORDER_WIDTH);
        mBorderColor = a.getColor(R.styleable.CircleImageView_civ_border_color, DEFAULT_BORDER_COLOR);
        mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_civ_border_overlay, DEFAULT_BORDER_OVERLAY);
        mFillColor = a.getColor(R.styleable.CircleImageView_civ_fill_color, DEFAULT_FILL_COLOR);

        a.recycle();

        init();
    }

    private void init() {
        super.setScaleType(SCALE_TYPE);
        mReady = true;

        if (mSetupPending) {
            setup();
            mSetupPending = false;
        }
    }

    @Override
    public ScaleType getScaleType() {
        return SCALE_TYPE;
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (scaleType != SCALE_TYPE) {
            throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
        }
    }

    @Override
    public void setAdjustViewBounds(boolean adjustViewBounds) {
        if (adjustViewBounds) {
            throw new IllegalArgumentException("adjustViewBounds not supported.");
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mDisableCircularTransformation) {
            super.onDraw(canvas);
            return;
        }

        if (mBitmap == null) {
            return;
        }

        if (mFillColor != Color.TRANSPARENT) {
            canvas.drawCircle(mDrawableRect.centerX(), mDrawableRect.centerY(), mDrawableRadius, mFillPaint);
        }
        canvas.drawCircle(mDrawableRect.centerX(), mDrawableRect.centerY(), mDrawableRadius, mBitmapPaint);
        if (mBorderWidth > 0) {
            canvas.drawCircle(mBorderRect.centerX(), mBorderRect.centerY(), mBorderRadius, mBorderPaint);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setup();
    }

    @Override
    public void setPadding(int left, int top, int right, int bottom) {
        super.setPadding(left, top, right, bottom);
        setup();
    }

    @Override
    public void setPaddingRelative(int start, int top, int end, int bottom) {
        super.setPaddingRelative(start, top, end, bottom);
        setup();
    }

    public int getBorderColor() {
        return mBorderColor;
    }

    public void setBorderColor(@ColorInt int borderColor) {
        if (borderColor == mBorderColor) {
            return;
        }

        mBorderColor = borderColor;
        mBorderPaint.setColor(mBorderColor);
        invalidate();
    }

    /**
     * @deprecated Use {@link #setBorderColor(int)} instead
     */
    @Deprecated
    public void setBorderColorResource(@ColorRes int borderColorRes) {
        setBorderColor(getContext().getResources().getColor(borderColorRes));
    }

    /**
     * Return the color drawn behind the circle-shaped drawable.
     *
     * @return The color drawn behind the drawable
     * @deprecated Fill color support is going to be removed in the future
     */
    @Deprecated
    public int getFillColor() {
        return mFillColor;
    }

    /**
     * Set a color to be drawn behind the circle-shaped drawable. Note that
     * this has no effect if the drawable is opaque or no drawable is set.
     *
     * @param fillColor The color to be drawn behind the drawable
     * @deprecated Fill color support is going to be removed in the future
     */
    @Deprecated
    public void setFillColor(@ColorInt int fillColor) {
        if (fillColor == mFillColor) {
            return;
        }

        mFillColor = fillColor;
        mFillPaint.setColor(fillColor);
        invalidate();
    }

    /**
     * Set a color to be drawn behind the circle-shaped drawable. Note that
     * this has no effect if the drawable is opaque or no drawable is set.
     *
     * @param fillColorRes The color resource to be resolved to a color and
     *                     drawn behind the drawable
     * @deprecated Fill color support is going to be removed in the future
     */
    @Deprecated
    public void setFillColorResource(@ColorRes int fillColorRes) {
        setFillColor(getContext().getResources().getColor(fillColorRes));
    }

    public int getBorderWidth() {
        return mBorderWidth;
    }

    public void setBorderWidth(int borderWidth) {
        if (borderWidth == mBorderWidth) {
            return;
        }

        mBorderWidth = borderWidth;
        setup();
    }

    public boolean isBorderOverlay() {
        return mBorderOverlay;
    }

    public void setBorderOverlay(boolean borderOverlay) {
        if (borderOverlay == mBorderOverlay) {
            return;
        }

        mBorderOverlay = borderOverlay;
        setup();
    }

    public boolean isDisableCircularTransformation() {
        return mDisableCircularTransformation;
    }

    public void setDisableCircularTransformation(boolean disableCircularTransformation) {
        if (mDisableCircularTransformation == disableCircularTransformation) {
            return;
        }

        mDisableCircularTransformation = disableCircularTransformation;
        initializeBitmap();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        initializeBitmap();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        initializeBitmap();
    }

    @Override
    public void setImageResource(@DrawableRes int resId) {
        super.setImageResource(resId);
        initializeBitmap();
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        initializeBitmap();
    }

    @Override
    public ColorFilter getColorFilter() {
        return mColorFilter;
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        if (cf == mColorFilter) {
            return;
        }

        mColorFilter = cf;
        applyColorFilter();
        invalidate();
    }

    private void applyColorFilter() {
        if (mBitmapPaint != null) {
            mBitmapPaint.setColorFilter(mColorFilter);
        }
    }

    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;

            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
            }

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void initializeBitmap() {
        if (mDisableCircularTransformation) {
            mBitmap = null;
        } else {
            mBitmap = getBitmapFromDrawable(getDrawable());
        }
        setup();
    }

    private void setup() {
        if (!mReady) {
            mSetupPending = true;
            return;
        }

        if (getWidth() == 0 && getHeight() == 0) {
            return;
        }

        if (mBitmap == null) {
            invalidate();
            return;
        }

        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setShader(mBitmapShader);

        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(mBorderColor);
        mBorderPaint.setStrokeWidth(mBorderWidth);

        mFillPaint.setStyle(Paint.Style.FILL);
        mFillPaint.setAntiAlias(true);
        mFillPaint.setColor(mFillColor);

        mBitmapHeight = mBitmap.getHeight();
        mBitmapWidth = mBitmap.getWidth();

        mBorderRect.set(calculateBounds());
        mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f);

        mDrawableRect.set(mBorderRect);
        if (!mBorderOverlay && mBorderWidth > 0) {
            mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f);
        }
        mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);

        applyColorFilter();
        updateShaderMatrix();
        invalidate();
    }

    private RectF calculateBounds() {
        int availableWidth = getWidth() - getPaddingLeft() - getPaddingRight();
        int availableHeight = getHeight() - getPaddingTop() - getPaddingBottom();

        int sideLength = Math.min(availableWidth, availableHeight);

        float left = getPaddingLeft() + (availableWidth - sideLength) / 2f;
        float top = getPaddingTop() + (availableHeight - sideLength) / 2f;

        return new RectF(left, top, left + sideLength, top + sideLength);
    }

    private void updateShaderMatrix() {
        float scale;
        float dx = 0;
        float dy = 0;

        mShaderMatrix.set(null);

        if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
            scale = mDrawableRect.height() / (float) mBitmapHeight;
            dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
        } else {
            scale = mDrawableRect.width() / (float) mBitmapWidth;
            dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
        }

        mShaderMatrix.setScale(scale, scale);
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);

        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }
  }

- Add following code in attrs.xml file for circleImageview style

     <declare-styleable name="CircleImageView">
        <attr name="civ_border_width" format="dimension" />
        <attr name="civ_border_color" format="color" />
        <attr name="civ_border_overlay" format="boolean" />
        <attr name="civ_fill_color" format="color" />
    </declare-styleable>

- Add following code in your xml file where com.test.constant.CircleImageView is a path of above Java class

     <com.test.constant.CircleImageView
          android:id="@+id/image_profile"
          android:layout_width="fill_parent"
          android:layout_height="60dp" />

- Finally, to initialize CircleImageView same as Imageview in Android and load image using Picasso or any third party library(if image load from server then use third party library otherwise not).









Thursday 17 May 2018

How to Make Splash Screen Android

public class SplashActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        Thread timerThread = new Thread() {
            public void run() {
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    //SharedPreferences sharedpreferences = getSharedPreferences(AppConstant.TAG_MyPref, Context.MODE_PRIVATE);
                    //String Student_Id = sharedpreferences.getString(AppConstant.TAG_Student_Id, null);

                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        };
        timerThread.start();
    }
}

How to Make border of Textview or Button or Layout in Android

- To Make one xml file inside drawable folder name is list_border.xml(drawable/list_border.xml)

 <?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="0dp"></corners>
    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />
    <stroke
        android:width="1dp"
        android:color="@color/register_edit_border" />

    <solid android:color="@android:color/white" />
</shape>

- Apply above xml file in Textview or Button or Layout as a Background

Ex -    <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="0.85"
                android:gravity="center"
                android:text="Test Click Me"
                android:background="@drawable/list_border"
                android:textColor="@android:color/white"
                android:textSize="18dp" />

How to Add Animation when change Activity in Android

- First Make anim Folder in res directory.(/res/anim)

- Make one xml file inside anim folder name is open_next.xml(/res/anim/open_next.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromXDelta="100%"
        android:toXDelta="0"
        android:duration="300" />
</set>

- Make another xml file inside anim folder name is close_next.xml(/res/anim/close_next.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromXDelta="0"
        android:toXDelta="100%p"
        android:duration="600" />
</set>

- Add Following code in Main Java class when change Activity

  Intent intent = new Intent(getApplicationContext(), OptionActivity.class);
  startActivity(intent);
  overridePendingTransition(R.anim.open_next, R.anim.close_next);


How to make Pagination Listview in Android

- First To download 3 class of package and put in your package.
https://drive.google.com/file/d/1ysWRLALl19LkOr7vH4ykAswXCQJPO545/view?usp=sharing

- To add following line in string.xml file

    <string name="xlistview_header_hint_normal">Refresh dropdown</string>
    <string name="xlistview_header_hint_ready">Refresh data release</string>
    <string name="xlistview_header_hint_loading">Loading ...</string>
    <string name="xlistview_header_last_time">Last updated:</string>
    <string name="xlistview_footer_hint_normal">View more</string>
    <string name="xlistview_footer_hint_ready">Loosen Load more</string>


- To make xml file name is xlistview_header.xml and add following code inside it.

   <?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:gravity="bottom">

    <RelativeLayout
        android:id="@+id/xlistview_header_content"
        android:layout_width="fill_parent"
        android:visibility="gone"
        android:layout_height="60dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical"
            android:id="@+id/xlistview_header_text">

            <TextView
                android:id="@+id/xlistview_header_hint_textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/xlistview_header_hint_normal" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/xlistview_header_last_time"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/xlistview_header_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/xlistview_header_arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-35dp"
            android:src="@drawable/xlistview_arrow" />

        <ProgressBar
            android:id="@+id/xlistview_header_progressbar"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-40dp"
            android:visibility="invisible" />
    </RelativeLayout>
   </LinearLayout>

 - To make xml file name is xlistview_footer.xml and add following code inside it.

   <?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">

    <RelativeLayout
        android:id="@+id/xlistview_footer_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <ProgressBar
            android:id="@+id/xlistview_footer_progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/xlistview_footer_hint_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="gone"
            android:text="@string/xlistview_footer_hint_normal" />
     </RelativeLayout>
    </LinearLayout>

 - To Add following code in main.xml file.

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

        <com.packagename.xlistview.XListView
            android:id="@+id/list_news"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:divider="@null"></com.packagename.xlistview.XListView>
    </LinearLayout>

- Add Following Code in Your Main Java Class.

-  First Declare variable first
   //XListview
    private XListView mListView;
    private Handler mHandler;
    int lastValueSize;
    NewsAdapter adapter;
    int pagenumber = 1;
    List<NewsPostConstant> list_array;
    ProgressDialog pDialog;

 - Add following code in onCreate Method.
     
      //To Initialize Array list
        list_array = new ArrayList<NewsPostConstant>();

       mListView = (XListView) view.findViewById(R.id.list_news);
       mListView.setPullLoadEnable(true);
       mListView.setXListViewListener(this);
       mHandler = new Handler();

       geneItems();

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

                Intent intent = new Intent(getActivity(), DescriptionActivity.class);
                String listSerializedToJson = new Gson().toJson(list_array);
                intent.putExtra("Data_Array", listSerializedToJson);
                intent.putExtra("Position", position);
                startActivity(intent);
            }
        });

- Add Following Method Outside of Oncreate Method.

      private void geneItems() {
        getAllData();    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    pagenumber++;
                    geneItems();
                    adapter.notifyDataSetChanged();
                    onLoad();
                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }
            }
        }, 1000);
    }


    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    pagenumber++;
                    geneItems();
                    adapter.notifyDataSetChanged();
                    onLoad();
                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }

            }
        }, 1000);
    }


    public void getAllData() {
        if (pagenumber == 1) {
            pDialog = new ProgressDialog(getActivity());
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setCancelable(false);
            pDialog.setMessage("Please wait");
            pDialog.show();
        }
        APIInterface apiService =
                ApiClientAnother.getClient().create(APIInterface.class);

        Call<TestConstant> call = apiService.getTestCategory(Category_id, pagenumber);

        call.enqueue(new Callback<TestConstant>() {
            @Override
            public void onResponse(Call<TestConstant> call, Response<TestConstant> response) {
                // Log.d("List size", new Gson().toJson(response.body()));
                String str_success = response.body().getStatus();
                Log.e("Url is",""+response.raw().request().url());
                if (str_success.equals("ok")) {
                    if (pagenumber == 1) {
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                    }
                    //Get Login Response
                    List<NewsPostConstant> list_post = response.body().getPosts();
                    for (int i = 0; i < list_post.size(); i++) {
                        int id = list_post.get(i).getId();
                        String title = list_post.get(i).getTitle();
                        String description = list_post.get(i).getContent();
                        String date = list_post.get(i).getDate();
                     
                        NewsPostConstant newsPostConstant = new NewsPostConstant();
                        newsPostConstant.setId(id);
                        newsPostConstant.setTitle(title);
                        newsPostConstant.setContent(description);
                        newsPostConstant.setDate(date);
                        list_array.add(newsPostConstant);
                    }
                    lastValueSize = mListView.getLastVisiblePosition() - 1;

                    adapter = new NewsAdapter(getActivity(), list_array);
                    mListView.setAdapter(adapter);
                    if (pagenumber != 1) {
                        mListView.setSelection(lastValueSize);
                    }
                } else {
                    if (pagenumber == 1) {
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                    }
                    //Toast.makeText(getApplicationContext(), "No Data Found", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<TestConstant> call, Throwable t) {
                if (pagenumber == 1) {
                    if (pDialog.isShowing()) {
                        pDialog.dismiss();
                    }
                }
                Toast.makeText(getActivity(), "Data Not Available", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public class NewsAdapter extends BaseAdapter {

        private List<NewsPostConstant> array_list;
        private Context context;

        public NewsAdapter(Context context, List<NewsPostConstant> array_list) {
            this.context = context;
            this.array_list = array_list;

        }

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

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int Position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convert, ViewGroup arg2) {
            // TODO Auto-generated method stub
            View gv;
            if (convert == null) {
                LayoutInflater lf = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                gv = new View(context);
                gv = lf.inflate(R.layout.text_category_list, null);
            } else {
                gv = (View) convert;
            }

            TextView text_category_name = (TextView) gv.findViewById(R.id.text_title);
            TextView text_date = (TextView) gv.findViewById(R.id.text_date);

            String title = array_list.get(position).getTitle();
            text_category_name.setText("" + Html.fromHtml(title));

            String date = array_list.get(position).getDate();
            StringTokenizer tokens = new StringTokenizer(date, " ");
            String first = tokens.nextToken();
            String second = tokens.nextToken();
            text_date.setText("" + Html.fromHtml(first));

            return gv;
        }
    }



Sunday 13 May 2018

How to Make and Use Sqlite Database in Android

//First  To Make DBHandler Class in Your Project

public class DBHandler extends SQLiteOpenHelper {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Test.db";
    //Table Name
    private static final String TABLE_NAME_CATEGORY = "maincategory";
    private static final String TABLE_NAME_SUB_CATEGORY = "subcategory";

    //Variable
    private static final String KEY_ID = "id";
    private static final String KEY_CLIENT_ID = "client_id";
    private static final String KEY_CATEGORY_ID = "category_id";
    private static final String KEY_CATEGORY_NAME = "category_name";
    private static final String KEY_CATEGORY_IMAGE = "category_image";
    private static final String KEY_SUB_CATEGORY_ID = "sub_category_id";
    private static final String KEY_SUB_CATEGORY_NAME = "sub_category_name";
    private static final String KEY_SUB_CATEGORY_DETAILS = "sub_category_detail";
    private static final String KEY_SUB_CATEGORY_TYPE = "sub_category_type";
    private static final String KEY_SUB_CATEGORY_IMAGE = "sub_category_image";
    private static final String KEY_SUB_CATEGORY_MENUTEST = "sub_category_menutest";
    private static final String KEY_SUB_CATEGORY_PRICE = "sub_category_price";
    private static final String KEY_SUB_CATEGORY_TASTE = "sub_category_menu_taste";
    private static final String KEY_SUB_CATEGORY_FOOD_TYPE = "sub_category_food_type";
    private static final String KEY_SUB_CATEGORY_ADDON = "sub_category_addon";
    private static final String KEY_TABLE_CATEGORY_ID = "table_category_id";
    private static final String KEY_TABLE_SUB_CATEGORY_ID = "table_subcategory_id";
    private static final String KEY_TABLE_NO_PERSON = "table_no_person";
    private static final String KEY_TABLE_NAME = "table_name";
    private static final String KEY_ITEM_PER_DAY = "item_day";
    private static final String KEY_ORDER_BY = "order_by";
    private static final String KEY_ITEM_NAME = "item_name";
    private static final String KEY_ITEM_TYPE = "item_type";
    private static final String KEY_ITEM_TASTE = "item_taste";
    private static final String KEY_ITEM_QTY = "item_qty";
    private static final String KEY_ITEM_DIET = "item_diet";
    private static final String KEY_ITEM_PRICE = "item_price";
    private static final String KEY_TOTAL_PRICE = "total_price";
    private static final String KEY_ITEM_ADDITIONAL_NOTE = "item_note";
    private static final String KEY_ORDER_STATUS = "order_status";
 
    String QUERY;

    String CREATE_TABLE_CATEGORY = "CREATE TABLE " + TABLE_NAME_CATEGORY + " (" + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_CATEGORY_ID + " VARCHAR," + KEY_CATEGORY_NAME + " VARCHAR," + KEY_CATEGORY_IMAGE + " BOLB)";

    String CREATE_TABLE_SUB_CATEGORY = "CREATE TABLE " + TABLE_NAME_SUB_CATEGORY + " (" + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_CATEGORY_ID + " VARCHAR," + KEY_SUB_CATEGORY_ID + " VARCHAR," + KEY_SUB_CATEGORY_NAME + " VARCHAR," +
            KEY_SUB_CATEGORY_TYPE + " VARCHAR," + KEY_SUB_CATEGORY_IMAGE + " BOLB," + KEY_SUB_CATEGORY_MENUTEST + " VARCHAR,"
            + KEY_SUB_CATEGORY_PRICE + " VARCHAR," + KEY_SUB_CATEGORY_DETAILS + " VARCHAR," + KEY_SUB_CATEGORY_TASTE + " VARCHAR,"
            + KEY_SUB_CATEGORY_FOOD_TYPE + " VARCHAR," + KEY_SUB_CATEGORY_ADDON + " VARCHAR)";

    String DROP_TABLE_CATEGORY = "DROP TABLE IF EXISTS " + CREATE_TABLE_CATEGORY;
    String DROP_TABLE_SUB_CATEGORY = "DROP TABLE IF EXISTS " + CREATE_TABLE_SUB_CATEGORY;

    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CATEGORY);
        db.execSQL(CREATE_TABLE_SUB_CATEGORY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE_CATEGORY);
        db.execSQL(DROP_TABLE_SUB_CATEGORY);
        onCreate(db);
    }

    //To Add Category
    public void addCategory(CategoryConstant category) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_CATEGORY_ID, category.getId());
            values.put(KEY_CATEGORY_NAME, category.getName());
            values.put(KEY_CATEGORY_IMAGE, category.getCatimage());
            db.insert(TABLE_NAME_CATEGORY, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    public void removeCategory() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from " + TABLE_NAME_CATEGORY);
    }

    public ArrayList<CategoryConstant> getAllCategory() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<CategoryConstant> categoryList = null;
        try {
            categoryList = new ArrayList<CategoryConstant>();
            String QUERY = "SELECT * FROM " + TABLE_NAME_CATEGORY;
            Cursor cursor = db.rawQuery(QUERY, null);
            if (!cursor.isLast()) {
                while (cursor.moveToNext()) {
                    CategoryConstant category = new CategoryConstant();
                    category.setID(cursor.getInt(0));
                    category.setId(cursor.getString(1));
                    category.setName(cursor.getString(2));
                    category.setCatimage(cursor.getString(3));
                    categoryList.add(category);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return categoryList;
    }


    //To Add Sub Category
    public void addSubCategory(SubCategoryConstant category) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_CATEGORY_ID, category.getCategoryId());
            values.put(KEY_SUB_CATEGORY_ID, category.getId());
            values.put(KEY_SUB_CATEGORY_NAME, category.getName());
            values.put(KEY_SUB_CATEGORY_TYPE, category.getVeg());
            values.put(KEY_SUB_CATEGORY_IMAGE, category.getMenuimage());
            values.put(KEY_SUB_CATEGORY_MENUTEST, category.getMenutest());
            values.put(KEY_SUB_CATEGORY_PRICE, category.getPrice());
            values.put(KEY_SUB_CATEGORY_DETAILS, category.getDetail());
            values.put(KEY_SUB_CATEGORY_TASTE, category.getMenutaste());
            values.put(KEY_SUB_CATEGORY_FOOD_TYPE, category.getFoodtype());
            values.put(KEY_SUB_CATEGORY_ADDON, category.getAddon());
            db.insert(TABLE_NAME_SUB_CATEGORY, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    public void removeSubCategory() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from " + TABLE_NAME_SUB_CATEGORY);
    }

    public ArrayList<SubCategoryConstant> getAllSubCategory(String categoryid, String type) {
        String QUERY;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<SubCategoryConstant> categoryList = null;
        try {
            categoryList = new ArrayList<SubCategoryConstant>();
            if (type.equals("0")) {
                QUERY = "SELECT * FROM " + TABLE_NAME_SUB_CATEGORY + " WHERE " + KEY_CATEGORY_ID
                        + " = '" + categoryid + "'";
            } else {
                QUERY = "SELECT * FROM " + TABLE_NAME_SUB_CATEGORY + " WHERE " + KEY_CATEGORY_ID
                        + " = '" + categoryid + "' AND " + KEY_SUB_CATEGORY_TYPE + " = '" + type + "'";
            }
            Cursor cursor = db.rawQuery(QUERY, null);
            if (!cursor.isLast()) {
                while (cursor.moveToNext()) {
                    SubCategoryConstant category = new SubCategoryConstant();
                    category.setID(cursor.getInt(0));
                    category.setCategoryId(cursor.getString(1));
                    category.setId(cursor.getString(2));
                    category.setName(cursor.getString(3));
                    category.setVeg(cursor.getString(4));
                    category.setMenuimage(cursor.getString(5));
                    category.setMenutest(cursor.getString(6));
                    category.setPrice(cursor.getString(7));
                    category.setDetail(cursor.getString(8));
                    category.setMenutaste(cursor.getString(9));
                    category.setFoodtype(cursor.getString(10));
                    category.setAddon(cursor.getString(11));
                    categoryList.add(category);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return categoryList;
    }

    public ArrayList<SubCategoryConstant> getSubCategoryPrice(String categoryid, String subcategoryid) {
        String QUERY;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<SubCategoryConstant> categoryList = null;
        try {
            categoryList = new ArrayList<SubCategoryConstant>();

            QUERY = "SELECT * FROM " + TABLE_NAME_SUB_CATEGORY + " WHERE " + KEY_CATEGORY_ID
                    + " = '" + categoryid + "' AND " + KEY_SUB_CATEGORY_ID + " = '" + subcategoryid + "'";
            Log.e("Query", QUERY);
            Cursor cursor = db.rawQuery(QUERY, null);
            if (!cursor.isLast()) {
                while (cursor.moveToNext()) {
                    SubCategoryConstant category = new SubCategoryConstant();
                    category.setID(cursor.getInt(0));
                    category.setCategoryId(cursor.getString(1));
                    category.setId(cursor.getString(2));
                    category.setName(cursor.getString(3));
                    category.setVeg(cursor.getString(4));
                    category.setMenuimage(cursor.getString(5));
                    category.setMenutest(cursor.getString(6));
                    category.setPrice(cursor.getString(7));
                    category.setDetail(cursor.getString(8));
                    category.setMenutaste(cursor.getString(9));
                    category.setFoodtype(cursor.getString(10));
                    category.setAddon(cursor.getString(11));
                    categoryList.add(category);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return categoryList;
    }

    public void removeCartAllItem(String user_id) {
        //Open the database
        SQLiteDatabase database = this.getWritableDatabase();

        //Execute sql query to remove from database
        String sql = "DELETE FROM " + TABLE_NAME_ITEM_VALUE + " WHERE " + KEY_CLIENT_ID + " = '" + user_id + "' AND "
                + KEY_ORDER_STATUS + " = '" + "N" + "'";
        // Log.d("QUesry is",sql);
        //NOTE: When removing by String in SQL, value must be enclosed with ''
        database.execSQL(sql);

        //Close the database
        database.close();
    }

    public void updateItemValue(String user_id, String taste, String qty, String base_price, String diet, String note, String categoryId,
                                String tbl_cat_id, String tbl_sub_cate_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_ITEM_TASTE, taste);
            values.put(KEY_ITEM_QTY, qty);
            values.put(KEY_ITEM_PRICE, base_price);
            values.put(KEY_ITEM_QTY, qty);
            values.put(KEY_ITEM_DIET, diet);
            values.put(KEY_ITEM_ADDITIONAL_NOTE, note);
            db.update(TABLE_NAME_ITEM_VALUE, values, KEY_CLIENT_ID + "='" + user_id + "' AND "
                    + KEY_SUB_CATEGORY_ID + "='" + categoryId + "' AND " + KEY_TABLE_CATEGORY_ID + " = '" + tbl_cat_id
                    + "' AND " + KEY_TABLE_SUB_CATEGORY_ID + " = '" + tbl_sub_cate_id + "'", null);
        } catch (Exception e) {
            Log.e("problem", e + "");
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }
}