从Android读取JSON文件

时间:2017-07-13 13:37:08

标签: android json

我尝试从我的应用程序中读取JSON文件,但是当我运行它时显示空白页面。 如果有人知道原因只是告诉我。提前致谢

适配器

    public class QuestionsActivity extends ArrayAdapter<quizzes> {

    protected quizzes[] quizzesList;
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater flat = LayoutInflater.from(getContext());
        View customView = flat.inflate(R.layout.activity_questions, parent, false);
        quizzes q=quizzesList[position];
        TextView title=(TextView)customView.findViewById(R.id.title);

        title.setText(q.title);

        return convertView;
    }

    QuestionsActivity(Context context, quizzes[] lst) {
        super(context, R.layout.activity_questions, lst);
        this.quizzesList=lst;}
    @Override
    public quizzes getItem(int position) {
        return quizzesList[position];
    }
}

主要

    public class Quiz extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        AsyncTask<Void, Void, String> async = new AsyncTask<Void, Void, String>()
        {
            @Override
            protected String doInBackground(Void... params) {
                try{
                    return getData();
                }catch (IOException e){
                    e.printStackTrace();
                }
                return "";
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);
            }

            @Override
            protected void onPostExecute(final String s)
            {
                try {
                    final JSONArray jsonArray=new JSONArray(s);
                    final quizzes[] q=new quizzes[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        String title=jsonObject.getString("title");
                        quizzes Quizzes =new quizzes(title);
                        q[i]=Quizzes;
                    }

                    final ListAdapter quizz_adapter=new QuestionsActivity(getApplicationContext(),q);
                    final ListView listView =(ListView) findViewById(R.id.list1);
                    listView.setAdapter(quizz_adapter);
                    Log.w("","");

                }catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.w("received data",s);
                super.onPostExecute(s);
            }
        };

        async.execute();

    }


    private String getData() throws IOException {
        URL url = new URL("http://quizz.pl/v28/api/quizs?limit=10&offset=0&order=FILL");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        int resCode = urlConnection.getResponseCode();
        String s = "";
        try {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = br.readLine()) != null) {
                s = s + line;
            }
        } finally {

            urlConnection.disconnect();
            return s;
        }
    }
}

JSON文件的启动程序属性

public class quizzes {

    String title;

    public quizzes( String title)
    {
        this.title=title;
    }

}

3 个答案:

答案 0 :(得分:0)

Ahmed El-elaimy!

我怀疑您在将数据设置到适配器后忘记拨打quizz_adapter.notifyDataSetChanged()

祝你好运!

答案 1 :(得分:0)

通过运行代码,在final JSONArray jsonArray=new JSONArray(s)之后抛出异常,这是因为您的Web服务不返回和数组,而是在属性quizs内部的对象是一个数组。

为了避免在解析Json字符串时遇到问题,我建议您使用the Gson library,这会消除很多工作

在提出问题之前,请尝试调试代码并阅读logcats

答案 2 :(得分:0)

我认为问题在于您如何使用 inpustream bufferedReader 对象。

这里有一个解决您问题的方法:

public static String getData(String urlp) throws JSONException {
            InputStreamReader in = null;
            StringBuilder sb = new StringBuilder();
            HttpURLConnection conn = null;

            try {
                URL url = new URL(urlp);
                conn = (HttpURLConnection)url.openConnection();

                if (conn != null && conn.getInputStream() != null) {
                    in = new InputStreamReader(conn.getInputStream(),
                            Charset.defaultCharset()
                            /*FROM JAVA DOC
                             Charset
 Description

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set 
ISO-8859-1   ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 
UTF-8 Eight-bit UCS Transformation Format 
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order 
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order 
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark 
*/);
                    BufferedReader bufferedReader = new BufferedReader(in);
                    if (bufferedReader != null) {
                        int i;
                        while ((i = bufferedReader.read()) != -1) {
                            sb.append((char) i);
                        }
                        bufferedReader.close();
                    }
                }

            in.close();
            } catch (Exception e) {
                //..dosomething
            } 

            return sb.toString();   
    }

在您的AsyncTask中或您需要的任何地方:

String url = "http://quizz.pl/v28/api/quizs?limit=10&offset=0&order=FILL";
JSONObject jsonbject = new JSONObject(getData(url));
JSONArray jsonarray = jsonbject.getJSONArray("quizs");

enter image description here

相关问题