我想使用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";
?>
发送-data.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_width="match_parent"
android:layout_height="match_parent"
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_width="wrap_content"
android:layout_height="wrap_content"
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_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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)
我试图找到如何解决它,但仍然没有, 请帮帮我,
答案 0 :(得分:0)
尝试向http
添加https
或URL
等方案:
http://192.168.1.139/a_test/send-data.php
答案 1 :(得分:0)
首先尝试邮递员的服务电话...检查你是否从192.168.1.139/a_test/send-data.php获得了正确的回复
按照her获取postman插件
检查下面的代码
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;
}