Android ListView使用Json解析数据

时间:2017-04-09 05:15:00

标签: android json listview

在这里,我正在分享我的代码如何在列表视图中解析这些数据。首先,我现在使用Json Parser这无法正常工作。现在我正在解析这个,所以我们看不到列表视图。请帮助我谢谢。

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;


public class HomeScreen extends Activity {

    ListView listview;
    String url;
    ArrayList<ParticipantItem> participantArrayList;
    ParticipantsAdapter pAdapter;
    JSONArray jsonOuterArray;
    private ProgressDialog pDialog;
    ImageView menu, refresh;
    Integer a;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_screen);
        participantArrayList = new ArrayList<ParticipantItem>();
        listview = (ListView) findViewById(R.id.listview);

        url = "http://findcourse.net/search_result.php?search=&study_field=17";//"http://findcourse.net/search_result.php?search=" + keywordvalue_get + sf_spinner_get + sl_spinner_get + si_spinner_get + sm_spinner_get;
        refresh = (ImageView) findViewById(R.id.refresh);
        menu = (ImageView) findViewById(R.id.menu);

        new GetData().execute();
        System.out.println("The square root of " + url);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

            }
        });


    }

    //////////////////////
    private class GetData extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(HomeScreen.this);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();


            if (jsonOuterArray.length() > 0) {
                for (int i = 0; i <= jsonOuterArray.length(); i++) {
                    a = jsonOuterArray.length();

                    JSONObject jsonObj;
                    try {
                        jsonObj = jsonOuterArray.getJSONObject(i);

                        JSONObject message = jsonObj.getJSONObject("result");
                        String offered_by_detail = message.getString("offered_by");

                        String course = message.getString("course");
                        String logo = message.getString("logo");
                        String total_views = message.getString("total_views");
                        String total_course_offered = message.getString("total_course_offered");
                        String feature_course = message.getString("feature_course");
                        String total_views_course = message.getString("total_views_course");
                        String course_info = message.getString("course_info");
                        String duration = message.getString("duration");
                        String tution_fee = message.getString("tution_fee");
                        String other_payable_fee = message.getString("other_payable_fee");
                        String intake = message.getString("intakesandroid");
                        String campus = message.getString("campusandroid");
                        String entry_requirement = message.getString("entry_requirement");
                        String longitude = message.getString("longitude");
                        String latitude = message.getString("latitude");
                        String search_filter = message.getString("search_filter");
                        String institute_info = message.getString("institute_info");
                        // Toast.makeText(HomeScreen.this, institute_info, Toast.LENGTH_SHORT).show();

                        TextView search_filtera = (TextView) findViewById(R.id.search_filter);

                        // search_filtera.setText("Search for " + String.valueOf(a) + " institutions offering in Agriculture courses");
                        search_filtera.setText(search_filter);


                        participantArrayList.add(new ParticipantItem(offered_by_detail, logo, course, total_views, course_info, duration, tution_fee, other_payable_fee, intake, campus, entry_requirement, longitude, latitude, search_filter, institute_info, total_course_offered, feature_course, total_views_course));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        pDialog.dismiss();
                    }
                }

            } else {

            }
            pAdapter = new ParticipantsAdapter(getApplicationContext(), participantArrayList);
            listview.setAdapter(pAdapter);

        }

        protected String doInBackground(final String... args) {
            HttpHandler sh = new HttpHandler();
            jsonOuterArray = new JSONArray();
            String jsonOuterArray = sh.makeServiceCall(url);
            return null;

        }
    }



}

2 个答案:

答案 0 :(得分:0)

错误可能是因为在doInBackground()中返回null。

使您的Json映射变得简单,将其添加到您的gradle文件

compile 'com.fasterxml.jackson.core:jackson-databind:2.3.2'

然后从Json

中检索对象列表
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        TypeReference<List<ParticipantItem>> mapType = new 
                       TypeReference<List<ParticipantItem>>() {};
        participantArrayList= objectMapper.readValue(jsonOuterArray,mapType) ;

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

答案 1 :(得分:0)

您的JsonArray长度为空,您需要从Asyntask中的响应中分配。请参阅下面的代码。

HttpManager:爪哇

 public class HttpManager {

public static String getResponse(RequestPackage p) {

    BufferedReader reader = null;
    String uri = p.getUri();

    //Managing GET request using appending parameter to the url
    if(p.getMethod().equals("GET")) {

        uri += "?" + p.getEncodedParams();
    }

    try {

        URL url = new URL(uri);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod(p.getMethod());

        //Managing POST request using OutPutStream
        if (p.getMethod().equals("POST")) {
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(p.getEncodedParams());
            writer.flush();
        }

        StringBuilder sb = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String line;
        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");

        }
        return sb.toString();
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            }
            catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
    }

}

}

RequestPackage.Java

public class RequestPackage {
private String uri;
private String method = "GET";
private Map<String,String> params = new HashMap<>();

public Map<String, Integer> getParamsInt() {
    return paramsInt;
}

public void setParamsInt(Map<String, Integer> paramsInt) {
    this.paramsInt = paramsInt;
}

private Map<String,Integer> paramsInt = new HashMap<>();

public String getUri() {
    return uri;
}

public void setUri(String uri) {
    this.uri = uri;
}

public String getMethod() {
    return method;
}

public void setMethod(String method) {
    this.method = method;
}

public Map<String, String> getParams() {
    return params;
}

public void setParams(Map<String, String> params) {
    this.params = params;
}

public void setParams(String key, String value) {
    params.put(key,value);
}


public String getEncodedParams() {
    StringBuilder sb = new StringBuilder();
    for(String key : params.keySet()) {
        String value = null;

        try{
            value = URLEncoder.encode(params.get(key),"UTF-8");
        }
        catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if(sb.length() > 0)
        {
            sb.append("&");
        }

        sb.append(key + "=" + value);
    }
    return sb.toString();
}

}

MainActivity.Java

public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
ArrayList<Result> participantArrayList;
ParticipantsAdapter pAdapter;
Integer a;
JSONArray jsonOuterArray=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //For GET request parameter pass through the url.
    RequestPackage regPackage = new RequestPackage();
    regPackage.setMethod("GET");
    regPackage.setUri("http://findcourse.net/search_result.php?search=&study_field=17");
    new webTask().execute(regPackage);
}

public class webTask extends AsyncTask<RequestPackage, String, String> {

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

        //You can also use progress dialog here
        Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(RequestPackage... requestPackages) {

        String content = HttpManager.getResponse(requestPackages[0]);
        return content;
    }

    @Override
    protected void onPostExecute(String result) {

        //Webserver will return response in a result variable.
        String response = result;
        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
        pDialog.dismiss();
        try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject item = (JSONObject) jsonArray.get(i);
                JSONObject message = item.getJSONObject("result");

                String offered_by_detail = message.getString("offered_by");

                String course = message.getString("course");
                String logo = message.getString("logo");
                String total_views = message.getString("total_views");
                String total_course_offered = message.getString("total_course_offered");
                Toast.makeText(MainActivity.this,
                        logo+ offered_by_detail + course, Toast.LENGTH_LONG).show();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        pDialog.dismiss();
        }

    }

}

}