我打了一个服务。我没有获得JSON数据列表,而在log cat中它显示所有数据即将到来

时间:2016-06-17 09:49:45

标签: android json http-post

我正在点击一项服务。我没有获得JSON数据列表,而在log cat中它显示所有数据即将到来。

我正在使用post service来设置param值。在log cat中我得到了所有数据。但我希望当我点击Leads按钮时,它应该是来自logcat的json数据。我正在粘贴Json数据,logcat,图像和代码。

我坚持这个任何人请帮助我为什么我没有得到json数据。

当我点击Leads按钮时,您可以在图像中看到我在吐司中收到错误。

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数据

  {
        "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]

image

2 个答案:

答案 0 :(得分:0)

您已经制作了JSONObject请求而不是JsonArray请求。

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

答案 1 :(得分:0)

问题是你正在制作一个JSONArray请求,而不是一个应该是正确实现的JsonObjectRequest。

我还建议您使用Gson解析Json,使其更容易解析。