Android在Listview中显示JSONArray,包含来自API(网站)的数据

时间:2015-12-28 11:40:53

标签: android json api listview

我是Android的新手,并且有一个任务集可以显示来自API的Genres列表 我不知道发生了什么。我成功地使用硬编码数据实现了正常的列表视图。但现在我需要使用REST服务并连接到网络并在列表视图中显示数据。

我的XML非常基础,只是一个listview

<?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, “姓名”: “操作”},{ “ID”:12, “姓名”: “冒险”},{ “ID”:16,“名称“:” 动画 “},{” ID “:35,” 姓名 “:” 喜剧 “},{” ID “:80,” 姓名 “:” 犯罪 “},{” ID “:99,” 姓名“: “纪录片”},{ “ID”:18, “姓名”: “戏剧”},{ “ID”:10751, “姓名”: “家庭”},{ “ID”:14, “名称”:“幻想“},{” ID “:10769,” 名 “:” 外国 “},{” ID “:36,” 名 “:” 历史记录 “},{” ID “:27,” 名 “:” 恐怖“} { “ID”:10402, “名”: “音乐”},{ “ID”:9648, “名”: “神秘”},{ “ID”:10749, “名”: “浪漫”},{ “id”:878,“name”:“Science Fiction”},{“id”:10770,“name”:“TV Movie”},{“id”:53,“name”:“Thriller”},{ “ID”:10752, “姓名”: “战争”},{ “ID”:37, “姓名”: “西方”}]}

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

2 个答案:

答案 0 :(得分:1)

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

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

记得抓住异常。

答案 1 :(得分:0)

完整的教程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"
} 

enter image description here

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的用法和完整代码,请参见源链接