android - 如何在ListView中显示带有列的对象数组android?

标签 android listview httpurlconnection

我开发混合 Android 应用程序,现在正在学习原生 Android。我想在原生 android 中创建一个简单的表格 View 。现在在 ionic 中我这样做。

JS

$scope.get_users = function(){
   $http.post('192.168.0.132/api/get_users', {is_active:true})
     .success(function(data){
         $scope.users = data;
     }.error(function(Error_message){
         alert(Error_message)
     }
}

HTML

<table>
    <thead>
        <tr>
           <th>Name</th>
           <th>Role</th>
        </tr>
    <tbody>
        <tr ng-repeat="user in users">
          <td ng-bind="::user.name"></td>
          <td ng-bind="::user.role"></td>
          <td><button ng-click="select_user(user)"></td>
        </tr>
     </tbody>
</table>

简单吧?一切都已就绪。

现在在 android 中这是我的代码。

public void get_users(){
    HttpURLConnection urlConnection;
    int length = 5000;

    try {
       // Prepare http post
       URL url = new URL("http://192.168.0.132/api/get_users");
       urlConnection = (HttpURLConnection) url.openConnection();
       urlConnection.setRequestProperty("Authorization", "");
       urlConnection.setRequestMethod("POST");
       urlConnection.setDoInput(true);
       urlConnection.setDoOutput(true);
       urlConnection.setUseCaches(false);
       urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

       // initiate http post call
       urlConnection.connect();

       // Get input stream
       InputStream is = urlConnection.getInputStream();

       // Convert Stream to String
       String contentAsString = convertInputStreamToString(is, length);

       // Initialize Array 
       JSONArray jObj = new JSONArray(contentAsString);
       int length = jObj.length();
       List<String> listContents = new ArrayList<String>(length);

       // Convert JSON Array to 
       for(int i=0; i<jObj.length(); i++){
           listContents.add(jObj.getString(i).toString());
       }

       // Set the array to listview adapter and set adapter to list view
       ListView myListView = (ListView) findViewById(R.id.listView2);
       ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listContents);
       myListView.setAdapter(arrayAdapter);

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

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

我怎样才能做得更简单,就像有列的表格一样?谢谢!

最佳答案

在我的主要 Activity 中,我有如下静态响应

   package com.example.listcolumn;

import static com.example.listcolumn.Constant.FIRST_COLUMN;
import static com.example.listcolumn.Constant.SECOND_COLUMN;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {
    private ArrayList<HashMap> list;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView lview = (ListView) findViewById(R.id.listview);
        populateList();
        listviewAdapter adapter = new listviewAdapter(this, list);
        lview.setAdapter(adapter);
    }

    private void populateList() {

        list = new ArrayList<HashMap>();

        HashMap temp = new HashMap();
        temp.put(FIRST_COLUMN, "Karthik");
        temp.put(SECOND_COLUMN, "Developer");
        list.add(temp);

        HashMap temp1 = new HashMap();
        temp1.put(FIRST_COLUMN, "Hello");
        temp1.put(SECOND_COLUMN, "Developer");
        list.add(temp1);

        HashMap temp2 = new HashMap();
        temp2.put(FIRST_COLUMN, "We r fr u");
        temp2.put(SECOND_COLUMN, "Deeveloper");
        list.add(temp2);

        HashMap temp3 = new HashMap();
        temp3.put(FIRST_COLUMN, "Hoffensoft");
        temp3.put(SECOND_COLUMN, "Company");
        list.add(temp3);

    }
}

通过使用适配器设置值

   package com.example.listcolumn;

import static com.example.listcolumn.Constant.FIRST_COLUMN;
import static com.example.listcolumn.Constant.FOURTH_COLUMN;
import static com.example.listcolumn.Constant.SECOND_COLUMN;
import static com.example.listcolumn.Constant.THIRD_COLUMN;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class listviewAdapter extends BaseAdapter {
    public ArrayList<HashMap> list;
    Activity activity;

    public listviewAdapter(Activity activity, ArrayList<HashMap> list) {
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    private class ViewHolder {
        TextView txtFirst;
        TextView txtSecond;
        TextView txtThird;
        TextView txtFourth;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        // TODO Auto-generated method stub
        ViewHolder holder;
        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.activity_main, null);
            holder = new ViewHolder();
            holder.txtFirst = (TextView) convertView.findViewById(R.id.FirstText);
            holder.txtSecond = (TextView) convertView.findViewById(R.id.SecondText);
            holder.txtThird = (TextView) convertView.findViewById(R.id.ThirdText);
            holder.txtFourth = (TextView) convertView.findViewById(R.id.FourthText);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        HashMap map = list.get(position);
        holder.txtFirst.setText((CharSequence) map.get(FIRST_COLUMN));
        holder.txtSecond.setText((CharSequence) map.get(SECOND_COLUMN));
        holder.txtThird.setText((CharSequence) map.get(THIRD_COLUMN));
        holder.txtFourth.setText((CharSequence) map.get(FOURTH_COLUMN));

        return convertView;
    }

}

嗨,我已经使用适配器完成了,完整的教程可以在这里获取 ListView with multiple columns

关于android - 如何在ListView中显示带有列的对象数组android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39911607/

相关文章:

Android:MapView 仅显示灰色网格,错误为 "Couldn' t get connection factory client”

android - 将项目添加到数据源不会出现在 ListView 中

android - Json 不返回其中的属性

Java将xml属性放在HTTP请求的 "request version"部分

java - 如何android单元测试和模拟静态方法

java - Android 纹理映射 - PNG 文件的映射不正确

c# - ListView 中的项目没有行缩进

java - 谷歌应用引擎 (Java) : URL Fetch Response too large problems

java - 我已经为 POST 方法提供了正确的参数和 header ,但响应代码是 400

java - 通知监听器服务 UI 更新