PHP生成JSON数据在Android Studio TextView显示及计算结果无法展示求助
Hey there! Let’s break down your two PHP + Android questions with practical, actionable solutions:
This involves two key parts: setting up your PHP backend to output valid JSON and writing Android code to fetch, parse, and display that data.
Step 1: PHP Backend - Output Valid JSON
First, make sure your PHP script sends the correct HTTP headers and encodes your data properly as JSON:
// Sample data (replace with your actual data) $responseData = [ "status" => "success", "content" => "Hello from your PHP server!" ]; // Set response header to indicate JSON content header("Content-Type: application/json"); // Encode and output the data echo json_encode($responseData); exit; // Stop execution after outputting JSON
Step 2: Android Frontend - Fetch and Display Data
We’ll use Volley (a lightweight network library) for simplicity—you can also use Retrofit if you prefer.
- Add Volley dependency to your app-level
build.gradle:
dependencies { implementation 'com.android.volley:volley:1.2.1' }
- Add internet permission to
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
- Write code to fetch JSON and update TextView:
import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONObject; import android.widget.TextView; // Inside your Activity's onCreate method RequestQueue requestQueue = Volley.newRequestQueue(this); String phpApiUrl = "http://your-server-ip/your-script.php"; // Replace with your actual PHP URL JsonObjectRequest jsonRequest = new JsonObjectRequest( Request.Method.GET, phpApiUrl, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // Parse the JSON response String message = response.getString("content"); // Update your TextView TextView resultTextView = findViewById(R.id.your_textview_id); resultTextView.setText(message); } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); // Handle errors (e.g., show "Failed to load data" in TextView) TextView resultTextView = findViewById(R.id.your_textview_id); resultTextView.setText("Failed to load data"); } } ); requestQueue.add(jsonRequest);
Looking at your PHP code snippet, there are a few likely issues preventing the $tot value from displaying correctly. Let’s troubleshoot:
Issue 1: Incomplete PHP Code (Syntax Error)
Your code cuts off at number_format($...—this will throw a PHP syntax error, which breaks the JSON output. Make sure you complete the number_format call properly. For example:
// Complete the number_format call (adjust decimal places as needed) $format->predicted = number_format($tot, 2); //保留两位小数 // Don't forget to output the JSON correctly header("Content-Type: application/json"); echo json_encode($format); exit;
Issue 2: $tot Might Be Invalid (NaN/Infinite)
If $b1, $b2, or $b3 have values that lead to invalid calculations, $tot could become NaN (Not a Number) or infinite. JSON encodes these as null, which Android might fail to parse. Add validation in PHP:
// Check if $tot is a valid number if (!is_numeric($tot) || is_infinite($tot) || is_nan($tot)) { $format->predicted = "Invalid calculation"; } else { $format->predicted = number_format($tot, 2); }
Issue 3: Android Parsing Mismatch
Since number_format returns a string (e.g., "123.45"), make sure you parse it as a string in Android, not a numeric type:
// In your onResponse method String totalAmount = response.getString("predicted"); TextView totalTextView = findViewById(R.id.total_textview); totalTextView.setText("Total: $" + totalAmount);
If you want to handle it as a number in Android, skip number_format in PHP and send the raw float:
$format->predicted = $tot; // Send raw numeric value
Then parse it in Android:
double total = response.getDouble("predicted"); TextView totalTextView = findViewById(R.id.total_textview); totalTextView.setText(String.format("Total: $%.2f", total));
Issue 4: Invalid JSON Output
Always test your PHP script directly in a browser to check if it outputs valid JSON. If you see PHP error messages mixed with JSON, fix those errors first—they’ll break Android’s parsing.
内容的提问来源于stack exchange,提问作者jerald furigay

