使用 JSON 将数据从 mysql 显示到 android studio
Posted
技术标签:
【中文标题】使用 JSON 将数据从 mysql 显示到 android studio【英文标题】:Displaying data from mysql into android studio using JSON 【发布时间】:2017-02-11 10:21:51 【问题描述】:我想使用 textview 将 mysql 中的数据显示到 android 中,但是当我运行应用程序时,它会自行强制停止, 有人可以帮我解决它,, 任何想法都会很好
dbconfig.php
<?php
//This script is designed by Android-Examples.com
//Define your host here.
$servername = "localhost";
//Define your database username here.
$username = "root";
//Define your database password here.
$password = "";
//Define your database name here.
$dbname = "u727224026_demo";
?>
发送数据.php
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM TextViewTable";
$result = $conn->query($sql);
if ($result->num_rows > 0)
// output data of each row
while($row[] = $result->fetch_assoc())
$json = json_encode($row);
else
echo "0 results";
echo $json;
$conn->close();
?>
MainActivity.java
package flix.yudi.kuesioner2;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
);
private class GetTextViewData extends AsyncTask<Void, Void, Void>
public Context context;
public GetTextViewData(Context context)
this.context = context;
@Override
protected void onPreExecute()
super.onPreExecute();
@Override
protected Void doInBackground(Void... arg0)
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("192.168.1.139/a_test/send-data.php");
try
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
catch (ClientProtocolException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
try
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
catch ( JSONException e)
e.printStackTrace();
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
return null;
protected void onPostExecute(Void result)
try
textview.setText(json.getString("ServerData"));
catch (JSONException e)
// TODO Auto-generated catch block
e.printStackTrace();
//Hiding progress bar after done loading TextView.
progressbar.setVisibility(View.GONE);
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.jsonparsingfromurltextview_android_examples.com.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_
android:layout_
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="TextView Static Text Before Load"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center"/>
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_
android:layout_
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp" />
<Button
android:id="@+id/button1"
android:layout_
android:layout_
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="Click Here to Load TextView data dynamically from MySQL Database Online Using JSON Parsing" />
logcat 错误提示
10-03 08:35:35.486 1754-2070/flix.yudi.kuesioner2 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: flix.yudi.kuesioner2, PID: 1754
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=192.168.1.139/a_test/send-data.php
at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at flix.yudi.kuesioner2.MainActivity$GetTextViewData.doInBackground(MainActivity.java:84)
at flix.yudi.kuesioner2.MainActivity$GetTextViewData.doInBackground(MainActivity.java:60)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
我试图找到如何解决它,但仍然没有, 请帮帮我,
ADDITIONAL INFO RESPONSE
【问题讨论】:
尝试下载 Postman,然后尝试向您的 url 发送 post 请求。你有回应吗? 感谢您的建议,我想知道如何使用它,因为我不知道,, 应该很简单,又好又直观 我已经编辑了我的帖子,关于来自另一个应用程序(如邮递员)的响应截图,现在我应该为下一步做什么先生?你有什么想法吗? 【参考方案1】:尝试将http
或https
之类的方案添加到URL
:
http://192.168.1.139/a_test/send-data.php
【讨论】:
我已经在 URL 中添加了 http 或 https,但它仍然强制关闭自己,您还有其他想法吗?【参考方案2】:首先在邮递员中尝试你的服务调用......检查你是否从 192.168.1.139/a_test/send-data.php 得到正确的响应
关注her获取邮递员插件
检查下面的代码
private String makeRESTService(String methodNameWithUrl) throws JSONException
final String KEY_USER_NAME = "username";
final String KEY_PASSWORD = "password";
System.out.println("url" + methodNameWithUrl);
String jsonResult = null;
String jsonObj = null;
//create a json string
JSONObject parent = new JSONObject();
parent.put(KEY_USER_NAME, "manu");
parent.put(KEY_PASSWORD, "1234");
Log.e("To json", jsonObj);
URL url = null;
HttpURLConnection urlConnection = null;
try
url = new URL("your url"); //place your url
catch (MalformedURLException e)
e.printStackTrace();
try
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonObj);
writer.flush();
writer.close();
os.close();
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
jsonResult = inputStreamToString(in)
.toString();
Log.e("jsonResult", jsonResult);
// readStream(in);
catch (IOException e)
e.printStackTrace();
finally
urlConnection.disconnect();
return jsonResult;
private StringBuilder inputStreamToString(InputStream is)
String rLine = "";
StringBuilder answer = new StringBuilder();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
try
while ((rLine = rd.readLine()) != null)
answer.append(rLine);
catch (IOException e)
e.printStackTrace();
return answer;
【讨论】:
感谢您的代码和您的参考,我试试看,您还有其他适用于 firef*x 的应用程序吗?但是我应该把你的代码放在哪里?我应该创建新的 java 类吗? AsyncTask 的 doinBackground 内部 我已经附上了来自服务器的截图响应,先生,你怎么看?我是不是做错了什么?以上是关于使用 JSON 将数据从 mysql 显示到 android studio的主要内容,如果未能解决你的问题,请参考以下文章
如何从 NSDictionary 将 json 显示到 uitextview
使用 JSON 和 PHP 从 Mysql DB 获取数据到 listView