android学习历程,自定义listview并从服务器端获取数据填充进listview

来源:互联网 发布:快速排序算法最坏情况 编辑:程序博客网 时间:2024/05/16 12:55

首先我们添加一个listview控件

//jqhuoqu.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".jqhuoqu">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="getservice"        android:id="@+id/getservice"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true" />    <ListView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/listView"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:layout_below="@+id/getservice"/></RelativeLayout>

这里只写了一个button,单击button时获取相关数据,填充进listview。
然后新建一个listview_item.xml文件用于自定义listview的样式。

//listview_item.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <ImageView        android:id="@+id/people"        android:layout_width="100dp"        android:layout_height="100dp"        android:layout_margin="10dp" />    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:orientation="vertical" >        <TextView            android:id="@+id/name"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="10dp"            android:layout_marginTop="10dp"            android:text="TextView" />        <TextView            android:id="@+id/time"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="10dp"            android:text="TextView"            />        <TextView            android:id="@+id/introduce"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="10dp"            android:layout_marginTop="10dp"            android:text="TextView" />    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:orientation="vertical" >    </LinearLayout></LinearLayout>

下面在主Activity里定义相关方法,这里注意我们需要在AndroidManifest.xml里加入如下语句允许程序联网通信。
<uses-permission android:name="android.permission.INTERNET" />

//jqhuoqu.javaimport android.annotation.TargetApi;import android.os.Build;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.ListView;import android.widget.SimpleAdapter;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.ParseException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;public class jqhuoqu extends ActionBarActivity {    private ListView listView = null;    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();    private SimpleAdapter simpleAdapter = null;    //消息部分    private static final int MSG_CODE = 1001;//定义存放数据库信息的变量,这里假设数据不超过100条    int a;    int ct_pid[] = new int[100];    int ct_cid[] = new int[100];    String[] ct_jobname = new String[100];    String[] ct_duty = new String[100];    String[] ct_requirements = new String[100];    String[] ct_keyword = new String[100];    String[] ct_salary = new String[100];    String[] ct_degree = new String[100];    String[] ct_experience = new String[100];    String[] ct_dateline = new String[100];    String[] ct_mail = new String[100];    String[] ct_school = new String[100];    String[] ct_workplace = new String[100];    private Handler mHandler = new Handler()    {        @Override        public void handleMessage(Message msg)        {            //接收并处理消息            if(msg.what == MSG_CODE)            {             //UI更新            initView();            }        }    };//初始化listview    private void initView() {        listView = (ListView) super.findViewById(R.id.listView);        settingAdapter();        listView.setAdapter(simpleAdapter);        simpleAdapter.notifyDataSetChanged();    }//重写Adapter    private void settingAdapter() {        list.clear();        //清空Adapter中的数据;        initList();        // map中的key        String from[] = new String[] { "people", "name","time", "introduce" };        // 模板中的组件id        int to[] = new int[] { R.id.people, R.id.name,R.id.time, R.id.introduce };        simpleAdapter = new SimpleAdapter(this, list, R.layout.listview_item,                from, to);    }//还不清楚如何从数据库获取图片,此处图片写在本地    private void initList() {        // 显示的图片资源        int[] res = new int[] { R.drawable.maaa,R.drawable.mao,                R.drawable.maoa, R.drawable.maoaa, R.drawable.maoaaa,R.drawable.maaa,                R.drawable.maoa,R.drawable.maaa,R.drawable.mao,                R.drawable.maoa, R.drawable.maoaa, R.drawable.maoaaa,R.drawable.maaa,                R.drawable.maoa,R.drawable.maaa,R.drawable.mao,                R.drawable.maoa, R.drawable.maoaa, R.drawable.maoaaa,R.drawable.maaa,                R.drawable.maoa,        };        for (int j = 0; j < a; j++) {            HashMap<String, Object> map = new HashMap<String, Object>();            System.out.println(j);            map.put("people", res[j]);            map.put("name", ct_jobname[j]);            map.put("time",ct_dateline[j]);            map.put("introduce", "我们需要有"+ct_experience[j]+"工作经验的人。"+"在"+ct_workplace[j]+"工作,"+"月薪"+ct_salary[j]+"。");            list.add(map);        }        //因为需要将数据库中的最新数据显示在最上端,利用这句话将数据倒序排列填充进listview;         Collections.reverse(list);    }    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_jqhuoqu);        findViewById(R.id.getservice).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                ArrayList nameValuePairs = new ArrayList();                //主线程中不能进行网络通信此处但开启子线程获取数据                (new Thread() {                    @TargetApi(Build.VERSION_CODES.KITKAT)                    @Override                    public void run() {                        JSONArray jArray;                        String result = null;                        InputStream is = null;                        StringBuilder sb = null;                        //获取数据                        try {                            HttpClient httpclient = new DefaultHttpClient();                            HttpGet httpget = new HttpGet("此处写服务器接口链接");                            HttpResponse response = httpclient.execute(httpget);                            HttpEntity entity = response.getEntity();                            is = entity.getContent();                            System.out.println("获取成功");                        } catch (Exception e) {                            Log.e("log_tag", "Error:" + e.toString());                        }                        //将获取数据转成字符串                        try {                            BufferedReader reader = new BufferedReader(                                    new InputStreamReader(is, "iso-8859-1"), 8);                            sb = new StringBuilder();                            sb.append(reader.readLine() + "\n");                            String line = "0";                            while ((line = reader.readLine()) != null) {                                sb.append(line + "\n");                            }                            is.close();                            result = sb.toString();                            System.out.println("转字符串成功");                        } catch (Exception e) {                            Log.e("log_tag", "Error converting result " + e.toString());                        }                        //将字符串输出                        try {                            jArray = new JSONArray(result);                            JSONObject json_data = null;                            a=jArray.length();                            for ( int i = 0; i < jArray.length(); i++) {                                json_data = jArray.getJSONObject(i);                                ct_pid[i] = json_data.getInt("PID");                                ct_cid[i] = json_data.getInt("CID");                                ct_jobname[i] = json_data.getString("JOBNAME");                                ct_duty[i] = json_data.getString("DUTY");                                ct_requirements[i] = json_data.getString("REQUIREMENTS");                                ct_keyword[i]=json_data.getString("KEYWORD");                                ct_salary[i]=json_data.getString("SALARY");                                ct_degree[i]=json_data.getString("DEGREE");                                ct_experience[i]=json_data.getString("EXPERIENCE");                                ct_dateline[i]=json_data.getString("DATELINE");                                ct_mail[i]=json_data.getString("MAIL");                                ct_school[i]=json_data.getString("SCHOOL");                                ct_workplace[i]=json_data.getString("WORKPLACE");                            }                        } catch (JSONException e1) {                            // Toast.makeText(getBaseContext(), "No City Found"                            // ,Toast.LENGTH_LONG).show();                        } catch (ParseException e1) {                            e1.printStackTrace();                        }//因为子线程中不允许修改UI,所以利用消息机制发送信息通知主线程更新UI                        Message msg = mHandler.obtainMessage(MSG_CODE);                        msg.sendToTarget();                    }                }//                ).start();            }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_jqhuoqu, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}
1 0
原创粉丝点击