Sunday, 17 April 2016

JSON Parsing in android

  

This tutorial used to featch the title and his image from server. And I also include pagination in this post To make two java class ServiceHandler.java
and ImageFragment.java

ImageFragment.java 

public class ImageFragment extends Fragment implements AdapterView.OnItemClickListener, XListView.IXListViewListener {

    String url;
    final int type=1,category_id=4;
    ProgressDialog pd;
    ArrayList<HashMap<String, String>> arr_image;
    ImageAdaper imageAdaper;
    ListView list_image;
    String imageId;
    int pagenumber=1;

    private XListView mListView;
    private ArrayAdapter<String> mAdapter;
    private ArrayList<String> items = new ArrayList<String>();
    private ArrayList<String> iamge_array = new ArrayList<String>();
    private ArrayList<String> image_id = new ArrayList<String>();
    private Handler mHandler;
    private int start = 0;
    private static int refreshCnt = 0;
    int lastValueSize;


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

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

        geneItems();


        MainActivity.image_refrace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /*SharedPreferences.Editor editor = getActivity().getSharedPreferences("MyPref", getActivity().MODE_PRIVATE).edit();
                editor.putString("listsize", "1");
                editor.commit();*/


                items.clear();
                iamge_array.clear();
                mListView.setSelection(0);
                // news_id.clear();

                int pagenumber = 1;
                // Toast.makeText(getApplicationContext(),"News",Toast.LENGTH_SHORT).show();
                if (isOnline()) {
                    url= Appconstant.TAG_BaseUrl + Appconstant.TAG_Method_GetDynamicPost + Appconstant.TAG_Method_GetDynamicPost_CategoryId
                            + category_id + Appconstant.TAG_Method_GetDynamicPost_Type
                            + type + Appconstant.TAG_Method_GetDynamicPost_PageNumber + pagenumber;

                    new listAs().execute(url);
                } else {
                    CheckInternet();
                }
            }
        });


        return view;
    }

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

        //imageId=arr_image.get(position).get(Appconstant.TAG_GetDynamicPost_Image_ID);
        String imageId=image_id.get(position-1);
        Intent intent=new Intent(getActivity(),DetailImage.class);
        intent.putExtra("Image ID",imageId);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_next);
    }

    private void geneItems(){


        if (isOnline()) {
            url= Appconstant.TAG_BaseUrl + Appconstant.TAG_Method_GetDynamicPost + Appconstant.TAG_Method_GetDynamicPost_CategoryId
                    + category_id + Appconstant.TAG_Method_GetDynamicPost_Type
                    + type + Appconstant.TAG_Method_GetDynamicPost_PageNumber + pagenumber;

            new listAs().execute(url);
        } else {
            CheckInternet();
        }
        pagenumber++;
    }

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

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

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


    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //geneItems();
                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }

                    geneItems();
                    imageAdaper.notifyDataSetChanged();
                    onLoad();

                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }

            }
        }, 2000);
    }



    class listAs extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub

                pd = new ProgressDialog(getActivity());
                pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                pd.setCancelable(false);
                pd.setMessage("Please wait");
                pd.show();


            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(params[0], ServiceHandler.GET);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObject=new JSONObject(jsonStr);
                    String result=jsonObject.getString("result");
                    if(result.equals("1")) {

                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int j = 0; j < jsonArray.length(); j++) {

                            JSONObject obj = jsonArray.getJSONObject(j);
                            String ImageId = obj.getString(Appconstant.TAG_GetDynamicPost_Image_ID);
                            String PostTitle=obj.getString(Appconstant.TAG_GetDynamicPost_Image_Post_Title);
                            String PostImage=obj.getString(Appconstant.TAG_GetDynamicPost_Image_Title_Image);

                            items.add(PostTitle);
                            iamge_array.add(PostImage);
                            image_id.add(ImageId);
                           /* HashMap<String, String> in = new HashMap<String, String>();
                            in.put(Appconstant.TAG_GetDynamicPost_Image_ID, ImageId);
                            in.put(Appconstant.TAG_GetDynamicPost_Image_Post_Title,PostTitle);
                            in.put(Appconstant.TAG_GetDynamicPost_Image_Title_Image,PostImage);

                            arr_image.add(in);*/
                        }
                    } else {
                        Toast.makeText(getActivity(),"Image List Not Found",Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (pd.isShowing()) {
                pd.dismiss();
            }


          /*  imageAdaper = new ImageAdaper(getActivity(),arr_image);
            list_image.setAdapter(imageAdaper);*/
            lastValueSize = mListView.getLastVisiblePosition()-1;

            imageAdaper = new ImageAdaper(getActivity(), items, iamge_array);
            mListView.setAdapter(imageAdaper);
            mListView.setSelection(lastValueSize);

        }
    }

    public class ImageAdaper extends BaseAdapter {

        private Context context;
        //  ArrayList<HashMap<String, String>> array_list;
        ArrayList<String> array_list;
        ArrayList<String> array_list_image;

        public ImageAdaper(Context c,
                           ArrayList<String> array_list,ArrayList<String> array_list_image) {
            // TODO Auto-generated constructor stub
            context = c;
            this.array_list = array_list;
            this.array_list_image=array_list_image;
        }


        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            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_fragment_image, null);
            } else {
                gv = (View) convert;
            }



         //   Toast.makeText(context,"size is "+lastValueSize,Toast.LENGTH_SHORT).show();

            //Reference of variable
            final TextView text_fragment_image= (TextView) gv.findViewById(R.id.fragment_text);
            final ImageView image_fragment_image=(ImageView) gv.findViewById(R.id.fragment_image);

            text_fragment_image.setText(Html.fromHtml(array_list.get(position)));
            String url=array_list_image.get(position);
           // imageId=array_list.get(position).get(Appconstant.TAG_GetDynamicPost_Image_ID);

            if(url != null && !url.isEmpty()){
                Picasso.with(context).load("" +url).placeholder(R.drawable.fragment_image_back).into(image_fragment_image);
            }
            else{
                image_fragment_image.setImageResource(R.drawable.fragment_image_back);
            }

           // Toast.makeText(context,"Size is="+(array_list.size()-1),Toast.LENGTH_SHORT).show();

            return gv;
        }
    }

    private boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

        if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
            Toast.makeText(getActivity(), "No Internet connection!",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    public void CheckInternet() {
        try {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle("Network Connection");
            alertDialog
                    .setMessage("Internet is not available, Please check your internet connectivity and try again");
            alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
            alertDialog.setPositiveButton("Setting",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            startActivity(new Intent(
                                    android.provider.Settings.ACTION_SETTINGS));
                        }
                    });

            alertDialog.setNegativeButton("OK",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            getActivity().finish();
                        }
                    });
            alertDialog.create();
            alertDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

To import following libraries 

compile 'org.apache.httpcomponents:httpcore:4.4.1'compile 'org.apache.httpcomponents:httpclient:4.5'compile 'com.squareup.picasso:picasso:2.3.2'


ServiceHandler.java

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
   
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            
            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return response;

    }
}

To make AppConstant Class
public class Appconstant {

    public static String TAG_BaseUrl = "http://www.xx.com/api/xxapi.php?";

    //GetDynamicPost
    public static String TAG_Method_GetDynamicPost = "method=getDynamicPost";
    public static String TAG_Method_GetDynamicPost_CategoryId="&category_id=";
    public static String TAG_Method_GetDynamicPost_Type="&type=";
    public static String TAG_Method_GetDynamicPost_PageNumber="&getpage=";
}


XML file of layout folder

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

    <com.abc.xyz.view.XListView
        android:id="@+id/list_image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000">
    </com.abc.xyz.view.XListView>

</LinearLayout>

 XListview's Constant Classes

XListView.java

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;




public class XListView extends ListView implements OnScrollListener {

    private float mLastY = -1; // save event y
    private Scroller mScroller; // used for scroll back
    private OnScrollListener mScrollListener; // user's scroll listener

    // the interface to trigger refresh and load more.
    private IXListViewListener mListViewListener;

    // -- header view
    private XListViewHeader mHeaderView;
    // header view content, use it to calculate the Header's height. And hide it
    // when disable pull refresh.
    private RelativeLayout mHeaderViewContent;
    private TextView mHeaderTimeView;
    private int mHeaderViewHeight; // header view's height
    private boolean mEnablePullRefresh = true;
    private boolean mPullRefreshing = false; // is refreashing.

    // -- footer view
    private XListViewFooter mFooterView;
    private boolean mEnablePullLoad;
    private boolean mPullLoading;
    private boolean mIsFooterReady = false;
  
    // total list items, used to detect is at the bottom of listview.
    private int mTotalItemCount;

    // for mScroller, scroll back from header or footer.
    private int mScrollBack;
    private final static int SCROLLBACK_HEADER = 0;
    private final static int SCROLLBACK_FOOTER = 1;

    private final static int SCROLL_DURATION = 400; // scroll back duration
    private final static int PULL_LOAD_MORE_DELTA = 50; // when pull up >= 50px
                                                        // at bottom, trigger
                                                        // load more.
    private final static float OFFSET_RADIO = 1.8f; // support iOS like pull
                                                    // feature.

    /**
     * @param context
     */
    public XListView(Context context) {
        super(context);
        initWithContext(context);
    }

    public XListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    public XListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    private void initWithContext(Context context) {
        mScroller = new Scroller(context, new DecelerateInterpolator());
        // XListView need the scroll event, and it will dispatch the event to
        // user's listener (as a proxy).
        super.setOnScrollListener(this);

        // init header view
        mHeaderView = new XListViewHeader(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView
                .findViewById(R.id.xlistview_header_content);
        mHeaderTimeView = (TextView) mHeaderView
                .findViewById(R.id.xlistview_header_time);
        addHeaderView(mHeaderView);

        // init footer view
        mFooterView = new XListViewFooter(context);

        // init header height
        mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        mHeaderViewHeight = mHeaderViewContent.getHeight();
                        getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                });
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        // make sure XListViewFooter is the last footer view, and only add once.
        if (mIsFooterReady == false) {
            mIsFooterReady = true;
            addFooterView(mFooterView);
        }
        super.setAdapter(adapter);
    }

    /**
     * enable or disable pull down refresh feature.
     *
     * @param enable
     */
    public void setPullRefreshEnable(boolean enable) {
        mEnablePullRefresh = enable;
        if (!mEnablePullRefresh) { // disable, hide the content
            mHeaderViewContent.setVisibility(View.INVISIBLE);
        } else {
            mHeaderViewContent.setVisibility(View.VISIBLE);
        }
    }

    /**
     * enable or disable pull up load more feature.
     *
     * @param enable
     */
    public void setPullLoadEnable(boolean enable) {
        mEnablePullLoad = enable;
        if (!mEnablePullLoad) {
            mFooterView.hide();
            mFooterView.setOnClickListener(null);
            //make sure "pull up" don't show a line in bottom when listview with one page
            setFooterDividersEnabled(false);
        } else {
            mPullLoading = false;
            mFooterView.show();
            mFooterView.setState(XListViewFooter.STATE_NORMAL);
            //make sure "pull up" don't show a line in bottom when listview with one page
            setFooterDividersEnabled(true);
            // both "pull up" and "click" will invoke load more.
            mFooterView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    startLoadMore();
                }
            });
        }
    }

    /**
     * stop refresh, reset header view.
     */
    public void stopRefresh() {
        if (mPullRefreshing == true) {
            mPullRefreshing = false;
            resetHeaderHeight();
        }
    }

    /**
     * stop load more, reset footer view.
     */
    public void stopLoadMore() {
        if (mPullLoading == true) {
            mPullLoading = false;
            mFooterView.setState(XListViewFooter.STATE_NORMAL);
        }
    }

    /**
     * set last refresh time
     *
     * @param time
     */
    public void setRefreshTime(String time) {
        mHeaderTimeView.setText(time);
    }

    private void invokeOnScrolling() {
        if (mScrollListener instanceof OnXScrollListener) {
            OnXScrollListener l = (OnXScrollListener) mScrollListener;
            l.onXScrolling(this);
        }
    }

    private void updateHeaderHeight(float delta) {
        mHeaderView.setVisiableHeight((int) delta
                + mHeaderView.getVisiableHeight());
        if (mEnablePullRefresh && !mPullRefreshing) { // 未处于刷新状æ€�,更新箭头
            if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                mHeaderView.setState(XListViewHeader.STATE_READY);
            } else {
                mHeaderView.setState(XListViewHeader.STATE_NORMAL);
            }
        }
        setSelection(0); // scroll to top each time
    }

    /**
     * reset header view's height.
     */
    private void resetHeaderHeight() {
        int height = mHeaderView.getVisiableHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn't shown fully. do nothing.
        if (mPullRefreshing && height <= mHeaderViewHeight) {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing && height > mHeaderViewHeight) {
            finalHeight = mHeaderViewHeight;
        }
        mScrollBack = SCROLLBACK_HEADER;
        mScroller.startScroll(0, height, 0, finalHeight - height,
                SCROLL_DURATION);
        // trigger computeScroll
        invalidate();
    }

    private void updateFooterHeight(float delta) {
        int height = mFooterView.getBottomMargin() + (int) delta;
        if (mEnablePullLoad && !mPullLoading) {
            if (height > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
                                                    // more.
                mFooterView.setState(XListViewFooter.STATE_READY);
            } else {
                mFooterView.setState(XListViewFooter.STATE_NORMAL);
            }
        }
        mFooterView.setBottomMargin(height);

//        setSelection(mTotalItemCount - 1); // scroll to bottom
    }

    private void resetFooterHeight() {
        int bottomMargin = mFooterView.getBottomMargin();
        if (bottomMargin > 0) {
            mScrollBack = SCROLLBACK_FOOTER;
            mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
                    SCROLL_DURATION);
            invalidate();
        }
    }

    private void startLoadMore() {
        mPullLoading = true;
        mFooterView.setState(XListViewFooter.STATE_LOADING);
        if (mListViewListener != null) {
            mListViewListener.onLoadMore();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mLastY == -1) {
            mLastY = ev.getRawY();
        }

        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mLastY = ev.getRawY();
            break;
        case MotionEvent.ACTION_MOVE:
            final float deltaY = ev.getRawY() - mLastY;
            mLastY = ev.getRawY();
            if (getFirstVisiblePosition() == 0
                    && (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) {
                // the first item is showing, header has shown or pull down.
                updateHeaderHeight(deltaY / OFFSET_RADIO);
                invokeOnScrolling();
            } else if (getLastVisiblePosition() == mTotalItemCount - 1
                    && (mFooterView.getBottomMargin() > 0 || deltaY < 0)) {
                // last item, already pulled up or want to pull up.
                updateFooterHeight(-deltaY / OFFSET_RADIO);
            }
            break;
        default:
            mLastY = -1; // reset
            if (getFirstVisiblePosition() == 0) {
            /*    // invoke refresh
                if (mEnablePullRefresh
                        && mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                    mPullRefreshing = true;
                    mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
                    if (mListViewListener != null) {
                        mListViewListener.onRefresh();
                    }
                }*/
                resetHeaderHeight();
            } else if (getLastVisiblePosition() == mTotalItemCount - 1) {
                // invoke load more.
                if (mEnablePullLoad
                    && mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA
                    && !mPullLoading) {
                    startLoadMore();
                }
                resetFooterHeight();
        }
            break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            if (mScrollBack == SCROLLBACK_HEADER) {
                mHeaderView.setVisiableHeight(mScroller.getCurrY());
            } else {
                mFooterView.setBottomMargin(mScroller.getCurrY());
            }
            postInvalidate();
            invokeOnScrolling();
        }
        super.computeScroll();
    }

    @Override
    public void setOnScrollListener(OnScrollListener l) {
        mScrollListener = l;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mScrollListener != null) {
            mScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // send to user's listener
        mTotalItemCount = totalItemCount;
        if (mScrollListener != null) {
            mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
                    totalItemCount);
        }
    }

    public void setXListViewListener(IXListViewListener l) {
        mListViewListener = l;
    }

    /**
     * you can listen ListView.OnScrollListener or this one. it will invoke
     * onXScrolling when header/footer scroll back.
     */
    public interface OnXScrollListener extends OnScrollListener {
        public void onXScrolling(View view);
    }

    /**
     * implements this interface to get refresh/load more event.
     */
    public interface IXListViewListener {
        public void onRefresh();

        public void onLoadMore();
    }
}

XListViewFooter.java

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;


public class XListViewFooter extends LinearLayout {
    public final static int STATE_NORMAL = 0;
    public final static int STATE_READY = 1;
    public final static int STATE_LOADING = 2;

    private Context mContext;

    private View mContentView;
    private View mProgressBar;
    private TextView mHintView;
   
    public XListViewFooter(Context context) {
        super(context);
        initView(context);
    }
   
    public XListViewFooter(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

   
    public void setState(int state) {
        mHintView.setVisibility(View.INVISIBLE);
        mProgressBar.setVisibility(View.INVISIBLE);
        mHintView.setVisibility(View.INVISIBLE);
        if (state == STATE_READY) {
            mHintView.setVisibility(View.VISIBLE);
            mHintView.setText(R.string.xlistview_footer_hint_ready);
        } else if (state == STATE_LOADING) {
            mProgressBar.setVisibility(View.GONE);
        } else {
            mHintView.setVisibility(View.VISIBLE);
            mHintView.setText(R.string.xlistview_footer_hint_normal);
        }
    }
   
    public void setBottomMargin(int height) {
        if (height < 0) return ;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
        lp.bottomMargin = height;
        mContentView.setLayoutParams(lp);
    }

    public int getBottomMargin() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
        return lp.bottomMargin;
    }


    /**
     * normal status
     */
    public void normal() {
        mHintView.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.GONE);
    }


    /**
     * loading status
     */
    public void loading() {
        mHintView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    /**
     * hide footer when disable pull load more
     */
    public void hide() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
        lp.height = 0;
        mContentView.setLayoutParams(lp);
    }

    /**
     * show footer
     */
    public void show() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
        lp.height = LayoutParams.WRAP_CONTENT;
        mContentView.setLayoutParams(lp);
    }

    private void initView(Context context) {
        mContext = context;
        LinearLayout moreView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.xlistview_footer, null);
        addView(moreView);
        moreView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
       
        mContentView = moreView.findViewById(R.id.xlistview_footer_content);
        mProgressBar = moreView.findViewById(R.id.xlistview_footer_progressbar);
        mHintView = (TextView)moreView.findViewById(R.id.xlistview_footer_hint_textview);
    }
   
   
}
 
XListViewHeader.java

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


public class XListViewHeader extends LinearLayout {
    private LinearLayout mContainer;
    private ImageView mArrowImageView;
    private ProgressBar mProgressBar;
    private TextView mHintTextView;
    private int mState = STATE_NORMAL;

    private Animation mRotateUpAnim;
    private Animation mRotateDownAnim;
   
    private final int ROTATE_ANIM_DURATION = 180;
   
    public final static int STATE_NORMAL = 0;
    public final static int STATE_READY = 1;
    public final static int STATE_REFRESHING = 2;

    public XListViewHeader(Context context) {
        super(context);
        initView(context);
    }

    /**
     * @param context
     * @param attrs
     */
    public XListViewHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
       
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, 0);
        mContainer = (LinearLayout) LayoutInflater.from(context).inflate(
                R.layout.xlistview_header, null);
        addView(mContainer, lp);
        setGravity(Gravity.BOTTOM);

        mArrowImageView = (ImageView)findViewById(R.id.xlistview_header_arrow);
        mHintTextView = (TextView)findViewById(R.id.xlistview_header_hint_textview);
        mProgressBar = (ProgressBar)findViewById(R.id.xlistview_header_progressbar);

        mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
        mRotateUpAnim.setFillAfter(true);
        mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
        mRotateDownAnim.setFillAfter(true);
    }

    public void setState(int state) {
        if (state == mState) return ;

        if (state == STATE_REFRESHING) {    // 显示进度
            mArrowImageView.clearAnimation();
            mArrowImageView.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.VISIBLE);
        } else {    // 显示箭头图片
            mArrowImageView.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
        }

        switch(state){
        case STATE_NORMAL:
            if (mState == STATE_READY) {
                mArrowImageView.startAnimation(mRotateDownAnim);
            }
            if (mState == STATE_REFRESHING) {
                mArrowImageView.clearAnimation();
            }
            mHintTextView.setText(R.string.xlistview_header_hint_normal);
            break;
        case STATE_READY:
            if (mState != STATE_READY) {
                mArrowImageView.clearAnimation();
                mArrowImageView.startAnimation(mRotateUpAnim);
                mHintTextView.setText(R.string.xlistview_header_hint_ready);
            }
            break;
        case STATE_REFRESHING:
            mHintTextView.setText(R.string.xlistview_header_hint_loading);
            break;
            default:
        }

        mState = state;
    }

    public void setVisiableHeight(int height) {
        if (height < 0)
            height = 0;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer
                .getLayoutParams();
        lp.height = height;
        mContainer.setLayoutParams(lp);
    }

    public int getVisiableHeight() {
        return mContainer.getLayoutParams().height;
    }

}
 
xlistview_footer.xml

<?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:text="@string/xlistview_footer_hint_normal" />
    </RelativeLayout>

</LinearLayout>

xlistview_header.xml

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

Sunday, 26 July 2015


CalendarView in Activity


In this example we have created three java class and two xml files such as Utility.class, CalendarView.class, CalendarAdapter.class and xml is calendar.xml, calendar_item.xml . 

CalendarAdapter.class

package com.examples.android.calendar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CalendarAdapter extends BaseAdapter {
private Context mContext;

private java.util.Calendar month;
public GregorianCalendar pmonth; // calendar instance for previous month
/**
* calendar instance for previous month for getting complete view
*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int lastWeekDay;
int leftDays;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;

private ArrayList<String> items;
public static List<String> dayString;
private View previousView;

public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}

public void setItems(ArrayList<String> items) {
for (int i = 0; i != items.size(); i++) {
if (items.get(i).length() == 1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}

public int getCount() {
return dayString.size();
}

public Object getItem(int position) {
return dayString.get(position);
}

public long getItemId(int position) {
return 0;
}

// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);

}
dayView = (TextView) v.findViewById(R.id.date);
// separates daystring into parts.
String[] separatedTime = dayString.get(position).split("-");
// taking last part of date. ie; 2 from 2012-12-02
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
// checking whether the day is in current month or not.
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
// setting offdays to white color.
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.BLUE);
}

if (dayString.get(position).equals(curentDateString)) {
setSelected(v);
previousView = v;
} else {
v.setBackgroundResource(R.drawable.list_item_background);
}
dayView.setText(gridvalue);

// create date string for comparison
String date = dayString.get(position);

if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}

// show icon if date is not empty and it exists in the items array
ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
if (date.length() > 0 && items != null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
} else {
iw.setVisibility(View.INVISIBLE);
}
return v;
}

public View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}

public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);

/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {

itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
dayString.add(itemvalue);

}
}

private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

return maxP;
}

}




CalendarView.class



package com.examples.android.calendar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Locale;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CalendarView extends Activity {

public GregorianCalendar month, itemmonth;// calendar instances.

public CalendarAdapter adapter;// adapter instance
public Handler handler;// for grabbing some event values for showing the dot
// marker.
public ArrayList<String> items; // container to store calendar items which
// needs showing the event marker
ArrayList<String> event;
LinearLayout rLayout;
ArrayList<String> date;
ArrayList<String> desc;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
Locale.setDefault(Locale.US);

rLayout = (LinearLayout) findViewById(R.id.text);
month = (GregorianCalendar) GregorianCalendar.getInstance();
itemmonth = (GregorianCalendar) month.clone();

items = new ArrayList<String>();

adapter = new CalendarAdapter(this, month);

GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);

handler = new Handler();
handler.post(calendarUpdater);

TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);

previous.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
setPreviousMonth();
refreshCalendar();
}
});

RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
setNextMonth();
refreshCalendar();

}
});

gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// removing the previous view if added
if (((LinearLayout) rLayout).getChildCount() > 0) {
((LinearLayout) rLayout).removeAllViews();
}
desc = new ArrayList<String>();
date = new ArrayList<String>();
((CalendarAdapter) parent.getAdapter()).setSelected(v);
String selectedGridDate = CalendarAdapter.dayString
.get(position);
String[] separatedTime = selectedGridDate.split("-");
String gridvalueString = separatedTime[2].replaceFirst("^0*",
"");// taking last part of date. ie; 2 from 2012-12-02.
int gridvalue = Integer.parseInt(gridvalueString);
// navigate to next or previous month on clicking offdays.
if ((gridvalue > 10) && (position < 8)) {
setPreviousMonth();
refreshCalendar();
} else if ((gridvalue < 7) && (position > 28)) {
setNextMonth();
refreshCalendar();
}
((CalendarAdapter) parent.getAdapter()).setSelected(v);

for (int i = 0; i < Utility.startDates.size(); i++) {
if (Utility.startDates.get(i).equals(selectedGridDate)) {
desc.add(Utility.nameOfEvent.get(i));
}
}

if (desc.size() > 0) {
for (int i = 0; i < desc.size(); i++) {
TextView rowTextView = new TextView(CalendarView.this);

// set some properties of rowTextView or something
rowTextView.setText("Event:" + desc.get(i));
rowTextView.setTextColor(Color.BLACK);

// add the textview to the linearlayout
rLayout.addView(rowTextView);

}

}

desc = null;

}

});
}

protected void setNextMonth() {
if (month.get(GregorianCalendar.MONTH) == month
.getActualMaximum(GregorianCalendar.MONTH)) {
month.set((month.get(GregorianCalendar.YEAR) + 1),
month.getActualMinimum(GregorianCalendar.MONTH), 1);
} else {
month.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) + 1);
}

}

protected void setPreviousMonth() {
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
month.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
month.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}

}

protected void showToast(String string) {
Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

}

public void refreshCalendar() {
TextView title = (TextView) findViewById(R.id.title);

adapter.refreshDays();
adapter.notifyDataSetChanged();
handler.post(calendarUpdater); // generate some calendar items

title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
}

public Runnable calendarUpdater = new Runnable() {

@Override
public void run() {
items.clear();

// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String itemvalue;
event = Utility.readCalendarEvent(CalendarView.this);
Log.d("=====Event====", event.toString());
Log.d("=====Date ARRAY====", Utility.startDates.toString());

for (int i = 0; i < Utility.startDates.size(); i++) {
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(GregorianCalendar.DATE, 1);
items.add(Utility.startDates.get(i).toString());
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
}


Utility.class


package com.examples.android.calendar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class Utility {
public static ArrayList<String> nameOfEvent = new ArrayList<String>();
public static ArrayList<String> startDates = new ArrayList<String>();
public static ArrayList<String> endDates = new ArrayList<String>();
public static ArrayList<String> descriptions = new ArrayList<String>();

public static ArrayList<String> readCalendarEvent(Context context) {
Cursor cursor = context.getContentResolver()
.query(Uri.parse("content://com.android.calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null,
null, null);
cursor.moveToFirst();
// fetching calendars name
String CNames[] = new String[cursor.getCount()];

// fetching calendars id
nameOfEvent.clear();
startDates.clear();
endDates.clear();
descriptions.clear();
for (int i = 0; i < CNames.length; i++) {

nameOfEvent.add(cursor.getString(1));
startDates.add(getDate(Long.parseLong(cursor.getString(3))));
endDates.add(getDate(Long.parseLong(cursor.getString(4))));
descriptions.add(cursor.getString(2));
CNames[i] = cursor.getString(1);
cursor.moveToNext();

}
return nameOfEvent;
}

public static String getDate(long milliSeconds) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
}


calendar_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/calendar_cell"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="2dip" >

    <TextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0000D7"
        android:textSize="14dip"
        android:textStyle="bold" >
    </TextView>

    <ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/date_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/date"
        android:src="@drawable/dot"
        android:visibility="gone" />

</LinearLayout>

calendar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/calendar_top" >

        <RelativeLayout
            android:id="@+id/previous"
            android:layout_width="40dip"
            android:layout_height="30dip"
            android:layout_alignParentLeft="true" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/arrow_left" />
        </RelativeLayout>

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dip"
            android:textColor="#000000"
            android:textSize="18dip"
            android:textStyle="bold" />

        <RelativeLayout
            android:id="@+id/next"
            android:layout_width="40dip"
            android:layout_height="30dip"
            android:layout_alignParentRight="true" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/arrow_right" />
        </RelativeLayout>
    </RelativeLayout>

    <GridView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridview"
        android:layout_below="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:listSelector="@android:color/transparent"
        android:numColumns="7"
        android:stretchMode="columnWidth" />
    
    <LinearLayout 
        android:id="@+id/text"
        android:layout_below="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <!-- <TextView 
           android:id="@+id/tvView"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:visibility="gone"
           android:text=""/> -->
    </LinearLayout>

</RelativeLayout>


In AndroidManifest to give two permission that is  
<uses-permission android:name="android.permission.READ_CALENDAR"/>
 <uses-permission android:name="android.permission.WRITE_CALENDAR"/>





Tuesday, 14 July 2015

Marquee in android


Marquee in Android


In xml file you enter the this code:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:lines="1"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:textColor="#ff4500"
        android:singleLine="true"
        android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>

In java file you enter this code:

textView =(TextView) rootView.findViewById(R.id.mywidget);
 textView.setSelected(true);

Wednesday, 11 March 2015

Android Login Screen Tutorial





DBAdapter.java:-
package com.my.members;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.Cursor;
public class DBAdapter
import android.database.sqlite.SQLiteDatabase; {
public static final String KEY_ROW_ID = "_id";
private static final String DATABASE_TABLE = "members";
public static final String KEY_PASSWORD = "password";
public static final String KEY_USERNAME = "username"; SQLiteDatabase mDb; Context mCtx;
public DBAdapter open() throws SQLException
DBHelper mDbHelper; public DBAdapter(Context context) { this.mCtx = context; } {
{
mDbHelper = new DBHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close()
ContentValues initialValues = new ContentValues();
mDbHelper.close(); } public long register(String user,String pw) { initialValues.put(KEY_USERNAME, user);
public boolean Login(String username, String password) throws SQLException
initialValues.put(KEY_PASSWORD, pw); return mDb.insert(DATABASE_TABLE, null, initialValues); } {
if (mCursor != null) {
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password}); if(mCursor.getCount() > 0) { return true; } }
}
return false;
}
DBHelper.java:-
package com.my.members;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
private static final String DATABASE_NAME = "membersdb";
public class DBHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE (_id integer primary key autoincrement,username text not null,password text not null);";
public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override
}
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { db.execSQL("DROP TABLE IF EXISTS members"); onCreate(db); }
MemberActivity.java:-
package com.my.members;
import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.Button; import android.widget.EditText;
EditText txtUserName;
public class MembersActivity extends Activity { DBAdapter dbAdapter; EditText txtPassword; Button btnLogin;
super.onCreate(savedInstanceState);
Button btnRegister; @Override public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btn_login);
txtUserName = (EditText) findViewById(R.id.et_user); txtPassword = (EditText) findViewById(R.id.et_pw); btnRegister = (Button) findViewById(R.id.btn_reg);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
dbAdapter = new DBAdapter(this); dbAdapter.open(); btnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) {
String password = txtPassword.getText().toString();
imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0); imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0); String username = txtUserName.getText().toString();
.show();
if (username.length() > 0 && password.length() > 0) { try { if (dbAdapter.Login(username, password)) { Toast.makeText(MembersActivity.this, "Successfully Logged In", Toast.LENGTH_LONG) } else {
Toast.LENGTH_LONG).show();
Toast.makeText(MembersActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(MembersActivity.this, "Some problem occurred", } } else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
Toast.makeText(MembersActivity.this, "Username or Password is empty", Toast.LENGTH_LONG).show(); } } }); btnRegister.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) {
long i = dbAdapter.register(username, password);
imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0); imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0); try { String username = txtUserName.getText().toString(); String password = txtPassword.getText().toString(); if(i != -1)
}
Toast.makeText(MembersActivity.this, "You have successfully registered",Toast.LENGTH_LONG).show(); } catch (SQLException e) { Toast.makeText(MembersActivity.this, "Some problem occurred", Toast.LENGTH_LONG).show(); } } });
}
main.xml:-
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:textSize="40dp" android:layout_gravity="right" android:layout_marginBottom="10dp" android:layout_marginLeft="30dp"/> <TableLayout android:id="@+id/tableLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" > </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <EditText android:id="@+id/et_user" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="250dp" android:layout_marginLeft="30dp" android:layout_marginBottom="10dp" android:hint="@string/u"> <requestFocus /> </EditText> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" > <EditText android:id="@+id/et_pw" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPassword" android:layout_marginLeft="30dp" android:layout_marginBottom="10dp" android:hint="@string/p"/> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/btn_login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/l" android:layout_marginLeft="30dp" android:layout_marginBottom="10dp" android:textSize="20dp"/> </TableRow> <TableRow android:id="@+id/tableRow5" android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/btn_reg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/r" android:layout_marginLeft="30dp" android:layout_marginBottom="10dp" android:textSize="20dp"/> </TableRow> </TableLayout> </LinearLayout>

Sunday, 8 March 2015

What is Android ???


Android is a mobile operating system (OS) based on the Linux kernel and currently developed by Google. 

Platform usage in Android


Charts in this section provide breakdowns of Android versions, based on the devices accessing the Play Store in a seven-day period ending on March 2, 2015. Therefore, these statistics exclude Android forks that do not access Google Play, such as Amazon's Fire tablets.

VersionCode nameRelease dateAPI levelDistribution
2.2FroyoMay 20, 201080.4%
2.3.3–2.3.7GingerbreadFebruary 9, 2011106.9%
4.0.3–4.0.4Ice Cream SandwichDecember 16, 2011155.9%
4.1.xJelly BeanJuly 9, 20121617.3%
4.2.xJelly BeanNovember 13, 20121719.4%
4.3Jelly BeanJuly 24, 2013185.9%
4.4KitKatOctober 31, 20131940.9%
5.0LollipopNovember 3, 2014213.3%
VersionCode nameRelease dateAPI levelDistribution
5.0LollipopNovember 3, 2014213.3%
4.4KitKatOctober 31, 20131940.9%
4.3Jelly BeanJuly 24, 2013185.9%
4.2.xNovember 13, 20121719.4%
4.1.xJuly 9, 20121617.3%
4.0.3–4.0.4Ice Cream SandwichDecember 16, 2011155.9%
2.3.3–2.3.7GingerbreadFebruary 9, 2011106.9%
2.2FroyoMay 20, 201080.4%