将图像从url添加到简单列表适配器(json)

时间:2014-01-13 17:33:42

标签: android json listview

我有这样的代码:

public class ListaPrzepisow  extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> recipesList;

// url to get all recipes list
private static String url_all_recipes = "http://web.onlyway.pl/wolowinkadb/get_all_recipes.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_recipeS = "recipes";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_AUTOR= "autor";
private static final String TAG_FOTKA= "zdjecie";

// recipes JSONArray
JSONArray recipes = null;

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

    // Hashmap for ListView
    recipesList = new ArrayList<HashMap<String, String>>();

    // Loading recipes in Background Thread
    new LoadAllrecipes().execute();

    // Get listview
    ListView lv = getListView();  

    // on seleting single recipe
    // launching Edit recipe 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(),
                    EditrecipeActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

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

        }


    });
    */

}

// Response from Edit recipe Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted recipe
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all recipe by making HTTP Request
 * */
class LoadAllrecipes extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ListaPrzepisow.this);
        pDialog.setMessage("Loading recipes. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All recipes from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_recipes, "GET", params);

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

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

            if (success == 1) {
                // recipes found
                // Getting Array of recipes
                recipes = json.getJSONArray(TAG_recipeS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String autor = c.getString(TAG_AUTOR);
                    String fotka = c.getString(TAG_FOTKA);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_AUTOR, autor);
                    map.put(TAG_FOTKA, fotka);

                    // adding HashList to ArrayList
                    recipesList.add(map);
                }
            } else {
                // no recipes found
                // Launch Add New recipe Activity
                Intent i = new Intent(getApplicationContext(),
                        ListaPrzepisow.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all recipes
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        ListaPrzepisow.this, recipesList,
                        R.layout.recipeslist_layout, new String[] { TAG_PID,
                                TAG_NAME, TAG_AUTOR, TAG_FOTKA},
                        new int[] { R.id.pid, R.id.name, R.id.Author, R.id.Thumb });
                // updating listview
                setListAdapter(adapter); 

            }
        });

    }

}
}

在String fotka = c.getString(TAG_FOTKA);我有想要成像的网址。我究竟能把它放到我的图像视图中。例如,使用此lib:https://github.com/koush/UrlImageViewHelper

我尝试了许多方式,但我已经卡住了

1 个答案:

答案 0 :(得分:1)

好的,我帮助了自己。我添加了我的扩展SimpleAdapter的适配器,如下所示:

package com.app.beefmania;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

public class MyAdapter extends SimpleAdapter {

public MyAdapter(Context context, List<? extends Map<String, ?>> data,
        int resource, String[] from, int[] to) {
    super(context, data, resource, from, to);
    // TODO Auto-generated constructor stub
}
@Override
public void setViewImage(ImageView v, String value) {
    UrlImageViewHelper.setUrlDrawable(v, value);   
}

}

所有工作都依赖于我的优势代码;)