在ListView中更改图像(使用简单适配器)

时间:2016-03-09 21:24:09

标签: android listview adapter

我正在关注this链接中的教程,以创建包含数据库数据的列表视图。它由一张图片(默认情况下 - 关闭灯泡)和两个文本组成 - 数据库记录的名称(房间)和状态(开/关)。在从数据库加载数据的AsyncTask结束时,我希望扫描列表,并将状态等于“1”的每个位置的图片更改为打开灯泡。

但图像不会改变。好像列表视图不令人耳目一新。

我们将不胜感激。

public class LightingActivity extends ListActivity {

private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray status = null;
ArrayList<HashMap<String, String>> statusList;

private static String address_getall = "http://192.168.2.112/db_lighting_getall.php";
private static String address_update = "http://192.168.2.112/db_lighting_change.php";

private static final String SID_SUCCESS = "success";
private static final String SID_ARRAY = "Lighting";
private static final String SID_ID = "light_id";
private static final String SID_NAME = "name";
private static final String SID_STATUS = "value";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.lighting_activity);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    statusList = new ArrayList<HashMap<String, String>>();

    new LoadData().execute();

    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // ...Listener...
        }
    });
}

class LoadData extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LightingActivity.this);
        pDialog.setMessage("Downloading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(address_getall, "GET", params);

        try {
            int success = json.getInt(SID_SUCCESS);
            if (success == 1) {
                status = json.getJSONArray(SID_ARRAY);
                for (int i = 0; i < status.length(); i++) {
                    JSONObject data = status.getJSONObject(i);
                    String light_id = data.getString(SID_ID);
                    String light_name = data.getString(SID_NAME);
                    String light_status = data.getString(SID_STATUS);

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(SID_ID, light_id);
                    map.put(SID_NAME, light_name);
                    map.put(SID_STATUS, light_status);

                    statusList.add(map);
                }
            } else {
                // Error
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        LightingActivity.this, statusList,
                        R.layout.lighting_list, new String[]{SID_ID, SID_STATUS, SID_NAME},
                        new int[]{R.id.light_id, R.id.light_status, R.id.light_name});
                setListAdapter(adapter);

                // I tried doing it like this:
                ListView lv = getListView();
                for (int i = 0; i < lv.getCount(); i++) {
                View v = lv.getAdapter().getView(i, null, null);
                TextView light_status = (TextView) v.findViewById(R.id.light_status);
                String status = light_status.getText().toString();
                if (status.equals("1")) {
                // Everything works till here - I checked with Toasts
                    ImageView img = (ImageView) v.findViewById(R.id.light_icon);
                    img.setImageResource(R.drawable.light_on);
                    lv.invalidateViews();
                    lv.refreshDrawableState();
                }
                }
            }
        });
    }
}

请宽容,我是java的新手:)

1 个答案:

答案 0 :(得分:0)

您的代码中存在许多错误,以至于它无法保存!我建议你谷歌关于如何使用AsyncTask将数据加载到ListView。有很多例子。快速搜索可以满足您的需求。

http://android-er.blogspot.gr/2010/07/load-listview-in-background-asynctask.html

只需几点指示

1) onPostExecute, onProgressUpdate and onPreExceute of AsyncTask are executed 
   in the UI thread so the runOnUiThread(new Runnable() {}) is not necessary.
   Only the doInBackground method is executed in another thread;

2) Put all the logic about what each rows shows like inside the getView method 
   of the adapter.

3) To update the views of a listView you change the data in the ArrayList and then 
   call  notifyDataSetChanged() on the ListView 's adapter. This causes all of the views 
   to be re-drawn. And because all the logic is in the getView method your views 
   are showing what the data contains.