如何制作接收数据的模型类

时间:2016-04-05 12:08:28

标签: android performance android-layout listview android-fragments

我如何将这些数据接收到Model类中我想创建一个像getter setter这样的模型类,并使用来自getter setter的数据。

  

我想制作Model类   基本上我把它存储到不在单独的类中的变量中,所以我想创建模型类

>这是我的代码

 class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
      /*  dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);*/
        Toast.makeText(getApplicationContext(), "fetch data from server", Toast.LENGTH_LONG).show();

    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            //------------------>>

            HttpGet httpGet = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);


                JSONArray jsonarray = new JSONArray(data);

                latLngList.clear();
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject obj = jsonarray.getJSONObject(i);

                    longitudeServer = obj.getString("longi");
                    latitudeServer = obj.getString("lati");
                    uniqueidSserver = obj.getString("uniqueid");

                    LatLng latLng = new LatLng(Double.parseDouble(latitudeServer), Double.parseDouble(longitudeServer));
                    latLngList.add(latLng);

                }


                return true;

            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;


    }

    protected void onPostExecute(Boolean result) {

        Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();

        if (result == false) {
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }
        try {

            if (marker != null) {
                mMap.clear();
                Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();

            }
            for (LatLng object : latLngList)

                marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));

            System.out.println(marker.getPosition() + "  Marker position.......");
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
            // mMap.clear();
        }

    }

2 个答案:

答案 0 :(得分:1)

首先将您想要的模型定义到一个类中,例如一个构造函数allwing从JSONObject创建一个新实例

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
    class MyServer {

        private String longitudeServer;
        private String latitudeServer;
        private String uniqueidSserver;

        public MyServer(JSONObject obj){
            try{
                longitudeServer = obj.getString("longi");
                latitudeServer = obj.getString("lati");
                uniqueidSserver = obj.getString("uniqueid");
            }catch(JSONException jse){
                e.printStackTrace();
            }
        }

        public String getLongitude(){
            return longitudeServer;
        }

        public void setLongitude(String longitudeServer){
            this.longitudeServer = longitudeServer;
        }

        //... More setter and getter here
    }
    // ... The existing code of your async task here
}

完成此操作后,您可以实现新的MyServer并使用其getter / setter

    for (int i = 0; i < jsonarray.length(); i++) {
        JSONObject obj = jsonarray.getJSONObject(i);
        MyServer s = new MyServer(obj); // Create your server from the JSONObject 
        LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
        latLngList.add(latLng);

    }

答案 1 :(得分:1)

虽然@Guillaume的回答是正确的,但我想建议一种更好更快的方法。您可以使用第三方库LoganSquare分别对JSON进行序列化和解析。您只需要注释模型并使用LoganSquare类来解析数据。

在你的情况下,它将是这样的:(密切关注类名和字段上方的注释)

@JsonObject
public class MyServer {

  @JsonField(name = "longi")
  public String longitudeServer;

  @JsonField(name = "lati")
  public String latitudeServer;

  @JsonField(name = "uniqueid")
  public String uniqueidSserver;

  public MyServer(){
  // blank constructor is required
  }
}

现在使用LoganSquare静态类来解析从服务器收到的json响应:

for (int i = 0; i < jsonarray.length(); i++) {
    MyServer s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), MyServer.class);

    LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
    latLngList.add(latLng);

}