2016-05-04 9 views
0

Androidアプリケーションのリストビューにmysqlデータベースのデータを表示する必要があります。私はチュートリアルをオンラインで見つけましたが、HttpPost、HttpResponse、HttpClientなどのいくつかのメソッドは廃止されました。代わりの方法を見つけるにはどうしたらいいですか?私がデータを表示したいこのアクティビティも断片です。非推奨のメソッドを使用してJSONを使用してListViewにMySQLデータをロード

ここに私のコードです:

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クラスです:

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; 

    } 

} 

そして、これは私のSingleOrderクラスです:

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()を使用することになっているだろうか?

答えて

1

代わりに、Android API自体が提供するクラスを使用できます。

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

関連する問題