使用 JSON 使用未弃用的方法将 MySQL 数据加载到 ListView

Loading MySQL data into ListView using JSON using non-deprecated methods

我需要将 mysql 数据库中的数据显示到 Android 应用程序的列表视图中。我在网上找到了一个教程,但有一些方法已被弃用(例如 HttpPost、HttpResponse、HttpClient 等)。我怎样才能找到替代方法?我要显示数据的这个Activity也是一个片段

这是我的代码:

public class PastOrders extends Fragment {

    Activity context;

    HttpPost httppost;

    StringBuffer buffer;

    HttpResponse response;

    HttpClient httpclient;

    ProgressDialog pd;

    CustomerAdapter adapter;

    ListView listProduct;

    ArrayList<SingleOrder> records;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.past_orders, container, false);

        context = this;

        records = new ArrayList<SingleOrder>();

        listProduct=(ListView)v.findViewById(R.id.listView1);

        adapter=new CustomerAdapter(context, R.layout.list_order,R.id.pro_name,records);

        listProduct.setAdapter(adapter);

        return v;
    }

    public void onStart(){

        super.onStart();

        //execute background task

        BackTask bt=new BackTask();

        bt.execute();

    }

    private class BackTask extends AsyncTask<Void,Void,Void>{

        protected void onPreExecute(){

            super.onPreExecute();

            pd = new ProgressDialog(context);

            pd.setTitle("Retrieving data");

            pd.setMessage("Please wait.");

            pd.setCancelable(true);

            pd.setIndeterminate(true);

            pd.show();

        }

        protected Void doInBackground(Void...params){

            InputStream is=null;

            String result="";

            try{

                httpclient=new DefaultHttpClient();

                httppost= new HttpPost("https://www.foodlebee.com/BeeTrack/orders.php");

                response=httpclient.execute(httppost);

                HttpEntity entity = response.getEntity();

                // Get our response as a String.

                is = entity.getContent();

            }catch(Exception e){

                if(pd!=null)

                    pd.dismiss(); //close the dialog if error occurs

                Log.e("ERROR", e.getMessage());

            }

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

                result=sb.toString();

            }catch(Exception e){

                Log.e("ERROR", "Error converting result "+e.toString());

            }

            try{
                result=result.substring(result.indexOf("["));

                JSONArray jArray =new JSONArray(result);

                for(int i=0;i<jArray.length();i++){

                    JSONObject json_data =jArray.getJSONObject(i);

                    SingleOrder p=new SingleOrder();

                    p.setpName(json_data.getString("pname"));

                    p.setuPrice(json_data.getInt("uprice"));

                    records.add(p);

                }

            }

            catch(Exception e){

                Log.e("ERROR", "Error pasting data "+e.toString());

            }

            return null;

        }

        protected void onPostExecute(Void result){

            if(pd!=null) pd.dismiss(); //close dialog

            Log.e("size", records.size() + "");

            adapter.notifyDataSetChanged(); //notify the ListView to get new records

        }

    }

}

这是我的 CustomAdapter class,用于向 ListView 提供数据:

public class CustomAdapter extends ArrayAdapter<SingleOrder> {

    int groupid;

    ArrayList<SingleOrder> records;

    Context context;


    public CustomAdapter(Context context, int vg, int id, ArrayList<SingleOrder>
            records) {

        super(context, vg, id, records);

        this.context = context;

        groupid = vg;

        this.records = records;

    }

    public View getView(int position, View convertView, ViewGroup parent) {


        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(groupid, parent, false);

        TextView textName = (TextView) itemView.findViewById(R.id.pro_name);

        textName.setText(records.get(position).getpName());

        TextView textPrice = (TextView) itemView.findViewById(R.id.pro_uprice);

        textPrice.setText(records.get(position).getuPrice() + "$");


        return itemView;

    }

}

这是我的单笔订单class:

public class SingleOrder {

    private String pName;

    private int uPrice;

    public void setpName(String pName){this.pName=pName;}

    public void setuPrice(int uPrice){this.uPrice=uPrice;}

    public String getpName(){return pName;}

    public int getuPrice(){return uPrice;}

}

我在以下方面遇到错误:

context = this; 

我应该使用 "context = getActivity();" 吗?

在以下几行中,我使用了已弃用的方法:

            httpclient=new DefaultHttpClient();

            httppost= new HttpPost("https://www.example.com/orders.php");

            response=httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();

            is = entity.getContent();

我是否也应该在最后一行中使用 getActivity()

相反,您可以使用 Android API 本身提供的 class。

String path, response;
URL url;
HttpURLConnection conn;
int responseCode;
try
{
    response = "";
    //path is the URL to connect with
    path = "http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10"
    url = new URL(path);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Connection", "close");
    conn.setConnectTimeout(15000);
    conn.connect();
    responseCode = conn.getResponseCode();
    Log.d("App Name", "Result Code: " + responseCode);
    if (responseCode == HttpsURLConnection.HTTP_OK) 
    {
        String line = "";
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is), 65535);
        Log.d("Output", br.toString());
        while ((line = br.readLine()) != null) 
        {
            response += line;
            Log.d("output lines", line);
        }
        is.close();
        br.close();
    } 
    else 
    {
        conn.disconnect();
        response = "";
    }
} 
catch (UnsupportedEncodingException | ProtocolException | MalformedURLException | IOException e) 
{
    Log.d("App Name",""+e.printStackTrace());
} 
finally 
{
    Log.d("App Name"," Connection disconnected..");
    conn.disconnect();
}

参考 API : https://developer.android.com/reference/java/net/HttpURLConnection.html

解释:https://developer.android.com/training/basics/network-ops/connecting.html