【问题标题】:Android display JSONArray in Listview with data from API (website)Android 在 Listview 中显示 JSONArray 以及来自 API(网站)的数据
【发布时间】:2015-12-28 11:40:53
【问题描述】:

我对 Android 非常陌生,并且有一个任务集来显示来自 API 的流派列表 我不知道发生了什么。我成功地实现了一个带有硬编码数据的普通列表视图。但现在我需要使用 REST 服务并连接到网络并在列表视图中显示数据。

我的 XML 很基础,只是一个列表视图

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
    <ListView
       android:id="@+id/lstView"
       android:layout_height="wrap_content"
       android:layout_width="match_parent">
    </ListView>
</LinearLayout>

在那之后,我有我的课。我目前有两 (2) 个错误。首先是尝试将 API 返回的字符串放入 JSONArray。第二个刚刚决定发生,通过说符号 R 无法解决。不知道这是怎么发生的。

无论如何,这是我的代码:

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

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

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


public class Genre extends Activity {
    ListView listView;
    private static final String DEBUG_TAG = "HttpExample";

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

        listView = (ListView) findViewById(R.id.lstView);

       ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        String result=null;
      try {
             result = downloadUrl();
        }catch(IOException e)
        {}

        ArrayList<String> lstData = new ArrayList<String>();
        JSONArray jarray = (JSONObject)result; //ERROR HERE
        try {
            if (jarray != null) {
                for (int i = 0; i < jarray.length(); i++) {
                    lstData.add(jarray.get(i).toString());
                }
            }
        }catch(JSONException j)
        {}

       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, lstData);

       listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                int itemPosition = position;

                String itemValue = (String) listView.getItemAtPosition(position);

                Toast.makeText(getApplicationContext(), "Position :" + itemPosition + " ListItem :" + itemValue, Toast.LENGTH_LONG).show();
            }
        });
    }

    private String downloadUrl() throws IOException{
        InputStream is = null;

        int len = 500;

        try{
            URL url = new URL("website here");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG,"The response is: " + response);
            is = conn.getInputStream();
            String contentAsString = readIt(is, len);
            return contentAsString;
        }finally{
            if(is != null){
                is.close();
            }
        }
    }

    public String readIt(InputStream stream, int len) throws IOException{
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }
}

我已经评论了给我错误的部分。 R 符号虽然是另一回事。如果我能让应用程序成功返回并转换 JSONArray,那就太好了。

我已经复制并粘贴了来自各个网站和 StackOverflow 本身的大部分(如果不是全部)代码,以寻找答案。

我得到的 JSON 数据:

{"流派":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name ":"动画"},{"id":35,"name":"喜剧"},{"id":80,"name":"犯罪"},{"id":99,"name": "纪录片"},{"id":18,"name":"戏剧"},{"id":10751,"name":"家庭"},{"id":14,"name":"奇幻"},{"id":10769,"name":"Foreign"},{"id":36,"name":"History"},{"id":27,"name":"Horror"} ,{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{ "id":878,"name":"科幻小说"},{"id":10770,"name":"电视电影"},{"id":53,"name":"Thriller"},{ "id":10752,"name":"War"},{"id":37,"name":"Western"}]}

我现在想显示名称,但我可以同时显示 ID 和名称。 帮助将不胜感激。谢谢 另外,如果您需要更多数据,请发表评论

【问题讨论】:

  • 仅列表视图中的名称?
  • JSONArray jarray = (JSONObject)result; //ERROR HERE,真的吗?
  • 如何将 json 结果类型转换为 jsonobject,然后将其分配给 jsonarray
  • JSON 使用 Retrofit2 示例 freakyjolly.com/…

标签: android json api listview


【解决方案1】:

你的结果是一个 Json 字符串,所以你需要像这样获取 JSONArray:

JSONObject obj = new JSONObject(result);
JSONArray jarray = obj.getJSONArray("genres");

记得捕捉异常。

【讨论】:

  • 仍然有错误 cannot cast java.lang.String to org.json.JSONArray
【解决方案2】:

完整教程https://www.freakyjolly.com/create-multiple-columns-listview-from-json-data-using-retrofit2-in-android-example/

使用 JSON

的示例
{
  "results": [
    {
      "phone": "+9178XXXX66",
      "name": "Olivia"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Isla"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Emily"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Amelia"
    },
    {
      "phone": "+9178XXXX66",
      "name": "Sophia"
    }],
  "statusCode": "1",
  "count": "2"
} 

activity_main.xml

<ListView
    android:id="@+id/listShowJSONData"
    android:layout_width="368dp"
    android:layout_height="398dp"
    android:layout_margin="10dp"
    android:layout_marginTop="8dp"
    android:padding="10dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView"
    tools:layout_editor_absoluteX="8dp" />

json_data_list.xml

<TextView
    android:id="@+id/userDetails"
    android:layout_width="95dp"
    android:layout_height="match_parent"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:layout_weight="1"
    android:text="TextView"
    android:textColor="#000000"
    android:textIsSelectable="true" />

<TextView
    android:id="@+id/userStatus"
    android:layout_width="83dp"
    android:layout_height="match_parent"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:layout_weight="1"
    android:text="TextView"
    android:textColor="#000000" />

现在自定义BaseAdapter (CustomListAdapter)

...
...
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    if(view==null)
    {
        view= LayoutInflater.from(c).inflate(R.layout.json_data_list,viewGroup,false);
    }

    TextView mUserDetails = (TextView) view.findViewById(R.id.userDetails);
    TextView mUserStatus = (TextView) view.findViewById(R.id.userStatus);


    Object getrow = this.users.get(i);
    LinkedTreeMap<Object,Object> rowmap = (LinkedTreeMap) getrow;
    String name = rowmap.get("name").toString();
    String phone = rowmap.get("phone").toString();

    mUserDetails.setText(name);
    mUserStatus.setText(phone);

    return view;
}
...
...

RetroFit2 用法和完整代码见源链接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多