如何从url(json数据)显示另一个活动中的单个列表项的详细信息?

时间:2015-05-16 17:11:13

标签: java android json

我编写了一个程序,用于显示来自URL的json数据列表,该URL具有图像和5个完整显示的textviews。 网址:https://itunes.apple.com/search?term=jack+johnson&limit=50

当我点击列表中的某个项目时,我想根据track-id在另一个活动中显示该项目的详细信息 网址:https://itunes.apple.com/lookup?id=659234741

因此,当我点击该项目时,详细信息将显示在文本视图中,但默认情况下,它会显示某些项目的id = 659234741的详细信息,或者简而言之,细节不匹配。

需要一些帮助才能找出问题

我的代码:

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:这是我在单项单击

上显示详细信息的类
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);

    }
}

谢谢

1 个答案:

答案 0 :(得分:1)

问题是您正在初始化getView方法中的每个元素resultp,因此listview适配器data的最后一个id /元素将被视为{{ 1}}。

我确定id resultp是最后一个元素,它将始终是每个onclick的id。

解决方法是在getView方法中创建最终659234741,而不是只有一个全局resultp

resultp