Thursday 3 August 2017

JSON PARSING CLASS

                        JSON PARSING CLASS

----------------------APPCONTROLLER CLASS----------------------
package com.httpabcdefapp1123.timetablenew;

import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

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



public class AppController extends MultiDexApplication {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;
    DiskBasedCache cache;

    @Override    public void onCreate() {
        super.onCreate();
        mInstance = this;
//        new LoginDataHelper(this);//        new UserDetailDataHelper(this); 
 MultiDex.install(this);
        // Create global configuration and initialize ImageLoader with this config    }

    public DiskBasedCache getDiskCache() {
        if (cache == null) {
            cache = new DiskBasedCache(getExternalCacheDir(), 209715200);
        }
        return cache;
    }

    public static synchronized AppController 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);
        }
    }
}









----------helper class-------------------
 
package com.httpabcdefapp1123.timetablenew.vollyrequest;

/** * Created on 10/5/2015. */
public interface Helper {
    public void backResponse(String response);
}










-------------------JSONParser class-----------------------------------


package com.httpabcdefapp1123.timetablenew.vollyrequest;

import android.content.Context;
import android.util.Log;

import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.httpabcdefapp1123.timetablenew.AppController;
import com.httpabcdefapp1123.timetablenew.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null, response;
    static String json = "";
    private Context cx;

    // constructor    public JSONParser(Context cx) {
        this.cx = cx;
    }



    // function get json from url    // by making HTTP POST or GET mehtod

    public static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;

    }

    public void parseVollyJSONObject(String url, int method, final JSONObject param, final Helper h) {
        //method GET=0,POST=1       /* String perameters; 
 if (param == null) {            perameters = null;
else {            perameters = param.toString();        }*/ 
 if (method == 0 || method == 1) {
            final JsonObjectRequest jsObjRequest = new JsonObjectRequest
                    (method, url, param, new Response.Listener<JSONObject>() {

                        @Override                        public void onResponse(JSONObject response) {
                            //Log.e("Response: ", response.toString()); 
 if (response != null) {
                                h.backResponse(response.toString());

                            } else {
                                M.E("Something went wrong.!");
                            }
                        }

                    }, new Response.ErrorListener() {

                        @Override                        public void onErrorResponse(VolleyError error) {
                            String err = (error.getMessage() == null) ? "Parse Fail" : error.getMessage();
                            h.backResponse("error");
                            Log.e("sdcard-err2:", err);
                            M.E("Something went wrong.!");
                        }
                    }) {
                @Override                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
            };

            jsObjRequest.setShouldCache(true);
            // Adding request to request queue 
 AppController.getInstance().
                    addToRequestQueue(jsObjRequest);
        } else {
            M.E("Invalid Request Method");
        }
    }

    public void parseVollyStringRequest(String url, int method, final Map<String, String> params, final Helper h) {
        //method GET=0,POST=1        if (NetworkUtil.getConnectivityStatus(cx)) {
            if (method == 0 || method == 1) {
                final MaterialDialog materialDialog = M.initProgressDialog(cx);
                final StringRequest jsObjRequest = new StringRequest
                        (method, url, new Response.Listener<String>() {
                            @Override 
 public void onResponse(String response) {
                                //M.E("Response: " + response.toString()); 
 if (response != null) {
                                    materialDialog.dismiss();
                                    h.backResponse(response.toString());
                                } else {
                                    M.E("Invalid Request Method");
                                }
                            }
                        }, new Response.ErrorListener() {

                            @Override 
 public void onErrorResponse(VolleyError error) {
                                String err = (error.getMessage() == null) ? "Parse Fail" : error.getMessage();
                                materialDialog.dismiss();
                                h.backResponse("error");
                                M.E("sdcard-err2:" + err);
                                M.E("Something went wrong.!");
                            }
                        }) {
                    @Override 
 protected Map<String, String> getParams() throws AuthFailureError {


                        //returning parameters                        return params;
                    }
                };
                // Adding request to request queue 
 AppController.getInstance().addToRequestQueue(jsObjRequest);


            } else {
                M.E("Invalid Request Method");
            }
        } else {
            M.T(cx, cx.getString(R.string.no_internet));
        }
    }

public void parseVollyStringRequestWithautProgressBar(String url, int method, final Map<String, String> params, final Helper h) {
        //method GET=0,POST=1        if (NetworkUtil.getConnectivityStatus(cx)) {
            if (method == 0 || method == 1) {
//                final MaterialDialog materialDialog=M.initProgressDialog(cx); 
 final StringRequest jsObjRequest = new StringRequest
                        (method, url, new Response.Listener<String>() {
                            @Override                            public void onResponse(String response) {
                                //M.E("Response: " + response.toString()); 
 if (response != null) {
//                                    materialDialog.dismiss(); 
 h.backResponse(response.toString());
                                } else {
                                    M.E("Invalid Request Method");
                                }
                            }
                        }, new Response.ErrorListener() {

                            @Override 
 public void onErrorResponse(VolleyError error) {
      String err = (error.getMessage() == null) ? "Parse Fail" : error.getMessage();
//                  materialDialog.dismiss(); 
 h.backResponse("error");
                M.E("sdcard-err2:" + err);
               M.E("Something went wrong.!");
                            }
                        }) {
                    @Override 
 protected Map<String, String> getParams() throws AuthFailureError {















                        //returning parameters 
 return params;
                    }
                };
                // Adding request to request queue 
 AppController.getInstance().addToRequestQueue(jsObjRequest);


            } else {
                M.E("Invalid Request Method");
            }
        } else {
            M.T(cx, cx.getString(R.string.no_internet));
        }
    }
}




--------------------------------------M class---------------------------------



package com.httpabcdefapp1123.timetablenew.vollyrequest;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;

/** * Created by Sohel on 9/17/2015. */public class M {
    public static void I(Context cx, Class<?> startActivity, Bundle data) {
        Intent i = new Intent(cx, startActivity);
        if (data != null)
            i.putExtras(data);
        cx.startActivity(i);
    }

    public static void E(String msg) {
        Log.e("Log.E By Sohel ", msg);
    }


    public static void T(Context c, String msg) {
        Toast.makeText(c, msg, Toast.LENGTH_SHORT).show();
    }



    public static MaterialDialog initProgressDialog(Context c) {
        return new MaterialDialog.Builder(c)
                .title("Please wait...")
                .autoDismiss(false)
                .content("Wait for a moment.")
                .progress(true, 0)
                .show();
    }

    public static void share(Context c, String subject, String shareBody) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
        c.startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }
}

 ----------------------NETWORKUtil CLASS----------------------------
package com.httpabcdefapp1123.timetablenew.vollyrequest;

/** * Created by CRUD Technology on 8/22/2015. */
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;

public class NetworkUtil {

   public static Boolean getConnectivityStatus(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connectivityManager.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    return true;
                }
            }
        } else {
            if (connectivityManager != null) {
                //noinspection deprecation                NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                if (info != null) {
                    for (NetworkInfo anInfo : info) {
                        if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}





-------------LIBERY(GRADLE)--------------
android {
    compileSdkVersion 26    buildToolsVersion "26.0.1"    defaultConfig {
        applicationId "com.example.meenakshi.shareprefeferenceexample"        minSdkVersion 15        targetSdkVersion 26        versionCode 1        versionName "1.0"        multiDexEnabled true        vectorDrawables.useSupportLibrary = true        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }



compile 'com.android.support:appcompat-v7:25.3.1'compile 'com.android.support:design:25.3.1'compile 'com.jakewharton:butterknife:8.5.1'compile 'com.wdullaer:materialdatetimepicker:3.1.3'compile 'com.android.support:cardview-v7:25.3.1'compile 'de.hdodenhof:circleimageview:2.1.0'compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'testCompile 'junit:junit:4.12'compile 'com.daimajia.slider:library:1.1.5@aar'compile 'com.nineoldandroids:library:2.4.0'compile 'com.squareup.picasso:picasso:2.5.2'annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'compile 'com.afollestad.material-dialogs:core:0.9.0.1'compile 'com.mcxiaoke.volley:library-aar:1.0.0'compile 'com.google.code.gson:gson:2.3.1'compile 'com.google.firebase:firebase-messaging:9.6.0'compile 'com.wang.avi:library:2.1.3'compile 'com.google.android.gms:play-services:9.6.0'compile 'com.android.support:multidex:1.0.1'compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'/*compile ('com.thomashaertel:multispinner:0.1.0@aar')*/compile 'com.squareup.picasso:picasso:2.5.2'
 



-----------please remember to add Appcontroller---------
<application    android:name=".AppController"    android:allowBackup="true"    android:icon="@mipmap/ic_launcher"    android:label="@string/app_name"    android:supportsRtl="true"    android:theme="@style/AppTheme">
 

 
 /////Thanks to Sohel Khan(Sir) for this Code.///////////
 


 

1 comment:

AutoComplete Address (Updated)

-------------------------------------Activity---------------------------------- package placeautocomplete.iteritory.com; import androi...