如何使用JSON for android从网站接收数据?

时间:2018-06-01 20:55:39

标签: java android json

我为我的android应用程序创建了一个类,它使用json连接到mysql数据库。请注意,php代码getNews.php已经过测试,它会以正确的json格式响应所需的数据。请注意,我只想获得一个包含此类ArrayReceiver.java数据的数组...但它不起作用...任何人都可以检查代码。

ArrayReceiver.java

 package com.example.batoul.uptodate4;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ArrayReceiver extends AsyncTask<String, Integer, String> {
    List<Article> a=new ArrayList<Article>();
    String url="192.168.11.8/utd/getNews.php";

    Boolean error = false;
    private ProgressDialog pDialog;
    Boolean success = false;
    String msg = "";

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

    }

    public List<Article> getA() {
        return a;
    }

    @Override
    protected String doInBackground(String... arg) {
        publishProgress(2);
        //  agendaArrayList = new ArrayList<>();
        List<NameValuePair> params = new ArrayList<>();
        try {



            //        params.add(new BasicNameValuePair("notActivated", "false"));


            ServiceHandler serviceClient = new ServiceHandler();
            String json = serviceClient.makeServiceCall(url,
                    ServiceHandler.POST, params);

            //  Log.e("aaa ", "> " + ServiceHandler.url);
            //  Log.d("Create Response: ", "> " + json);

            if (json != null) {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    if (jsonObj != null) {
                        //int catObj22 = jsonObj.getInt("success");

                        //  if (catObj22 == 1) {
                        JSONArray titles = jsonObj.getJSONArray("title");


                        for (int i = 0; i < titles.length(); i++) {
                            String catObj = (String) titles.get(i);



                            Article obj = new Article(0,"");
                            obj.setTitle(catObj);


                            a.add(obj);

                        }

                        success = true;
                    } else {
                        success = false;
                    }
                    // }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                Log.e("JSON Data", "Didn't receive any data from server!");
            }
        } catch (Exception e) {
            error = true;
            return null;
        }
        Log.e("aaa ", " success");

        return "success";
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
//            if (pDialog.isShowing()) {
//                pDialog.dismiss();
//            }
        //    Toast.makeText(TravelsActivity.this, s, Toast.LENGTH_LONG).show();
        if (success) {

            //   for (int i = 0; i < travelsArr.size(); i++) {
            //     new getPic().execute("" + i);
            // }
            //ListAdapterClass adapter = new ListAdapterClass( ArticleArr,view.getContext());
            //SubjectListView.setAdapter(adapter);
        }


    }
}

ServiceHandler.java

package com.example.batoul.uptodate4;

import android.util.Log;

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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;

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

public class ServiceHandler {

    static InputStream is = null;
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    public static String url ,u;

    public ServiceHandler() {

    }
    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);

    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {

                    httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
                }
                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    this.url =url +"?" + paramString;
                }
                HttpGet httpGet = new HttpGet(this.url);


                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error: " + e.toString());
        }

        return response;

    }
}

getNews.php:

<?php
$response = array();
$db = mysqli_connect('localhost', 'root', '', 'utd1_db');
 $query = " SELECT * FROM `article`";// need change
$result = $db->query($query);
 if ($result->num_rows > 0) {
$title = array();
while ($row = $result->fetch_assoc()) {
            array_push($title, $row["title"]);// need change
 }
$response["success"] = 1;
$response["title"] = $title;
 echo json_encode($response);
} else {
 $response["success"] = 0;
$response["message"] = "Nothing found";
echo json_encode($response);
}
?>

0 个答案:

没有答案