简体   繁体   中英

I am hitting one service . I am not getting listing of JSON data while in log cat it is showing all the data is coming

I am hitting one service . I am not getting listing of JSON data while in log cat it is showing all the data is coming .

I am using post service to set param values . In the log cat i am getting all the data . but i want when i click on the Leads button it should be come json data which is coming in logcat . I am pasting Json data ,logcat ,image and code for same.

I am stuck with this Any one please help why i am not getting json data .

You can see in the image when i am clicking on Leads button then i am getting error in toast .

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import tatahousingleads.com.tatahousingleads.app.AppController;
public class MainActivity extends Activity {
    // json array response url
    private String urlJsonArry = "http://tatahousing.in/UtilityApp/report/filter-leads.php";
    private static String TAG = MainActivity.class.getSimpleName();
    private Button btnMakeObjectRequest, btnMakeArrayRequest;
    // Progress dialog
    private ProgressDialog pDialog;
    private TextView txtResponse;
    // temporary string to show the parsed response
    private String jsonResponse;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // btnMakeObjectRequest = (Button) findViewById(R.id.btnObjRequest);
        btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
        txtResponse = (TextView) findViewById(R.id.txtResponse);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // making json array request
                makeJsonArrayRequest();
                new SendDeviceID().execute();
            }
        });
    }


    private class SendDeviceID extends AsyncTask<String, String, String>
    {
        String res;

        InputStream inputStream = null;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... params)
        {

            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            param.add(new BasicNameValuePair("search_type","bookings"));

          //  param.add(new BasicNameValuePair("leads","leads"));


            try {

                try {
                    // Set up HTTP post

                    // HttpClient is more then less deprecated. Need to change to URLConnection
                    HttpClient httpClient = new DefaultHttpClient();

                    HttpPost httpPost = new HttpPost(urlJsonArry);

                    httpPost.setEntity(new UrlEncodedFormEntity(param));

                    System.out.println(" PARAM " + param);

                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    HttpEntity httpEntity = httpResponse.getEntity();

                    // Read content & Log
                    inputStream = httpEntity.getContent();
                } catch (UnsupportedEncodingException e1) {
                    Log.e("Unsupported Exception", e1.toString());
                    e1.printStackTrace();
                } catch (ClientProtocolException e2) {
                    Log.e("ClientProtocolException", e2.toString());
                    e2.printStackTrace();
                } catch (IllegalStateException e3) {
                    Log.e("IllegalStateException", e3.toString());
                    e3.printStackTrace();
                } catch (IOException e4) {
                    Log.e("IOException", e4.toString());
                    e4.printStackTrace();
                }
                // Convert response to string using String Builder
                try {
                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
                    StringBuilder sBuilder = new StringBuilder();

                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sBuilder.append(line + "\n");
                    }

                    inputStream.close();
                    res = sBuilder.toString();


                } catch (Exception e) {
                    Log.e("String/BufferReader", "Error converting" + e.toString());
                }

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

            }

            return res;
        }

        @Override
        protected void onPostExecute(String s)
        {
            super.onPostExecute(s);

            if(s != null)
            {
                if(!s.equals(""))
                {
                    System.out.println(" Leads:  " + s);

                }
            }
        }
    }


    private void makeJsonArrayRequest() {
        showpDialog();
        JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        try {
                            // Parsing json array response
                            // loop through each json object
                            jsonResponse = "";
                            for (int i = 0; i < response.length(); i++) {
                                JSONObject leads = (JSONObject) response
                                       .get(i);
                                String id = leads.getString("bookings");

}
                           txtResponse.setText(jsonResponse);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                        hidepDialog();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                hidepDialog();
            }
        });
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(req);
    }
    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }
    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

Appcontroller.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 AppController extends Application {

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

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

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

    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);
        }
    }
}

activity_main.xml

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    android:scrollbarStyle="insideInset"
    android:scrollbars="vertical" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <Button
        android:id="@+id/btnArrayRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:text="Leads"
       />
    <TextView
        android:id="@+id/txtResponse"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnArrayRequest"
        android:layout_marginTop="20px"
        android:padding="20dp" />
</LinearLayout>
    </ScrollView>

logcat

I/System.out:  Leads:  {"success":"true","total":4,"bookings":[{"refno":"ARI1003631","name":"Lalat Shekhar Samal","email":"lalat.sekhar11@gmail.com","address":"Bhubaneswar","city":"Bhubaneswar","state":"Odisha","country":"India","nationality":"Indian","panno":"DWFPS4677G","passportno":"","contactno":"+91 7787825750","unittype":"AC 2 BHK Small 1099 sqft","project":"Ariana","trn_amount":"","dateofbirth":"16-05-1988","trn_transactionid":"","platform":"UtilityApp-Android","success":""},{"refno":"ARI1003642","name":"Sekhar","email":"lalat.sekhar11@gmail.com","address":"Kolkata","city":"Kolkata","state":"Westbengal","country":"India","nationality":"Indian","panno":"DWDAH5455G","passportno":"","contactno":"+91 7787825750","unittype":"1 BHK Small 657 sqft","project":"Ariana","trn_amount":"","dateofbirth":"16-05-1988","trn_transactionid":"","platform":"UtilityApp-Android","success":""},{"refno":"ARAGUR1003649","name":"Vikramjit Roy","email":"email@vikramjietroy.com","address":"C-251, Florence Marvel\r\nSushant Lok 3, Sector 57","city":"Gurgaon","state":"Haryana","country":"India","nationality":"Indian","panno":"ADCPR5412J","passportno":"","contactno":"+91 8800993333","unittype":"Plot (538 Sq. Yd.)","project":"Arabella","trn_amount":"50000.00","dateofbirth":"01-12-1970","trn_transactionid":"FAM24305385638","platform":"UtilityApp-IOS","success":"Success"},{"refno":"GOA1004116","name":"DrPragati Sinha","email":"drpragatisinha@yahoo.co.in","address":"DHARHARA HOUSE.BANK ROAD.","city":"PATNA","state":"Bihar","country":"India","nationality":"Indian","panno":"AKPPS1958E","passportno":"","contactno":"+91 9835020007","unittype":"2 BHK","project":"Rivage","trn_amount":"30000.00","dateofbirth":"27-10-1951","trn_transactionid":"GHMP4548172054","platform":"UtilityIphoneApp-Booking","success":"PGS10001-Success"}]}
06-17 14:59:18.601 25789-25789/tatahousingleads.com.tatahousingleads D/Volley: [1] 3.onErrorResponse: MainActivity

Json data

  {
        "success": "true",
        "total": 4,
        "bookings": [{
            "refno": "ARI1003631",
            "name": "Lalat Shekhar Samal",
            "email": "lalat.sekhar11@gmail.com",
            "address": "Bhubaneswar",
            "city": "Bhubaneswar",
            "state": "Odisha",
            "country": "India",
            "nationality": "Indian",
            "panno": "DWFPS4677G",
            "passportno": "",
            "contactno": "+91 7787825750",
            "unittype": "AC 2 BHK Small 1099 sqft",
            "project": "Ariana",
            "trn_amount": "",
            "dateofbirth": "16-05-1988",
            "trn_transactionid": "",
            "platform": "UtilityApp-Android",
            "success": ""
        }, {
            "refno": "ARI1003642",
            "name": "Sekhar",
            "email": "lalat.sekhar11@gmail.com",
            "address": "Kolkata",
            "city": "Kolkata",
            "state": "Westbengal",
            "country": "India",
            "nationality": "Indian",
            "panno": "DWDAH5455G",
            "passportno": "",
            "contactno": "+91 7787825750",
            "unittype": "1 BHK Small 657 sqft",
            "project": "Ariana",
            "trn_amount": "",
            "dateofbirth": "16-05-1988",
            "trn_transactionid": "",
            "platform": "UtilityApp-Android",
            "success": ""
        }, {
            "refno": "ARAGUR1003649",
            "name": "Vikramjit Roy",
            "email": "email@vikramjietroy.com",
            "address": "C-251, Florence Marvel\r\nSushant Lok 3, Sector 57",
            "city": "Gurgaon",
            "state": "Haryana",
            "country": "India",
            "nationality": "Indian",
            "panno": "ADCPR5412J",
            "passportno": "",
            "contactno": "+91 8800993333",
            "unittype": "Plot (538 Sq. Yd.)",
            "project": "Arabella",
            "trn_amount": "50000.00",
            "dateofbirth": "01-12-1970",
            "trn_transactionid": "FAM24305385638",
            "platform": "UtilityApp-IOS",
            "success": "Success"
        }, {
            "refno": "GOA1004116",
            "name": "DrPragati Sinha",
            "email": "drpragatisinha@yahoo.co.in",
            "address": "DHARHARA HOUSE.BANK ROAD.",
            "city": "PATNA",
            "state": "Bihar",
            "country": "India",
            "nationality": "Indian",
            "panno": "AKPPS1958E",
            "passportno": "",
            "contactno": "+91 9835020007",
            "unittype": "2 BHK",
            "project": "Rivage",
            "trn_amount": "30000.00",
            "dateofbirth": "27-10-1951",
            "trn_transactionid": "GHMP4548172054",
            "platform": "UtilityIphoneApp-Booking",
            "success": "PGS10001-Success"
        }]
}][1]][1]

图片

You have make JSONObject Request Instead Of JsonArray Request.

  JsonObjectRequest req = new JsonObjectRequest (urlJsonArry,
                new Response.Listener<JSONObject>() 

The problem is that you are making a JSONArray Request,instead of an JsonObjectRequest that should be the correct implementation.

Also I recommend you to use Gson to parse Json, makes it easier to parse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM