简体   繁体   English

Android中的多列自定义ListView

[英]Multi-Column Custom ListView in Android

I've problem with adding rows dynamically to a two column custom ListView. 我在将行动态添加到两列自定义ListView时遇到问题。 The AsyncTask fetches the data correctly from web service but rows are not added to ListView. AsyncTask从Web服务正确获取数据,但行未添加到ListView。 The add_to_list() procedure is bing called and it is displaying the parameters but ListView is not getting updated. 调用了add_to_list()过程,它正在显示参数,但ListView没有得到更新。 Please guide me what's wrong with the code. 请指导我代码有什么问题。

1) mail_row.xml 1)mail_row.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/cell_borders"
    android:orientation="horizontal"
    android:paddingBottom="1dip"
    android:paddingTop="1dip"
    android:weightSum="4"
    tools:ignore="HardcodedText" >    
    <TextView
        android:id="@+id/msgTime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"        
        android:gravity="center"
        android:layout_weight="1.5"
        android:text="Time" />    
    <TextView
        android:id="@+id/msgText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"        
        android:gravity="center"      
        android:layout_weight="2.5"  
        android:text="Message" />    
</LinearLayout>

2) mail_box.xml 2)mail_box.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp"
    tools:ignore="HardcodedText" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        tools:ignore="UselessParent" >
        <Button
            android:id="@+id/bBack_Mail"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Back"
            tools:ignore="HardcodedText" />
    </LinearLayout>
    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:background="@android:color/darker_gray" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/cell_borders"
        android:orientation="horizontal"
        android:paddingBottom="1dip"
        android:paddingTop="1dip"
        android:weightSum="4"
        tools:ignore="HardcodedText" >
        <TextView
            android:id="@+id/tvTime_Mail"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:gravity="center"
            android:text="Time" />
        <TextView
            android:id="@+id/tvText_Mail"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2.5"
            android:gravity="center"
            android:text="Message" />
    </LinearLayout>
    <View
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:background="@android:color/darker_gray" />
    <ListView
        android:id="@+id/lstMail_Mail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>

3) Mail_Box.java 3)Mail_Box.java

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Mail_Box extends Activity implements View.OnClickListener {

    private ListView list;
    private ArrayList<HashMap<String, String>> mylist;
    private HashMap<String, String> map;
    private String url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //Here is a valid URL
    private String urlSearch = null;
    private Button bBack;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mail_box);
        this.initializer();
        SimpleAdapter mSchedule = new SimpleAdapter(this, mylist,
                R.layout.mail_row,
                new String[] { "mail_time", "mail_message" }, new int[] {
                        R.id.tvTime_Mail, R.id.tvText_Mail });
        list.setAdapter(mSchedule);

        this.urlSearch = this.url + "rashid";
        MyTask runner = new MyTask();
        runner.execute(this.url);

    }

    private void initializer() {
        bBack = (Button) findViewById(R.id.bBack_Mail);
        bBack.setOnClickListener(this);
        list = (ListView) findViewById(R.id.lstMail_Mail);
        mylist = new ArrayList<HashMap<String, String>>();

    }

    @Override
    public void onClick(View v) {
        finish();
    }

    private void add_to_list(String tm, String msg) {
        //This message is shown properly
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
        try {
        map = null;
        map = new HashMap<String, String>();
        map.put("mail_time", tm);
        map.put("mail_message", msg);
        mylist.add(map);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
        }
    }

    // --------------AsyncTask Class--------------------------------
    private class MyTask extends AsyncTask<String, Void, String> {
        private String msg = "";
        private JSONParser jParser;
        private JSONObject json;
        private static final String TAG_DATA = "data";
        private static final String TAG_TIME = "MAIL_TIME";
        private static final String TAG_TYPE = "TYPE";
        private static final String TAG_TEXT = "MSG_TEXT";

        private JSONArray data = null;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog = ProgressDialog.show(Mail_Box.this,
                    "Loading Mails", "Please wait for a while.", true);
        }

        @Override
        protected String doInBackground(String... urls) {
            try {
                this.jParser = new JSONParser();
                this.json = jParser.getJSONFromUrl(urls[0]);
                if (this.json != null)
                    msg = "DONE";
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Response: ", this.msg);
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            progressDialog.dismiss();
            if (msg.equals("DONE")) {
                try {
                    data = json.getJSONArray(TAG_DATA);
                    int i = data.length();
                    if (i == 0) {
                        Toast.makeText(getApplicationContext(),
                                "No record  found.", Toast.LENGTH_SHORT).show();
                    } else {
                        for (int j = 0; j < i; j++) {
                            JSONObject c = data.getJSONObject(j);
                            String tm = c.getString(TAG_TIME);
                            String type = c.getString(TAG_TYPE);
                            String txt = c.getString(TAG_TEXT);
                            add_to_list(tm, txt);
                        }
                    }

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Error",
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getApplicationContext(),
                        "Unable to search record.", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

You have to call adapter.notifyDataSetChanged() when you are dynamically loading the data just make adapter a global variable and change your add_to_list() method to 在动态加载数据时,必须调用adapter.notifyDataSetChanged()只是将适配器设为全局变量,然后将add_to_list()方法更改为

   private void add_to_list(String tm, String msg) {
    //This message is shown properly
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
       try {
           map = null;
           map = new HashMap<String, String>();
           map.put("mail_time", tm);
           map.put("mail_message", msg);
           mylist.add(map);
           adapter.notifyDataSetChanged()
       } catch (Exception e) {
           Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
       }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM