Friday 31 March 2017

How to use the Filtering on RecycleView in Android Studio.

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


First we need to add Library to our project.  

compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:design:25.2.0'


Create Xml file in project.    
Open => app => res => layout - activity_main.xml.


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

    tools:context="com.gswebtechnologies.recycleviewfiltering.MainActivity">

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

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="12dp" />


    </LinearLayout>
</RelativeLayout>

   

Create the Java file in project.
Open app => main => src = MainActivity.java


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.SearchView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private static final String TAG = "MainActivity";
    RecyclerView recyclerView;
    SearchView searchView;
    RecycleViewAdapter recycleViewAdapter;
    private ArrayList<ListItem> listItems;

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

        //getting the widget id
        init();
        //using the click listner in android
        listener();
        //set the data in listView
        setList();
        //SearchView
        setSearchView();

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recycleViewAdapter = new RecycleViewAdapter(this, listItems);
        recyclerView.setAdapter(recycleViewAdapter);

    }

    private void setSearchView() {
        searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(this);
        searchView.setSubmitButtonEnabled(true);
        searchView.setQueryHint("Search Here");
    }

    private void init() {
        recyclerView = (RecyclerView) findViewById(R.id.recycleView);
        //SearchView
        searchView = (SearchView) findViewById(R.id.searchView);
    }

    private void listener() {

    }

    public void setList() {

        listItems = new ArrayList<ListItem>();

        ListItem item = new ListItem();
        item.setData("Google");
        listItems.add(item);

        item = new ListItem();
        item.setData("Arun");
        listItems.add(item);

        item = new ListItem();
        item.setData("Kamal");
        listItems.add(item);

        item = new ListItem();
        item.setData("Balvinder");
        listItems.add(item);

        item = new ListItem();
        item.setData("Manjeet");
        listItems.add(item);


    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        recycleViewAdapter.filter(newText);
        return true;
    }
}


Create the Java file in project.
Open app => main => src = RecycleViewAdapter.java

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;



public class RecycleViewAdapter extends RecyclerView.Adapter<MyCustomViewHolder>{

    private List<ListItem> listItems, filterList;
    private Context mContext;

    public RecycleViewAdapter(Context context, List<ListItem> listItems) {
        this.listItems = listItems;
        this.mContext = context;
        this.filterList = new ArrayList<ListItem>();
        // we copy the original list to the filter list and use it for setting row values
        this.filterList.addAll(this.listItems);
    }

    @Override
    public MyCustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item, null);
        MyCustomViewHolder viewHolder = new MyCustomViewHolder(view);
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(MyCustomViewHolder customViewHolder, int position) {

        ListItem listItem = filterList.get(position);
        customViewHolder.tvName.setText(listItem.name);


    }

    @Override
    public int getItemCount() {
        return (null != filterList ? filterList.size() : 0);
    }

    // Do Search...
    public void filter(final String text) {

        // Searching could be complex..so we will dispatch it to a different thread...
        new Thread(new Runnable() {
            @Override
            public void run() {

                // Clear the filter list
                filterList.clear();

                // If there is no search value, then add all original list items to filter list
                if (TextUtils.isEmpty(text)) {

                    filterList.addAll(listItems);

                } else {
                    // Iterate in the original List and add it to filter list...
                    for (ListItem item : listItems) {
                        if (item.name.toLowerCase().contains(text.toLowerCase()) ||
                                item.name.toLowerCase().contains(text.toLowerCase())) {
                            // Adding Matched items
                            filterList.add(item);
                        }
                    }
                }

                // Set on UI Thread
                ((Activity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Notify the List that the DataSet has changed...
                        notifyDataSetChanged();
                    }
                });

            }
        }).start();

    }
}



Create the Java file in project.

Open app => main => src = MyCustomViewHolder.java


import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MyCustomViewHolder extends RecyclerView.ViewHolder {

    protected ImageView imageView;
    protected TextView tvName, tvPlace;
    protected ImageView imgThumb;

    public MyCustomViewHolder(View view) {
        super(view);
        this.tvName = (TextView) view.findViewById(R.id.txtName);

    }
}  


Create the Java file in project.
Open app => main => src = ListItem.java



public class ListItem {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    String name;


    public void setData(String name){
        this.name=name;

    }
}


May this code help you. Thanks!!!!!!
How to get the User detail through facebook in Android Studio..

Creating Facebook App.

Go to https://developers.facebook.com/.

First we need to add Volley Library to our project.
compile 'com.facebook.android:facebook-android-sdk:4.0.0'

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.
Create Xml file in project.   
Open => app => res => layout - activity_main.xml.


<com.facebook.login.widget.LoginButton
                android:id="@+id/login_button"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginBottom="24dp"
                android:background="@drawable/bt_facebook"
                android:padding="12dp"
                android:layout_marginTop="12dp"
                />


Create the Java file in project.
Open app => main => src = MainActivity.java


    private CallbackManager callbackManager;
    LoginButton login_button;
    String email,name,first_name,last_name;

        //*******savedInstanceState******//

        FacebookSdk.sdkInitialize(this.getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        //***put the facebookSDK and callbackManager Object in middle saveInstanceState and setContentView*****//
    


login_button=(LoginButton) findViewById(R.id.login_button);
        login_button.setReadPermissions(Arrays.asList("public_profile","email"));
        login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
        {
            @Override
            public void onSuccess(LoginResult loginResult)
            {

                GraphRequest graphRequest  = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
                {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response)
                    {
                        sendData(object);
                    }
                });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,first_name,last_name,email");
                graphRequest.setParameters(parameters);
                graphRequest.executeAsync();
            }

            @Override
            public void onCancel()
            {

            }

            @Override
            public void onError(FacebookException exception)
            {

            }
        });

    }

    private void sendData(JSONObject object) {
        try {
            email = object.getString("email");
            name = object.getString("name");
            first_name = object.optString("first_name");
            last_name = object.optString("last_name");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Intent main = new Intent(MainActivity.this, YourActivity.class);
        main.putExtra("email", email);
        main.putExtra("name", name);
        startActivity(main);
    }


    @Override
    protected void onRestart() {
        LoginManager.getInstance().logOut();
        super.onRestart();
    }

    @Override
    protected void onResume() {
        LoginManager.getInstance().logOut();
        super.onResume();
    }

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        callbackManager.onActivityResult(requestCode, resultCode, intent);
      
    }

Add Internet permission in your manifest.

<uses-permission android:name="android.permission.INTERNET" />







How scan the data through Aadhar Card in Android.


First we need to add Library to our project.

compile 'com.journeyapps:zxing-android-embedded:2.0.1@aar'  
compile 'com.journeyapps:zxing-android-legacy:2.0.1@aar'
compile 'com.journeyapps:zxing-android-integration:2.0.1@aar'
compile 'com.google.zxing:core:3.
0.1'

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create the Java file in project.

Open app => main => src = MainActivity.java



Create Xml file in project.    
Open => app => res => layout - activity_main.xml.


 <LinearLayout
        android:id="@+id/ll_scan_qr_wrapper"
        android:layout_width="match_parent"
        android:layout_height="72dp"
        android:background="#fff"
        android:padding="8dp"
        android:orientation="horizontal"
        android:onClick="scanNow">
        <!-- scanner -->
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1.50">
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@mipmap/qr_scanner"/>
        </LinearLayout>


Create the Java file in project.

Open app => main => src = MainActivity.java


  String uid,user_name,gender,yearOfBirth,careOf,villageTehsil,postOffice,district,state,postCode;
 LinearLayout ll_scanned_data_wrapper = (LinearLayout)findViewById(R.id.ll_scan_qr_wrapper);

/**
     * onclick handler for scan new card
     * @param view
     */
    public void scanNow( View view){
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setPrompt("Scan a Aadharcard QR Code");
        integrator.setResultDisplayDuration(500);
        integrator.setCameraId(0);  // Use a specific camera of the device
        integrator.initiateScan();
    }

    /**
     * function handle scan result
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        callbackManager.onActivityResult(requestCode, resultCode, intent);
        //retrieve scan result
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

        if (scanningResult != null) {
            //we have a result
            String scanContent = scanningResult.getContents();
            String scanFormat = scanningResult.getFormatName();

            // process received data
            if(scanContent != null && !scanContent.isEmpty()){
                processScannedData(scanContent);
            }else{

            }

        }else{

        }
    }
    /**
     * process xml string received from aadhaar card QR code
     * @param scanData
     */
    protected void processScannedData(String scanData){

        XmlPullParserFactory pullParserFactory;

        try {
            // init the parserfactory
            pullParserFactory = XmlPullParserFactory.newInstance();
            // get the parser
            XmlPullParser parser = pullParserFactory.newPullParser();

            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(new StringReader(scanData));

            // parse the XML
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if(eventType == XmlPullParser.START_DOCUMENT) {

                } else if(eventType == XmlPullParser.START_TAG && DataAttributes.AADHAAR_DATA_TAG.equals(parser.getName())) {
                    // extract data from tag
                    //uid
                    uid = parser.getAttributeValue(null,DataAttributes.AADHAR_UID_ATTR);
                    //name
                    user_name = parser.getAttributeValue(null,DataAttributes.AADHAR_NAME_ATTR);
                    //gender
                    gender = parser.getAttributeValue(null,DataAttributes.AADHAR_GENDER_ATTR);
                    // year of birth
                    yearOfBirth = parser.getAttributeValue(null,DataAttributes.AADHAR_YOB_ATTR);
                    // care of
                    careOf = parser.getAttributeValue(null, DataAttributes.AADHAR_CO_ATTR);
                    // village Tehsil
                    villageTehsil = parser.getAttributeValue(null,DataAttributes.AADHAR_VTC_ATTR);
                    // Post Office
                    postOffice = parser.getAttributeValue(null,DataAttributes.AADHAR_PO_ATTR);
                    // district
                    district = parser.getAttributeValue(null,DataAttributes.AADHAR_DIST_ATTR);
                    // state
                    state = parser.getAttributeValue(null,DataAttributes.AADHAR_STATE_ATTR);
                    // Post Code
                    postCode = parser.getAttributeValue(null,DataAttributes.AADHAR_PC_ATTR);

                } else if(eventType == XmlPullParser.END_TAG) {


                } else if(eventType == XmlPullParser.TEXT) {


                }
                // update eventType
                eventType = parser.next();
            }

            // display the data on screen
          displayScannedData();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }// EO function

    /**
     * show scanned information
     */
    public void displayScannedData(){

        String mName=user_name;
        String mUid=uid;
        String name=gender;
    
    }



Add Internet permission in your manifest.

<uses-permission android:name="android.permission.INTERNET" />







Thursday 30 March 2017

How to  the Data locally in Android Studio.

[
{"ID":1,"name":"A"},
{"ID":2,"name":"B"},
{"ID":3,"name":"C"},
{"ID":4,"name":"D"},
{"ID":5,"name":"E"},
{"ID":6,"name":"F"},
{"ID":7,"name":"G"}
]


First we need to add Volley Library to our project.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


Create the Java file in project.
Open app => main => src = MainActivity.java


              TimeAdapter timeAdapter;
              final ArrayList<TimeItem> timeArrayList = new ArrayList<>();

              DataBaseHandler handler = new DataBaseHandler(this);
              NetworkUtils utils = new NetworkUtils(MainActivity.this);

                if (handler.getMenuCount() == 0 && utils.isConnectingToInternet()) {
                    //Execute the AsyncTask
                    customDialog();
              } else {
                    ListView popListView = (ListView) findViewById(R.id.popList);
                    final ArrayList<TimeItem> menuList = handler.getAllMenu();
                    timeAdapter = new TimeAdapter(MainActivity.this, menuList);
                    popListView.setAdapter(timeAdapter);
                }

            }
        });

 private void customDialog() {
        String GET_URL = "http://clientdemo.mayaitsolution.com/upload/getallmenus";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String mID=jsonObject.getString("ID");
                                String menu_id=jsonObject.getString("ID");
                                String mDay = jsonObject.getString("name");
                                TimeItem timeItem = new TimeItem();
                                timeItem.setDay(mDay);

                                //set the data in database
                                handler.addMenu(timeItem);


                                //deleiveryEditText.setText(mDelivery);
                                timeAdapter = new TimeAdapter(MainActivity.this, timeArrayList);
                                // set the adapter object to the Recyclerview
                                timeAdapter.notifyDataSetChanged();
                                popListView.setAdapter(timeAdapter);


                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(stringRequest);

    }

Create Xml file in project.   
Open => app => res => layout - activity_main.xml.


  <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ListView
                android:id="@+id/popList"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </ListView>
        </LinearLayout>


Create Xml file in project.     
Open => app => res => layout - time_row_item.xml.

<?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
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start|center"
        android:orientation="horizontal"
        android:padding="12dp">

        <TextView
            android:id="@+id/txtTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="22dp"
            android:text="Day"
            android:textColor="#000"
            android:textSize="16dp"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>



Create the Java file in project.
Open app => main => src = TimeAdapter.java


public class TimeAdapter extends BaseAdapter {
    ArrayList<TimeItem> items = new ArrayList<TimeItem>();
    Activity con;

    public TimeAdapter(Activity con, ArrayList<TimeItem> items) {
        this.con = con;
        this.items = items;
    }

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

    @Override
    public Object getItem(int pos) {
        return items.get(pos);
    }

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

    @Override
    public View getView(final int pos, View view, ViewGroup viewGroup) {
        LayoutInflater inflator = con.getLayoutInflater();
        View listItem = inflator.inflate(R.layout.time_row_item, null, true);

        //TextView
        TextView dayTextView = (TextView) listItem.findViewById(R.id.txtTime);

        //Typeface childFont = Typeface.createFromAsset(listItem.getContext().getAssets(),"fonts/Titillium-Regular.otf");
        //dayTextView.setTypeface(childFont);

        //Get and set the data here
        dayTextView.setText(items.get(pos).getDay());
        return listItem;
    }
}


Create the Java file in project.
Open app => main => src = TimeItem.java

public class TimeItem {
    String day;

    public String getDay() {
        return day;
    }

    public void setDay(String day) {
        this.day = day;
    }
}


Create the Java file in project.
Open app => main => src = NetworkUtils.java


public class NetworkUtils {

    private Context context;

    public NetworkUtils(Context context) {
        this.context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }

}


Create the Java file in project.
Open app => main => src = Listener.java


interface Listener {
    //Main image
    public void addItem(TimeItem city);
    public ArrayList<TimeItem> getAllItem();
    public int getItemCount();

    //Main Menu List
    public void addMenu(TimeItem city);
    public ArrayList<TimeItem> getAllMenu();
    public int getMenuCount();




    // Category
    public void SaveJsonSubCat(String data, JSONArray jsonObject);
    public boolean isItemAvailable(String url);
    JSONArray GetSubCat(String data);


    // Gallery Image
    public void SaveImage(String data, JSONArray jsonObject);
    public boolean isItemImage(String url);
    JSONArray GetImage(String data);

}




Create the Java file in project.
Open app => main => src = DataBaseHandler  .java


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.easy.cube.customitem.TimeItem;

import org.json.JSONArray;

import java.util.ArrayList;

/**
 * Created by Shobhna on 16-Mar-16.
 */

public class DataBaseHandler  extends SQLiteOpenHelper implements Listener {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Database.db";
    //Main category Activity
    public static final String TABLE_NAME = "item_table";

    public static final String TABLE_MENU = "item_list";
    public static final String TABLE_ALL_IMAGE = "all_image";


    //SubCatgory Activity
    public static final String TABLE_FOOD_ForJson = "cate_menu";
    public static final String TABLE_IMAGE_ForJson = "cate_image";

    private static final String KEY_ID = "_id";
    private static final String KEY_MENU = "_name";
    private static final String KEY_MENU_ID = "_menu_id";
    private static final String KEY_ALL_IMAGE = "url_image";
    private static final String KEY_IMAGE = "_image";


    ///************************START*********************************//
    //All Catogory Table
    String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE + " TEXT)";
    String CREATE_TABLE_MENU = "CREATE TABLE " + TABLE_MENU + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_MENU + " TEXT,"+KEY_MENU_ID +" TEXT)";
    String CREATE_TABLE_ALLIMAGE = "CREATE TABLE " + TABLE_ALL_IMAGE + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ALL_IMAGE + " TEXT)";



    //SubCatogry Table
    String CREATE_FOODForJson = "CREATE TABLE " + TABLE_FOOD_ForJson + " (" + "url" + " TEXT, " + " array " + " TEXT)";

    String CREATE_IMAGEForJson = "CREATE TABLE " + TABLE_IMAGE_ForJson + " (" + "url_image" + " TEXT, " + " array_image" + " TEXT)";



    //Main Category
    String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
    String DROP_TABLE_MENU = "DROP TABLE IF EXISTS " + TABLE_MENU;
    String DROP_TABLE_ALLIMAGE = "DROP TABLE IF EXISTS " + TABLE_ALL_IMAGE;

    String DROP_TABLE_FOOD_ForJson = "DROP TABLE IF EXISTS " + TABLE_FOOD_ForJson;

    String DROP_TABLE_IMAGE_ForJson = "DROP TABLE IF EXISTS " + TABLE_IMAGE_ForJson;








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

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Main Catgory
        db.execSQL(CREATE_TABLE);
        db.execSQL(CREATE_TABLE_MENU);
        db.execSQL(CREATE_TABLE_ALLIMAGE);
        db.execSQL(CREATE_FOODForJson);
        db.execSQL(CREATE_IMAGEForJson);





    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Main Catgory
        db.execSQL(DROP_TABLE);
        db.execSQL(DROP_TABLE_MENU);
        db.execSQL(DROP_TABLE_ALLIMAGE);


        //Catogry
        db.execSQL(DROP_TABLE_FOOD_ForJson);
        db.execSQL(DROP_TABLE_IMAGE_ForJson);

        onCreate(db);
    }


    //Get All Image
    @Override
    public void addItem(TimeItem item) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_IMAGE, item.getImage_url());
            db.insert(TABLE_NAME, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    @Override
    public ArrayList<TimeItem> getAllItem() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<TimeItem> itemList = null;
        try {
            itemList = new ArrayList<TimeItem>();
            String QUERY = "SELECT * FROM " + TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            if (cursor.moveToFirst()) {
                do {
                    TimeItem item = new TimeItem();
                    item.setId(cursor.getString(0));
                    item.setImage_url(cursor.getString(1));
                    itemList.add(item);
                } while (cursor.moveToNext());
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return itemList;
    }

    @Override
    public int getItemCount() {
        int num = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            String QUERY = "SELECT * FROM " + TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            num = cursor.getCount();
            db.close();
            return num;
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return 0;
    }

    ///////////////////////////////////
    //////////////////////////////////
    //Get All Menu
    @Override
    public void addMenu(TimeItem item) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_MENU, item.getDay());
            values.put(KEY_MENU_ID, item.getMenu_id());
            db.insert(TABLE_MENU, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }


    @Override
    public ArrayList<TimeItem> getAllMenu() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<TimeItem> itemList = null;
        try {
            itemList = new ArrayList<TimeItem>();
            String QUERY = "SELECT * FROM " + TABLE_MENU;
            Cursor cursor = db.rawQuery(QUERY, null);
            if (cursor.moveToFirst()) {
                do {
                    TimeItem item = new TimeItem();
                    item.setId(cursor.getString(0));
                    item.setDay(cursor.getString(1));
                    item.setMenu_id(cursor.getString(2));
                    itemList.add(item);
                } while (cursor.moveToNext());
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return itemList;
    }

    @Override
    public int getMenuCount() {
        int num = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            String QUERY = "SELECT * FROM " + TABLE_MENU;
            Cursor cursor = db.rawQuery(QUERY, null);
            num = cursor.getCount();
            db.close();
            return num;
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return 0;
    }



    //////////////////
    //////////////
    ////////////end

    //All SubCatory Table
    //Food catogory
    ///////////////////////////////////////////////////////
    //////////////////////
    @Override
    public void SaveJsonSubCat(String data, JSONArray jsonObject) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put("url", data);
            values.put("array", jsonObject.toString());
            db.insert(TABLE_FOOD_ForJson, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    @Override
    public JSONArray GetSubCat(String data) {
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            //  String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_FOOD_ForJson+" WHERE url = '"+data+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url")).equals(data)){
                        JSONArray obj = new JSONArray(cursor.getString(cursor.getColumnIndex("array")));
                        db.close();
                        return obj;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return null;
    }

    @Override
    public boolean isItemAvailable(String url) {

        SQLiteDatabase db = this.getReadableDatabase();
        try {
            // String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_FOOD_ForJson,null);//+" WHERE url = '"+url+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url")).equals(url)){
                        db.close();
                        return true;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return false;
    }

//**************************************************************************End*****************************************//
    //////Gallary Image////////////////
    /////save images///////


    @Override
    public void SaveImage(String data, JSONArray jsonObject) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put("url_image", data);
            values.put("array_image", jsonObject.toString());
            db.insert(TABLE_IMAGE_ForJson, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    @Override
    public JSONArray GetImage(String data) {
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            //  String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_IMAGE_ForJson+" WHERE url_image = '"+data+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url_image")).equals(data)){
                        JSONArray obj = new JSONArray(cursor.getString(cursor.getColumnIndex("array_image")));
                        db.close();
                        return obj;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return null;
    }

    @Override
    public boolean isItemImage(String url) {

        SQLiteDatabase db = this.getReadableDatabase();
        try {
            // String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_IMAGE_ForJson,null);//+" WHERE url = '"+url+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url_image")).equals(url)){
                        db.close();
                        return true;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return false;
    }

}




Add Internet permission in your manifest

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>






How to filter the data on list in Android.

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

Create the Java file in project.
Open app => main => src = MainActivity.java


SearchView searchView=(SearchView)view.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                (your adapter name).getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                (your adapter name) getFilter().filter(newText);
                return true;
            }
        });


//Click on listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CustomItem mReference = (CustomItem) parent.getAdapter().getItem(position);
                if (String.valueOf(mReference) == null) {
                    Toast.makeText(getActivity(), "NO REFERENCE", Toast.LENGTH_SHORT).show();
                } else {
                    Intent in = new Intent(getActivity(), DetailActivity.class);
                    in.putExtra("reference", mReference.getmReference());
                    startActivity(in);
                }
            }
        });



Create the Java file in project.

Open app => main => src = CustomAdapter .java


/**
 * Created by Saify on 3/21/2017.
 **/

public class CustomAdapter extends BaseAdapter implements Filterable {
    private static ArrayList<CustomItem> searchArrayList;

    private LayoutInflater mInflater;
    private ArrayList<CustomItem> orignalItems = new ArrayList<>();
    private ItemFilter mFilter = new ItemFilter();

    public CustomAdapter (Context context, ArrayList<CustomItem> results) {
        this.searchArrayList = results;
        this.orignalItems =results;
        mInflater = LayoutInflater.from(context);
    }

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

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.hotel_item, null);
            holder = new ViewHolder();
            holder.txtName = (TextView) convertView.findViewById(R.id.name);
           
           convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtName.setText(searchArrayList.get(position).getName());
        return convertView;
    }

    static class ViewHolder {
        TextView txtName;
      
    }

    /**
     * implement base BaseAdapter method here.....
     */

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List<CustomItem> list = orignalItems;

            int count = list.size();
            final ArrayList<CustomItem> nlist = new ArrayList<CustomItem>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i).name;
                if (filterableString.toLowerCase().contains(filterString)) {
                    CustomItem mYourCustomData = list.get(i);
                    nlist.add(mYourCustomData);
                    // nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            searchArrayList = (ArrayList<CustomItem>) results.values;
            notifyDataSetChanged();
        }

    }
}
 


How to post the data in object on server.

Example:

{
    "action": "login",   
    "email": "abc@gmail.com",
    "password": "12345"
}



Creating New Project.

Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project. 
compile 'com.android.support.constraint:constraint-layout:1.0.1'
compile 'com.loopj.android:android-async-http:1.4.9'



Create Xml file in project.    
Open => app => res => layout - activity_main.xml.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="12dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/sendData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send data" />
</LinearLayout>


Create the Java file in project.
Open app => main => src = MainActivity.java



import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;


public class MainActivity extends AppCompatActivity { 
    //Button
    Button loginButton;
    //TextView
    TextView responseTextView;
    // Response
    String responseServer;

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

        //Getting the Widget Id Here
        init();
        //using the click leistner here
        listener();

    }

    private void init() {
        //TextView
        responseTextView = (TextView) findViewById(R.id.txtText);
        //Button
        loginButton = (Button) findViewById(R.id.sendData);
    }

    private void listener() {
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AsyncT asyncT = new AsyncT();
                asyncT.execute();
            }
        });
    }

    /* Inner class to get response */
    class AsyncT extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("Enter your url here");

            try {

                JSONObject jsonobj = new JSONObject();
                jsonobj.put("action", "login");// This field accouding to server requirment...
                jsonobj.put("email_mobile", "abc@gmail.com"); //put the email EditText field text here...
                jsonobj.put("password", "1234");//put the passwors EditText field text here...
                StringEntity stringEntity = new StringEntity(jsonobj.toString());

                httppost.setEntity(stringEntity);
                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                InputStream inputStream = response.getEntity().getContent();
                InputStreamToStringExample str = new InputStreamToStringExample();
                responseServer = str.getStringFromInputStream(inputStream);
                Log.e("response", "response:::" + responseServer);
                //Here getting the response data....

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            //set the server response here
            responseTextView.setText(responseServer);
        }
    }

    public static class InputStreamToStringExample {

        public static void main(String[] args) throws IOException {

            // intilize an InputStream
            InputStream is = new ByteArrayInputStream("file content....".getBytes());
            String result = getStringFromInputStream(is);
        }

        // convert InputStream to String
        private static String getStringFromInputStream(InputStream is) {

            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();

            String line;
            try {

                br = new BufferedReader(new InputStreamReader(is));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return sb.toString();
        }

    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>