Tuesday, 25 April 2017

How to upload the Multipart Request data on server Using Android Volley.

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 'dev.dworks.libs:volleyplus:+'


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

<?xml version="1.0" encoding="utf-8"?>
<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:padding="16dp"
    tools:context="org.snowcorp.imageupload.MainActivity"
    android:orientation="vertical">


    <Button
        android:id="@+id/button_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SelectImage"
        android:textColor="#000"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"
        android:padding="10dp"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/border"
        android:layout_gravity="center_horizontal"
        android:padding="5dp"
        android:layout_margin="20dp"/>

    <Button
        android:id="@+id/button_upload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post"
        android:textColor="#000"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"/>

</LinearLayout>




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

import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.android.volley.request.SimpleMultiPartRequest;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Button choseButton, uploadButton;
    private ProgressBar progressBar;
    public static String BASE_URL = "your url here";
    static final int PICK_IMAGE_REQUEST = 1;
    String filePath;


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

        imageView = (ImageView) findViewById(R.id.imageView);
        choseButton = (Button) findViewById(R.id.button_choose);
        uploadButton = (Button) findViewById(R.id.button_upload);

        choseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageBrowse();
            }
        });

        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (filePath != null) {
                    imageUpload(filePath);
                } else {
                    Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
                }

            }
        });
    }

    private void imageBrowse() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            if(requestCode == PICK_IMAGE_REQUEST){
                Uri picUri = data.getData();
                filePath = getPath(picUri);
                Log.d("filePath", filePath);
                imageView.setImageURI(picUri);

            }
        }
    }

    private void imageUpload(final String imagePath) {

        SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        smr.addFile("image", imagePath);
        MyApplication.getInstance().addToRequestQueue(smr);

    }

    private String getPath(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

}



Create the Java file in project
.

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

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {
    public static final String TAG = MyApplication.class.getSimpleName();
    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}


Add Internet permission in your manifest.

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


 

How to use croper  in andorid.

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 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.jakewharton:butterknife:8.4.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"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/preImage"
        android:layout_width="144dp"
        android:layout_height="144dp"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:src="@mipmap/ic_launcher"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"></de.hdodenhof.circleimageview.CircleImageView>

</RelativeLayout>




Create the Java file in project.

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

import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.soundcloud.android.crop.Crop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

import static journal.shibboleth.com.croperactivity.MarshMallowPermission.CAMERA_PERMISSION_REQUEST_CODE;
import static journal.shibboleth.com.croperactivity.MarshMallowPermission.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE;

public class MainActivity extends AppCompatActivity {

    private static final int CAMERA_REQUEST = 108;
    private String mCurrentPhotoPath = "";
    private MarshMallowPermission marshMallowPermission;
    CircleImageView mPreImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPreImageView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.preImage);

        mPreImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CheckVersions.isMarshmallow()) {
                    marshMallowPermission =
                            new MarshMallowPermission(MainActivity.this);
                    if (!marshMallowPermission.checkPermissionForCamera()) {
                        marshMallowPermission.requestPermissionForCamera();
                    } else {
                        if (!marshMallowPermission.checkPermissionForExternalStorage()) {
                            marshMallowPermission.requestPermissionForExternalStorage();
                        } else {
                            clickImage();
                        }
                    }
                } else {
                    clickImage();
                }
            }
        });



    }

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

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home) {
            Intent returnIntent = new Intent();
            setResult(RESULT_CANCELED, returnIntent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_PERMISSION_REQUEST_CODE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (!marshMallowPermission.checkPermissionForExternalStorage()) {
                        marshMallowPermission.requestPermissionForExternalStorage();
                    } else {
                        clickImage();
                    }
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "Camera permission needed." +
                            " Please allow in App Settings for additional " +
                            "functionality.", Toast.LENGTH_LONG).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            case EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    clickImage();
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "External Storage permission needed. " +
                            "Please allow in App Settings for additional" +
                            " functionality.", Toast.LENGTH_LONG).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }

            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    private void clickImage() {
        final CharSequence[] items = {"Take Photo Camera", "Take Photo Gallery"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo Camera")) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
                        // Create the File where the photo should go
                        File photoFile;
                        photoFile = createImageFile();
                        // Continue only if the File was successfully created
                        if (photoFile != null) {
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        } else {
                            mCurrentPhotoPath = "";
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        }
                    }
                } else if (items[item].equals("Take Photo Gallery")) {
                    Crop.pickImage(MainActivity.this);
                }
            }
        });
        builder.show();
    }
    private File createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  // prefix
                    ".jpg",         // suffix
                    storageDir      // directory

            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Save a file: path for use with ACTION_VIEW intents
        if (image != null) {
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            Log.i("Ihdh", "Image" + mCurrentPhotoPath);
        }
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode != RESULT_CANCELED) {
            if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
                beginCrop(result.getData());
            } else if (requestCode == Crop.REQUEST_CROP) {
                handleCrop(resultCode, result);
            } else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
                if (mCurrentPhotoPath == null || mCurrentPhotoPath.isEmpty()) {
                    beginCrop(result.getData());
                } else {
                    beginCrop(Uri.parse(mCurrentPhotoPath));
                }
            }
        }
    }

    private void beginCrop(Uri source) {
        try {
            File file = MainActivity.this.getCacheDir();
            deleteDir(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        Crop.of(source, destination).asSquare().start(this, Crop.REQUEST_CROP);
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir != null && dir.delete();
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            try {
                mPreImageView.setImageDrawable(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Log.i("CROP", "handleCrop: " + Crop.getOutput(result));
                mPreImageView.setImageURI(Crop.getOutput(result));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            try {
                Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String saveToInternalStorage(Bitmap bitmapImage) {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        String name = System.currentTimeMillis() + "_image.jpg";
        File mypath = new File(directory, name);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 50, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return directory.getAbsolutePath() + "/" + name;
    }

}

//Check the version in this class.
Create the Java file in project.

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

import android.os.Build;

public class CheckVersions {
    public static boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
}

//Permission....
Create the Java file in project.

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

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

public class MarshMallowPermission {
    public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
    public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;
    Activity activity;

    public MarshMallowPermission(Activity activity) {
        this.activity = activity;
    }


    public boolean checkPermissionForExternalStorage() {
        int result = ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    public boolean checkPermissionForCamera() {
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
        return result == PackageManager.PERMISSION_GRANTED;
    }


    public void requestPermissionForExternalStorage() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(activity, "External Storage permission needed. " +
                    "Please allow in App Settings for additional" +
                    " functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        }
    }

    public void requestPermissionForCamera() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.CAMERA)) {
            Toast.makeText(activity, "Camera permission needed." +
                    " Please allow in App Settings for additional " +
                    "functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.CAMERA},
                    CAMERA_PERMISSION_REQUEST_CODE);
        }
    }

}


Add Internet permission in your manifest.


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />

<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>






May this code help you. Thanks!!!!!!

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>