我需要将值传递给textview。任何人都可以帮助我吗? [英] i need to get the values to a textview .can anyone help me ?
问题描述
package com.example.get;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache .http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl。 client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
$ / b
import android.app.Activity;
import andro id.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences ;
导入android.content.SharedPreferences.Editor;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android .widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展Activity实现OnClickListener {
私有EditText用户;
私有Button获取;
TextView txtFname;
TextView txtMname;
TextView txtLname;
JSONObject hay;
//进度对话框
私有ProgressDialog pDialog;
// JSON解析器类
JSONParser jsonParser = new JSONParser(); < br $>
private static final String LOGIN_URL =http://www.digiassistant.comuf.com/projectphp/test.php; //更改为webhost
//从真实服务器测试:
//私有静态最终字符串LOGIN_URL =http:/ /www.yourdomain.com/webservice/login.php;
//来自php脚本repsonse的JSON元素ID:
private static final String TAG_SUCCESS =success;
private static final String TAG_MESSAGE =message;
@Override
protected void onCreate(Bundle savedInstanceState){
// TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//设置输入字段
user =(EditText)findViewById(R.id.user );
txtFname =(TextView)findViewById(R.id.fname);
txtMname =(TextView)findViewById(R.id.lname);
txtLname =(TextView)findViewById(R.id.mname);
//设置按钮
get =(Button)findViewById(R.id.get);
//注册听众
get.setOnClickListener(this);
}
@Override
public void onClick(查看v){
// TODO自动生成的方法存根
新的AttemptLogin()。执行();
}
类AttemptLogin扩展了AsyncTask< string,> {
/ **
*开始后台主题之前显示进度对话框
* * /
boolean failure = false;
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(尝试登录......);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String ... args){
// TODO自动生成的方法存根
//检查成功标签
int success;
String username = user.getText() .toString();
试试{
//构建参数
List< namevaluepair> params = new ArrayList< namevaluepair>();
params.add(new BasicNameValuePair(username,username));
Log .d(request!,starting);
//通过发出HTTP请求获取产品详细信息
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL,POST,params);
//检查日志中的json响应
Log.d(登录尝试,json.toString());
// json成功标签
success = json.getInt(TAG_SUCCESS);
if(success == 1){
Log.d(Login Successful!,json.toString());
///
//
//意图i =新意图(Login.this,Ma inActivity.class);
//完成();
// startActivity(i);
// finish();
返回json.getString(TAG_MESSAGE);
} else {
Log.d(登录失败! ,json.getString(TAG_MESSAGE));
返回json.getString(TAG_MESSAGE);
}
} catch(JSONException e){
e.printStackTrace();
}
返回null; < br $>
}
/ **
*完成后台任务后关闭进度对话框
* ** /
protected void onPostExecute(String file_url){
//删除产品后关闭对话框
pDialog.dismiss( );
尝试{
JSONObj ect json = null;
JSONObject hay = new JSONObject((Map)json);
JSONArray user = hay.getJSONArray(user);
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString(firstname);
String middlename = jb.getString(middlename );
String lastname = jb.getString(lastname);
//在textview中显示所有数据
txtFname.setText(名字:+名字);
txtMname.setText(中间名:+中间名);
txtLname.setText(姓氏+姓氏);
} catch(例外e)
{
e.printStackTrace( );
}
if(file_url!= null){
Toast.makeText(MainActivity.this,file_url,Toast.LENGTH_LONG)。 show();
}
}
}
}
当我运行这个时我只能获得帖子。
它不会更新txtviews
< br $>
这是我的php文件
require('config.inc.php');
if(!empty($ _ POST)){
//初始查询
$ query =选择last_name,first_name, middle_initial FROM admin其中username =:user;
$ query_params = array(':user'=> $ _POST ['username']);
//执行查询
try {
$ stmt = $ db - >准备($查询);
$ result = $ stmt - >执行($ query_params);
} catch(PDOException $ ex){
$ response [success] = 0;
$ response [message] =数据库错误!;
die(json_encode($ response));
}
//最后,我们可以使用fetchAll将所有找到的行检索到数组中
$ rows = $ stmt - > fetchAll();
if($ rows){
$ response [success] = 1;
$ response [message] =发布可用!;
$ response [user] = array();
foreach($行作为$ row){
$ user = array();
// $ user [names] = $ row [names ];
$ user [middlename] = $ row [middle_initial];
$ user [firstname] = $ row [first_name];
$ user [lastname] = $ row [last_name];
//更新我们的repsonse JSON数据
array_push($ response [user],$ user);
}
//回显JSON响应
echo json_encode($ response);
} else {
$ response [success] = 0 ;
$ response [message] =没有用户可用!;
die(json_encode($回复));
}
}否则{}
?>
< form action =test.phpmethod =POST>
用户名:< input type =textname =username>
< input type =submitvalue =Submit>
< ; / form>
package com.example.get;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private EditText user;
private Button get;
TextView txtFname;
TextView txtMname;
TextView txtLname;
JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://www.digiassistant.comuf.com/projectphp/test.php"; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText)findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button)findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask<string,> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List<namevaluepair> params = new ArrayList<namevaluepair>();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
///
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try{
JSONObject json = null;
JSONObject hay = new JSONObject ((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
}catch(Exception e)
{
e.printStackTrace();
}
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
when i run this i get post available only .
it doesnt update the txtviews
here is my php file
require('config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
推荐答案
_POST)){
//初始查询
_POST)) {
//initial query
query =选择last_name,first_name,middle_initial FROM admin其中username =:user;
query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
query_params = array(':user'=>
query_params = array(':user' =>
这篇关于我需要将值传递给textview。任何人都可以帮助我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!