【发布时间】:2021-03-11 06:48:31
【问题描述】:
我目前正在构建一个需要管理历史交易数据库的项目。
我按照本网站的说明将我的数据库连接到项目:
How To Connect An Android App To A MySQL Database
之后,我尝试在Fragment_History 中使用此代码构建我的项目,但是出现了这个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mind.loginregisterapps, PID: 6912
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.JSONArray.<init>(JSONArray.java:94)
at org.json.JSONArray.<init>(JSONArray.java:110)
at com.mind.loginregisterapps.Fragment_History.loadIntoListView(Fragment_History.java:83)
at com.mind.loginregisterapps.Fragment_History.access$000(Fragment_History.java:24)
at com.mind.loginregisterapps.Fragment_History$1DownloadJSON.onPostExecute(Fragment_History.java:55)
at com.mind.loginregisterapps.Fragment_History$1DownloadJSON.onPostExecute(Fragment_History.java:42)
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)
我查看了代码,发现downloadJSON中的URL连接失败导致null值被传递。
因此,我添加了res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config>
</network-security-config>
并编辑清单:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true"
</application>
然后,使用HTTPUrlConnection时出现此错误,我迷茫了:
Failed to connect to localhost/127.0.0.1:80
我尝试将downloadJSON和network_security_config.xml中的localhost改成127.0.0.1,错误变成:
Failed to connect to /127.0.0.1:80
我该如何解决这个问题?请告诉我。
非常感谢!
代码如下:
Fragment_History.java
public class Fragment_History extends Fragment {
ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_history, container, false);
listView = (ListView)view.findViewById(R.id.list_history);
downloadJSON("http://localhost/hist_login.php");
return view;
}
private void downloadJSON(final String urlWebService) {
class DownloadJSON extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
ArrayList<History> list = new ArrayList<History>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
list.add(new History(obj.getString("h_rName"),obj.getDouble("h_amount")));
}
HistoryAdapter adapter = new HistoryAdapter(list, getActivity());
listView.setAdapter(adapter);
}
}
hist_login.php:
<?php
$db = "test";
$user = "root";
$pass = "";
$host = "localhost";
// Create connection
$con=mysqli_connect($host,$user,$pass,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all of our stocks from table 'history'
$sql = "SELECT * FROM history";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
} else
{
echo "Not connected...";
}
// Close connections
mysqli_close($con);
?>
【问题讨论】:
-
我的回答让你满意吗?