【问题标题】:Loading image in ListView from Array ID Android从数组 ID Android 在 ListView 中加载图像
【发布时间】:2014-01-10 21:22:03
【问题描述】:

我目前有一个 ListAdapter 设置,它通过 JSON 传递从 MYSQL 数据库中提取的信息。我正在尝试根据产品的 ID 显示存储在可绘制文件夹中的图像。例如,对于产品 1,R.drawable.img1 显示在等等..

public class GetProducts extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSON jParser = new JSON();
Functions uf = new Functions();

ArrayList<HashMap<String, Object>> productsList;

// url to get all products list
private static String url_all_products = "http://jumpto.be/api/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_IMGURL = "image";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, Object>>();
    new GetProductsFromDB().execute();
    // Loading products in Background Thread


    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    /*lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    OrderBuild.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });*/

}



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


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(GetProducts.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }


    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url_all_products, params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String ImgUrl = c.getString(TAG_PID);

                    // creating new HashMap
                    HashMap<String, Object> map = new HashMap<String, Object>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    String imageLink = "R.drawable.img"+id;
                    map.put(TAG_IMGURL, imageLink);

                    // adding HashList to ArrayList
                    productsList.add(map); 
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }


    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {



                ListAdapter adapter = new SimpleAdapter(
                        GetProducts.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_IMGURL},
                        new int[] { R.id.pid, R.id.name, R.id.img });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

我刚刚告诉我它找不到目录的当前代码。我查看了 URI,但不知道如何在数组 / for 循环中运行它们。

非常感谢

【问题讨论】:

    标签: android mysql json listadapter


    【解决方案1】:

    R.drawable.img1实际上只是你自动生成的R.java文件中定义的一个int值,所以不能直接使用。

    但是,您可以使用以下方法检索您的可绘制对象:

    Resources resources = getResources();
    int resId = resources.getIdentifier("img" + id, "drawable", getPackageName());
    Drawable myDrawable = resources.getDrawable(resId);
    

    或者,您可以将图像文件放在assets 目录中,然后使用文件名从那里加载它们。

    InputStream inputStream = getAssets().open("img" + id + ".jpg");
    Drawable drawable = Drawable.createFromStream(inputStream, null);
    mImageView.setImageDrawable(drawable);
    

    【讨论】:

    • 感谢您的回答,如何将其分配给 ListAdapter?是不是通过Map.put
    【解决方案2】:

    您可以在 hashmap 中为 drawable 设置 int 值。在列表适配器中很容易绑定。

    int imageLink = R.drawable.img1; map.put(TAG_IMGURL, imageLink);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2021-03-30
      • 1970-01-01
      相关资源
      最近更新 更多