Android Studio:在单个Async Task中从两个URL下载JSON数据
Hey there! Let's work through this together—since you already have one URL working with your downloadJSON class, adding a second dataset to display alongside it is totally doable. Let's break down common, actionable approaches to fix this:
1. Fetch Both URLs in Parallel (Most Efficient)
If your downloadJSON class supports asynchronous operations (like returning a Promise), you can kick off both requests at the same time and wait for both to complete before processing the data. Here's a typical implementation:
// Assuming your downloadJSON returns a Promise Promise.all([ downloadJSON("https://your-first-url.com/data"), downloadJSON("https://your-second-url.com/data") ]) .then(([firstDataset, secondDataset]) => { // Now you have both datasets—render them together! console.log("First data:", firstDataset); console.log("Second data:", secondDataset); renderCombinedContent(firstDataset, secondDataset); }) .catch(error => { console.error("One or both requests failed:", error); });
This way, you don't waste time waiting for the first request to finish before starting the second.
2. Fetch URLs Sequentially (Simpler for Sync Code)
If your downloadJSON works synchronously, or you need to fetch the first dataset before the second, just call the method back-to-back:
try { const firstDataset = downloadJSON("https://your-first-url.com/data"); const secondDataset = downloadJSON("https://your-second-url.com/data"); // Process and display both datasets together renderCombinedContent(firstDataset, secondDataset); } catch (error) { console.error("Request failed:", error); }
Note: This will be slower than parallel requests since it waits for one to finish before starting the next.
3. Troubleshoot the Second URL (Often the Culprit)
If the above logic isn't working, the issue might not be your code—it could be the second URL itself. Check these things:
- Double-check the URL for typos, missing paths, or incorrect domain names
- If you're working in a browser, check the Network tab in dev tools to see the request status (e.g., 404, 403, 500)
- Confirm the second URL returns valid JSON (use tools like JSONLint to validate the response)
- Ensure the server allows cross-origin requests (if you're fetching from a different domain)
4. Extend Your downloadJSON Class for Batch Requests
If you want to make this reusable, add a static method to your class to handle multiple URLs at once:
class downloadJSON { static async fetchSingle(url) { // Your existing single-URL fetch logic here const response = await fetch(url); if (!response.ok) throw new Error(`HTTP Error: ${response.status}`); return response.json(); } static async fetchMultiple(urls) { return Promise.all(urls.map(url => this.fetchSingle(url))); } } // Usage downloadJSON.fetchMultiple([url1, url2]) .then(([data1, data2]) => renderCombinedContent(data1, data2)) .catch(err => console.error(err));
内容的提问来源于stack exchange,提问作者rianskii

