You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:ListView筛选后如何通过JSON存储ID跳转Activity

Fixing Intent Navigation with JSON ID After ListView Filtering

Hey there! I totally get the frustration—when you filter your ListView, the position of items shifts, so using the position to fetch data from the original JSON array doesn't work anymore. The solution is simple: instead of passing the ListView position, pass the actual id stored in your Model object (which matches the ID from your JSON). Here's how to fix this step by step:

Step 1: Pass the Real ID from MainActivity's Item Click

Right now, you're passing the ListView position to the Info activity. Instead, grab the clicked Model object and extract its real ID:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Get the clicked Model object from the Adapter
        Model clickedItem = (Model) parent.getItemAtPosition(position);
        int realItemId = clickedItem.getId();
        
        // Pass the real ID instead of position
        Intent myIntent = new Intent(MainActivity.this, Info.class);
        myIntent.putExtra("item_id", realItemId);
        startActivity(myIntent);
    }
});

Step 2: Fetch Data by ID in the Info Activity

Previously, you used the position to index directly into the JSON array. Now, you'll need to loop through the JSON array to find the item that matches the passed ID:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_info);
    aaa = (TextView) findViewById(R.id.aaa);
    bbb = (TextView) findViewById(R.id.bbb);
    
    Intent mIntent = getIntent();
    int targetId = mIntent.getIntExtra("item_id", -1);
    
    // Handle case where no ID was passed
    if (targetId == -1) {
        finish();
        return;
    }
    
    String arquivo = loadJSON("lista.json");
    try {
        JSONObject obj = new JSONObject(arquivo);
        JSONArray a = obj.getJSONArray("locais");
        
        // Loop through the array to find the matching ID
        for (int i = 0; i < a.length(); i++) {
            JSONObject item = a.getJSONObject(i);
            int currentId = item.getInt("id"); // JSON "id" strings are parsed to int here
            
            if (currentId == targetId) {
                aaa.setText(String.valueOf(currentId));
                bbb.setText("Base: " + item.getString("description"));
                break; // Exit loop once we find the item
            }
        }
        
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Bonus: Optimize by Passing the Entire Model Object (Optional)

For a cleaner, more efficient approach, you can make your Model class implement Parcelable so you can pass the entire object directly through the Intent. This avoids re-parsing the JSON in the Info activity:

Update the Model Class to Implement Parcelable

public class Model implements Parcelable {
    private String description;
    private int id;

    public Model(int id, String description) {
        this.id = id;
        this.description = description;
    }

    // Parcelable constructor
    protected Model(Parcel in) {
        description = in.readString();
        id = in.readInt();
    }

    // Parcelable required methods
    public static final Creator<Model> CREATOR = new Creator<Model>() {
        @Override
        public Model createFromParcel(Parcel in) {
            return new Model(in);
        }

        @Override
        public Model[] newArray(int size) {
            return new Model[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(description);
        dest.writeInt(id);
    }

    // Getters and Setters
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

Pass the Model Object in MainActivity

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Model clickedItem = (Model) parent.getItemAtPosition(position);
        Intent myIntent = new Intent(MainActivity.this, Info.class);
        myIntent.putExtra("selected_model", clickedItem);
        startActivity(myIntent);
    }
});

Retrieve the Model in Info Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_info);
    aaa = (TextView) findViewById(R.id.aaa);
    bbb = (TextView) findViewById(R.id.bbb);
    
    Model selectedModel = getIntent().getParcelableExtra("selected_model");
    if (selectedModel != null) {
        aaa.setText(String.valueOf(selectedModel.getId()));
        bbb.setText("Base: " + selectedModel.getDescription());
    } else {
        finish();
    }
}

This approach is better for performance (no repeated JSON parsing) and makes your code cleaner—perfect for a university project!

内容的提问来源于stack exchange,提问作者slamvanpanel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:45:21