Android Studio中如何将PHP变量/字符串传递至Java?
Hey there! Let's break this down step by step to get your PHP $result variable properly passed to your Android Java code, and confirm that your core思路 is actually on the right track.
First: Your Initial Idea Is Correct!
You're right that PHP's output (like echoing $result) should be received in Android's onPostExecute method. The gap is likely in how you're formatting the PHP output, or how you're reading/processing it on the Android side. Let's fix those missing pieces.
Step 1: Make Sure Your PHP Script Outputs $result Properly
Just echoing raw values might cause parsing issues on the Android side, especially if $result is an array or object. The safest approach is to use JSON for data exchange:
<?php // First, set the response header to tell Android this is JSON data header('Content-Type: application/json'); // Assume $result is your data (could be an array, object, etc.) $result = [ "status" => "success", "account_id" => 456, "message" => "Account created successfully" ]; // Encode and output the result as JSON echo json_encode($result); ?>
This ensures the data is structured consistently, making it easy to parse in Java.
Step 2: Fix the Android Side to Receive and Process the Data
If you're using AsyncTask (since you mentioned onPostExecute), here's how to properly fetch and handle the PHP response:
First, Add Required Permissions
In your AndroidManifest.xml, don't forget these critical permissions (otherwise the app can't make network calls):
<uses-permission android:name="android.permission.INTERNET" /> <!-- For Android 9+, add this if you're using HTTP (not HTTPS) --> <application ... android:usesCleartextTraffic="true"> ... </application>
Example AsyncTask Implementation
private class FetchAccountTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... voids) { String phpResponse = ""; try { // Replace with your local server IP (don't use localhost - emulator can't reach it!) URL url = new URL("http://192.168.1.100/dupCreateAccount.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // Use POST if your PHP expects POST data // Read the response from PHP InputStream inputStream = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { phpResponse += line; } conn.disconnect(); } catch (IOException e) { e.printStackTrace(); phpResponse = "Error fetching data"; } return phpResponse; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); // This response is exactly what PHP echoed! Now parse the JSON try { JSONObject jsonResult = new JSONObject(response); String status = jsonResult.getString("status"); int accountId = jsonResult.getInt("account_id"); String message = jsonResult.getString("message"); // Now you can use this data for your Java business logic Log.d("Account Data", "Status: " + status + ", ID: " + accountId); // Update UI or run other business logic here } catch (JSONException e) { e.printStackTrace(); // Handle cases where the response isn't valid JSON } } }
Common Mistakes You Might Be Making
- Using
localhostin the Android URL: The emulator'slocalhostpoints to itself, not your computer's server. Use your computer's local IP address (e.g.,192.168.1.100) instead. - Not reading the full response: If you're only checking the HTTP status code and not reading the input stream, you'll never get the
$resultdata. - Missing JSON formatting: Echoing raw strings or unstructured data makes parsing unreliable. JSON is the standard for cross-language data exchange.
- Network calls on the main thread: Android blocks network operations on the UI thread, so make sure all fetching happens in
doInBackground.
内容的提问来源于stack exchange,提问作者JD333

