简体   繁体   中英

Android CustomAdapter on ListView displaying images

I am parsing a JSON file from url and successfully taking TrackName, ArtistName,ImageUrl information. I can display them successfully on a SimpleAdapter.

Then i am trying to download images from ImageUrl and i save them on a HashMap<String,Object> contentslists

The problem is when i need to display the images on my ListView. I created a CustomAdapter but i am in trouble how to HashMapping and displaying the images on ListView.

PlaylistActivity.java:

package com.example.andreaskonstantakos.akazooa1;

import android.content.Intent;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class PlaylistActivity extends AppCompatActivity {

private String TAG = PlaylistActivity.class.getSimpleName();
private ListView lv;

String PlaylistId;
//TextView tv ;
ArrayList<HashMap<String, Object>> ContentsList;
Bitmap[] mThumbIds;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_playlist);

    ContentsList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list1);

    new GetSongs().execute();
}

private class GetSongs extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        init();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
        Toast.makeText(PlaylistActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String url = "http://akazoo.com/services/Test/TestMobileService.svc/playlist?playlistid="+PlaylistId;

        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array of a JSON object
                JSONObject Results = jsonObj.getJSONObject("Result");
                JSONArray Items = Results.getJSONArray("Items");

                //mThumbIds =new Bitmap[Items.length()];

                // looping through All songs
                for (int i = 0; i < Items.length(); i++) {

                        JSONObject c = Items.getJSONObject(i);


                        String TrackName = c.getString("TrackName");
                        String ArtistName = c.getString("ArtistName");
                        String ImageUrl = c.getString("ImageUrl");


                        // mThumbIds[i]= getBitmapFromURL(ImageUrl);

                        // tmp hash map
                        HashMap<String,Object> contentslists = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contentslists.put("TrackName", TrackName);
                        contentslists.put("ArtistName", ArtistName);
                        contentslists.put("Image",getBitmapFromURL(ImageUrl));


                        // adding contents to contents list
                        ContentsList.add(contentslists);


                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });

            }

        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG).show();
                }
            });
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        CustomAdapter adapter = new CustomAdapter(PlaylistActivity.this, ContentsList,
                R.layout.list_item, new String[]{ "TrackName","ArtistName","Image"},
                new int[]{R.id.Name, R.id.ItemCount, R.id.Image});
        lv.setAdapter(adapter);

    }
}

public void init() {

    Intent intent=getIntent();
    PlaylistId = intent.getStringExtra("PlaylistId");

    //tv = (TextView)findViewById(R.id.PlaylistIdTv);
   // tv.setText(PlaylistId);
}

public void onclickBack(View view){

    Intent intent = new Intent(PlaylistActivity.this, MainActivity.class);

    startActivity(intent);
    finish();

}

//Mobile phone back button
public void onBackPressed()  {

    Intent intent = new Intent(PlaylistActivity.this, MainActivity.class);

    startActivity(intent);
    finish();

}

public Bitmap getBitmapFromURL(String src) {
    try {
        java.net.URL url = new java.net.URL(src);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
}

CustomAdapter.java:`

package com.example.andreaskonstantakos.akazooa1;

import android.content.Context;
import android.graphics.Bitmap;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Andreas Konstantakos on 1/6/2017.
 */

public class CustomAdapter extends SimpleAdapter {


/**
 * Constructor
 *
 * @param context  The context where the View associated with this SimpleAdapter is running
 * @param data     A List of Maps. Each entry in the List corresponds to one row in the list. The
 *                 Maps contain the data for each row, and should include all the entries specified in
 *                 "from"
 * @param resource Resource identifier of a view layout that defines the views for this list
 *                 item. The layout file should include at least those named views defined in "to"
 * @param from     A list of column names that will be added to the Map associated with each
 *                 item.
 * @param to       The views that should display column in the "from" parameter. These should all be
 *                 TextViews. The first N views in this list are given the values of the first N columns
 */
public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
    super(context, data, resource, from, to);
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View v =  super.getView(position, convertView, parent);
    HashMap<String, Object> hm = (HashMap<String, Object>) super.getItem(position);
    ImageView image = (ImageView) v.findViewById(R.id.Image);
    TextView txt1 = (TextView) v.findViewById(R.id.TrackName);
    TextView txt2 = (TextView) v.findViewById(R.id.ArtistName);



    image.setImageBitmap((Bitmap) hm.get("Image"));
    txt1.setText(hm.get("TrackName").toString());
    txt2.setText(hm.get("ArtistName").toString());



    return v;

}
}

`

Any solution?

Instead of HashMap<String, Object> I would recommend to use ArrayList<CustomObject> . In CustomObject you can store TrackName , ArtistName , ImageUrl . Later, you can access the desired object by using getView()'s position parameter. See this link for a better approach: http://www.journaldev.com/10416/android-listview-with-custom-adapter-example-tutorial . For displaying the image I recommend Glide or Universal Image Loader or any other image managers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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