如何在android中检索textView文本,以便.php文件将其读作' $ _ id'的ID。在预执行php文件之前?因为在我的php文件中,我需要在执行json数组之前从我的android工作室检索一个ID(这是我认为至少在错误中我想到的)
我是编程新手所以请解释一下,当你还是编程的新手时
这是我的php代码:
<?php
$host='localhost';
$user='root';
$password='';
$db='employee101';
$_id = $_POST['id'];
$sql = "select * from employee_comments where id = $_id;";
$con = mysqli_connect($host,$user,$password,$db);
$result = mysqli_query($con, $sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response,array("id"=>$row[0],"comment"=>$row[1],"rating"=>$row[2]));
}
echo json_encode(array("server_respo"=>$response));
mysqli_close($con);
?>
以下是我在android studio中的代码 包rjj.tutorial_jsonandlistview;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
String Json_STRING;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackgroundTask().execute();
//new line
}
/*public void getJSON(View view) {
new BackgroundTask().execute();
}*/
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/json_comments.php";
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText(result);
Json_STRING = result;
}
}
编辑: php文件
<?php
$host='localhost';
$user='root';
$password='';
$db='employee101';
if (!empty($_POST['id'])) {
$_id = $_POST['id'];
$sql = "select * from employee_comments where id = $_id;";
$con = mysqli_connect($host,$user,$password,$db);
$result = mysqli_query($con, $sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response,array("id"=>$row[0],"comment"=>$row[1],"rating"=>$row[2]));
}
}
echo json_encode(array("server_respo"=>$response));
mysqli_close($con);
?>
在预执行中添加了一行以检索ID,但我认为它无效
protected void onPreExecute() {
textView = (TextView) findViewById(R.id.textView3);
String password = textView.getText().toString();
json_url = "http://10.0.2.2/json_comments.php";
}
PHP中的错误:
注意:未定义的索引:在C:\ wamp64 \ www \ json_comments.php中的id在线 6注意:未定义的变量:响应中 第25行的C:\ wamp64 \ www \ json_comments.php注意:未定义 变量:第27行的C:\ wamp64 \ www \ json_comments.php中的con警告: mysqli_close()期望参数1为mysqli,null为null 第27行的C:\ wamp64 \ www \ json_comments.php
答案 0 :(得分:0)
你需要将你的代码包装在条件
中if (!empty($_POST['id'])) {
# place your code here
}
修改强>
<?php
$host='localhost';
$user='root';
$password='';
$db='employee101';
if (!empty($_POST['id'])) {
$_id = $_POST['id'];
$sql = "select * from employee_comments where id = $_id;";
$con = mysqli_connect($host,$user,$password,$db);
$result = mysqli_query($con, $sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response,array("id"=>$row[0],"comment"=>$row[1],"rating"=>$row[2]));
}
echo json_encode(array("server_respo"=>$response));
mysqli_close($con);
}
?>
答案 1 :(得分:0)
在php文件中,您从 $ _ POST ['id'] 获取ID。那么,在Java文件中, HttpURLConnection httpURLConnection 你需要使用方法POST,并将数据发送到php文件。
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
String Json_STRING;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackgroundTask().execute();
//new line
}
/*public void getJSON(View view) {
new BackgroundTask().execute();
}*/
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/json_comments.php";
}
@Override
protected String doInBackground(Void... params) {
try {
String urlParameters = "id=your_id";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = json_url;;
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
is = urlConn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
stringBuilder.append(inputLine + "\n");
in.close();
return stringBuilder.toString().trim();
//Your code read data return here ...
} else {
is = urlConn.getErrorStream();
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText(result);
Json_STRING = result;
}
}
答案 2 :(得分:-1)
首先你不能在asynctask里面的textview中设置值,因为所有ui相关的操作只能在ui线程上完成,见下文
如果您想在代码中读取和写入文本,可以执行以下操作:
public class MainActivity extends AppCompatActivity {
String Json_STRING;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.text_view_id);
String text=textview.getText();
new BackgroundTask().execute(text);
//new line
}
/*public void getJSON(View view) {
new BackgroundTask().execute();
}*/
// change first param of asynctask to String to accept array of string params
class BackgroundTask extends AsyncTask<String, Void, String> {
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/json_comments.php";
}
@Override
protected String doInBackground(String... params) {
try {
String param=params[0]; // you can access text of textview from here and pass it to your url like "json_url?id=param"
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(result);
}
});
}
}
php android