Android开发:如何去除日期中的"/"并追加到指定URL?
Solution: Dynamic URL Construction with Volley Integration
Let's walk through how to implement this step by step, with proper error handling and Volley integration:
Step 1: Handle Intent Parameters & URL Construction
First, we'll safely retrieve the Intent extras, process the departure date to remove slashes, then build our final API URL. Note that I've fixed the & in your original URL to & (since & is an HTML entity and will cause issues in a real API request):
public class MyActivity extends AppCompatActivity { // Base URL with placeholders for dynamic params private static final String BASE_URL = "https://tripfareapi.herokuapp.com/flightapi?src=%s&dest=%s&depdate=%s"; private String departuredate; // Class-level variable if needed elsewhere @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); // Retrieve Intent extras safely Bundle bundle = getIntent().getExtras(); if (bundle != null) { String from = bundle.getString("from"); String to = bundle.getString("to"); departuredate = bundle.getString("departuredate"); // Validate all required parameters are present if (from != null && to != null && departuredate != null) { // Remove all "/" from departure date String cleanedDate = departuredate.replaceAll("/", ""); // Build the final URL using String formatting String newUrl = String.format(BASE_URL, from, to, cleanedDate); // Call Volley method to fetch data getData(newUrl); } else { // Handle missing parameters (show error toast, etc.) Toast.makeText(this, "Missing required flight parameters", Toast.LENGTH_SHORT).show(); } } else { // No extras found in Intent Toast.makeText(this, "No flight details provided", Toast.LENGTH_SHORT).show(); } }
Step 2: Implement Volley's getData() Method
Next, we'll create the getData() method to send a GET request using Volley, handle the response, and manage errors. Make sure you've added Volley to your project dependencies first (e.g., implementation 'com.android.volley:volley:1.2.1' in your app-level build.gradle):
private void getData(String url) { // Initialize Volley RequestQueue RequestQueue requestQueue = Volley.newRequestQueue(this); // Create a StringRequest for GET request StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response -> { // Handle successful response (parse JSON, update UI, etc.) Log.d("VolleyResponse", "Response: " + response); // Example: Parse the response into your data model here }, error -> { // Handle request errors Log.e("VolleyError", "Error fetching data: " + error.getMessage()); Toast.makeText(this, "Failed to fetch flight data", Toast.LENGTH_SHORT).show(); }); // Add the request to the queue requestQueue.add(stringRequest); } }
Key Notes:
- Safe Parameter Handling: We added null checks for the Bundle and all retrieved parameters to avoid
NullPointerExceptions. - URL Formatting: Using
String.format()makes the URL construction cleaner than concatenation, especially with multiple dynamic values. - Date Cleaning:
replaceAll("/", "")removes all forward slashes from the departure date string. If you only need to remove specific instances, you can adjust this (but this works for full removal). - Volley Setup: Ensure you have Volley added to your project, and the RequestQueue is properly initialized. You can also use a singleton RequestQueue for better performance across your app.
内容的提问来源于stack exchange,提问作者mDeveloper
相关产品推荐
相关产品推荐

