Android Studio php 连接
Posted
技术标签:
【中文标题】Android Studio php 连接【英文标题】:Android Studio php connection 【发布时间】:2021-05-29 01:03:05 【问题描述】:我正在尝试在 android studio java 中使用 php 从 db 获取信息。 php 代码 100% 工作。 问题是当我从 Android 模拟器打开应用程序时,应用程序几乎立即自行关闭。
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.c__expensechart, PID: 2450
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:121)
at org.json.JSONTokener.nextValue(JSONTokener.java:98)
at org.json.JSONObject.<init>(JSONObject.java:165)
at org.json.JSONObject.<init>(JSONObject.java:182)
at com.example.c__expensechart.MainActivity$Connection.onPostExecute(MainActivity.java:89)
at com.example.c__expensechart.MainActivity$Connection.onPostExecute(MainActivity.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:771)
at android.os.AsyncTask.access$900(AsyncTask.java:199)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 2450 SIG: 9
这是我在 run 中收到的错误消息 Logcat 为空 Build 也没有错误 据我所知,onPostExecute 存在问题,所以让我向您展示它的外观
我有课
class Connection extends AsyncTask<String, String, String>
其中我有两个功能:
protected String doInBackground(String... params)
String result = "";
String host = "http://192.168.1.114/php_api/GET.php";
try
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
while((line = reader.readLine()) != null)
stringBuffer.append(line);
break;
reader.close();
result = stringBuffer.toString();
catch(Exception e)
return new String("There exception" + e.getMessage());
return null;
和
protected void onPostExecute(String result)
try
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success == 1)
JSONArray measurements = jsonResult.getJSONArray("measurements");
for(int i = 0; i < measurements.length(); i++)
JSONObject measure = measurements.getJSONObject(i);
int measureId = measure.getInt("id");
double start_times = measure.getDouble("start_times");
double end_times = measure.getDouble("end_times");
double power = measure.getDouble("power");
String line = measureId + ":" + start_times + ":" + end_times + ":" + power;
setMeasureInfo(line);
else
Toast.makeText(getApplicationContext(), "There aren't any measurements", Toast.LENGTH_SHORT).show();
catch (JSONException e)
编辑: 关于我创建的数据库连接,它会向我显示它在文件中读取的所有内容,以确保 这就是它所说的
"success":1,
"measurements"[
"id":"1","start_times":"42405","end_times":"48","power":"65508"
]
我的 PHP 代码:
<?php
$host = 'localhost';
$user = 'root';
$pwd = '';
$db = 'c--db';
$conn = mysqli_connect($host, $user, $pwd, $db);
if(!$conn)
die("ERROR in connection: " . mysqli_connect_error());
$response = array();
$sql_query = "SELECT * FROM `measurements`";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0)
$response['success'] = 1;
$measurements = array();
while($row = mysqli_fetch_assoc($result))
array_push($measurements, $row);
$response['measurements'] = $measurements;
else
$response['success'] = 0;
$response['message'] = 'No data';
echo json_encode($response);
mysqli_close($conn);
?>
【问题讨论】:
【参考方案1】:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int java.lang.String.length()”
在 com.example.c__expensechart.MainActivity$Connection.onPostExecute(MainActivity.java:89)
JSONArray measurements = jsonResult.getJSONArray("measurements");
for(int i = 0; i < measurements.length(); i++)
...
您可能不会在此处检索您的数组。检查密钥是否正确。
【讨论】:
你的意思是“测量” 是的。您确定此时可以获得“测量”字段吗?您可以发布您的 JSON 文件,或者至少发布带有测量值的部分吗? 我不使用 JSON 文件检查 php 最好能看到生成的 JSON。有断点一步步检查解析吗? 您的“测量”键后缺少“:”,但我认为这是一个错字问题。尝试在解析中放置断点以查看会发生什么【参考方案2】:我解决了这个问题。 所以实际上我仔细检查了错误日志,发现它与 apache 库有关 我搜索了错误,发现我也必须将它添加到 AndroidManifest.xml 它应该是这样的:
<application
...
...
android:usesCleartextTraffic="true"
android:requestLegacyExternalStorage="true">
...
...
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
【讨论】:
以上是关于Android Studio php 连接的主要内容,如果未能解决你的问题,请参考以下文章