narahari_arjun
narahari_arjun

Reputation: 643

how to display details of single item of list in another activity from url (json data)?

I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly. Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.

When i click on an item from the list i want to display the details of that item in another activity based on the track-id Url : https://itunes.apple.com/lookup?id=659234741

So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.

Need some help to figure out the problem

My Code :

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resultsList = new ArrayList<HashMap<String, String>>();
    lv = getListView();

    // Calling async task to get json
    new GetTunesDetails().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                tunes = jsonObj.getJSONArray(TAG_RESULT);

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

                    artworkImage = c.getString("artworkUrl100");
                    wrapperType = c.getString("wrapperType");
                    artistName = c.getString("artistName");
                    collectionName = c.getString("collectionName");
                    trackName = c.getString("trackName");
                    collectionPrice = c.getString("collectionPrice");
                    trackId = c.getString("trackId");

                    // tmp hashmap for single contact
                    HashMap<String, String> tunesMap = new HashMap<String, 
                    String>();

                    // adding each child node to HashMap key => value
                    // contact.put(TAG_ID, firstname);
                    tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
                    tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
                    tunesMap.put(TAG_ARTIST_NAME, artistName);
                    tunesMap.put(TAG_COLLECTION_NAME, collectionName);
                    tunesMap.put(TAG_TRACK_NAME, trackName);
                    tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
                    tunesMap.put(TAG_TRACK_ID, trackId);

                    // adding contact to contact list
                    resultsList.add(tunesMap);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this, resultsList);
        // Set the adapter to the ListView
        lv.setAdapter(adapter);

    }
}

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName, 
collectionPrice;
ImageView artworkImage;

public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> 
arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables

    // this.position = position;

    inflater = (LayoutInflater) 
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.custom_row, parent, false);
    // Get the position
    resultp = data.get(position);

    // Locate the TextViews in listview_item.xml
    wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
    artistName = (TextView) itemView.findViewById(R.id.artistName);
    collectionName = (TextView) itemView.findViewById(R.id.collectionName);
    trackName = (TextView) itemView.findViewById(R.id.trackName);
    collectionPrice = (TextView) 
    itemView.findViewById(R.id.collectionPrice);

    // Locate the ImageView in listview_item.xml
    artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);

    // Capture position and set results to the TextViews
    wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
    artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
    collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
    trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
    collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
    // Capture position and set results to the ImageView
    // Passes flag images URL into ImageLoader.class
    imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE), 
    artworkImage);
    // Capture ListView item click

    itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) { // TODO Auto-generated method
            Toast.makeText(context, "Clicked at position " + position, 
            Toast.LENGTH_LONG).show();
            Intent intent = new Intent(context, SingleTrack.class);
            intent.putExtra("track_image", 
            resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
            intent.putExtra("wrapper_type", 
            resultp.get(MainActivity.TAG_WRAPPER_TYPE));
            intent.putExtra("artistName", 
            resultp.get(MainActivity.TAG_ARTIST_NAME));
            intent.putExtra("collectionName", 
            resultp.get(MainActivity.TAG_COLLECTION_NAME));
            intent.putExtra("trackName", 
            resultp.get(MainActivity.TAG_TRACK_NAME));
            intent.putExtra("collectionPrice", 
            resultp.get(MainActivity.TAG_COLLECTION_PRICE));
            intent.putExtra("trackId", 
            resultp.get(MainActivity.TAG_TRACK_ID));
            context.startActivity(intent);
        }
    });

    return itemView;
}

SingleTrack.java : This is the class where i displaying the details on single item click

public class SingleTrack extends Activity {

// URL to get contacts JSON
private static String url = "";

// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";

// contacts JSONArray
JSONArray tracks = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;

ProgressDialog pDialog;

String passedData1, passedData2, passedData3, passedData4, passedData5, 
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText, 
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName, 
collectionPrice, trackId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_track);
    wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
    artistNameText = (TextView) findViewById(R.id.artistName1);
    collectionNameText = (TextView) findViewById(R.id.collectionName1);
    trackNameText = (TextView) findViewById(R.id.trackName1);
    collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
    trackImage = (ImageView) findViewById(R.id.artworkImage1);
    passedData1 = getIntent().getStringExtra("track_image");
    passedData2 = getIntent().getStringExtra("wrapper_type");
    passedData3 = getIntent().getStringExtra("artistName");
    passedData4 = getIntent().getStringExtra("collectionName");
    passedData5 = getIntent().getStringExtra("trackName");
    passedData6 = getIntent().getStringExtra("collectionPrice");
    passedData7 = getIntent().getStringExtra("trackId");
    singleTrackDetails = new ArrayList<HashMap<String, String>>();
    // url
    url = "https://itunes.apple.com/lookup?id=" + passedData7;
    // Calling async task to get json
    new GetSingleTrackDetails().execute();
}

class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
    private JSONObject jsonObj;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(SingleTrack.this);
        pDialog.setMessage("Loading Track Details...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... params) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                tracks = jsonObj.getJSONArray(TAG_RESULT);

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

                    artworkImage = c.getString("artworkUrl100");
                    wrapperType = c.getString("wrapperType");
                    artistName = c.getString("artistName");
                    collectionName = c.getString("collectionName");
                    trackName = c.getString("trackName");
                    collectionPrice = c.getString("collectionPrice");
                    trackId = c.getString("trackId");

                    // tmp hashmap for single contact
                    HashMap<String, String> tunesMap = new HashMap<String, 
                    String>();

                    // adding each child node to HashMap key => value
                    // contact.put(TAG_ID, firstname);
                    tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
                    tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
                    tunesMap.put(TAG_ARTIST_NAME, artistName);
                    tunesMap.put(TAG_COLLECTION_NAME, collectionName);
                    tunesMap.put(TAG_TRACK_NAME, trackName);
                    tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
                    tunesMap.put(TAG_TRACK_ID, trackId);

                    // adding contact to contact list
                    singleTrackDetails.add(tunesMap);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
        wrapperTypeText.setText(wrapperType);
        artistNameText.setText(artistName);
        collectionNameText.setText(collectionName);
        trackNameText.setText(trackName);
        collectionPriceText.setText(collectionPrice);

    }
}

Thank you

Upvotes: 0

Views: 60

Answers (1)

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.

Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.

A solution for this is to create a final resultp within your getView method instead of having just one global resultp.

final HashMap<String, String> resultp = data.get(position);

Upvotes: 1

Related Questions