错误"只有创建视图层次可以触摸其观点和QUOT原线;在Android中 [英] Error "Only the original thread that created a view hierarchy can touch its views" in Android
问题描述
我创建了使用Android和PHP登录一个简单的应用程序,但我得到一个错误,谁能帮助我?我试图让Android的之间的关系,为客户端和PHP / MySQL作为服务器端,但还没有成功地得到响应。
AndroidLogin.java
包com.sencide;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;
进口org.apache.http.protocol.HTTP;
进口org.apache.http.util.EntityUtils;进口android.os.Bundle;
进口android.os.StrictMode;
进口android.app.Activity;
进口android.util.Log;
进口android.view.Menu;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.TextView;公共类AndroidLogin扩展活动实现OnClickListener {
OK按钮,背部,退出;
TextView的结果;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
StrictMode.setThreadPolicy(政策); //登录按钮点击
OK =(按钮)findViewById(R.id.btn_login);
ok.setOnClickListener(本); 结果=(的TextView)findViewById(R.id.lbl_result); } 公共无效postLoginData(){
//创建一个新的HttpClient和邮政头
HttpClient的HttpClient的=新DefaultHttpClient();
Log.e(性反应 - >中,后的HttpClient);
/ *如果login.php中的用户名和密码,等于saranga返回true * /
HttpPost httppost =新HttpPost(http://10.0.2.2/login.php);
Log.e(性反应 - >中,后httppost);
尝试{
//添加用户名和密码
EditText上的uname =(EditText上)findViewById(R.id.txt_username);
字符串username = uname.getText()的toString()。 的EditText PWORD =(EditText上)findViewById(R.id.txt_password);
。字符串密码= pword.getText()的toString(); 清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
nameValuePairs.add(新BasicNameValuePair(用户名的用户名));
nameValuePairs.add(新BasicNameValuePair(密码,密码));
httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
Log.e(性反应 - >中,使用列表名称对之后); //执行HTTP POST请求
Log.w(SENCIDE,执行HTTP POST请求);
HTT presponse响应= httpclient.execute(httppost);
Log.e(性反应 - >中后,再执行HTTP响应);
//字符串str = inputStreamToString(response.getEntity()的getContent()。)的toString()。
字符串str = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
//Log.w(\"SENCIDE,STR); Log.e(性反应 - >中,+ STR); 如果(str.toString()。equalsIgnoreCase(真))
{
Log.w(SENCIDE,TRUE);
result.setText(登录成功);
}其他
{
Log.w(SENCIDE,假);
result.setText(STR);
} }赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
}
} 私人的StringBuilder inputStreamToString(InputStream为){
串线=;
StringBuilder的总=新的StringBuilder();
//环绕式InputStream的一个BufferedReader
RD的BufferedReader =新的BufferedReader(新的InputStreamReader(是));
//读取响应,直到结束
尝试{
而((行= rd.readLine())!= NULL){
total.append(线);
}
}赶上(IOException异常五){
e.printStackTrace();
}
//返回满弦
总回报;
} / *如果login.php中的用户名和密码,等于test1的*返回true /
@覆盖
公共无效的onClick(查看视图){
// TODO自动生成方法存根
最后弦乐resultText;
如果(str.toString()。equalsIgnoreCase(真)){
resultText =登录成功;
}其他{
resultText =海峡;
} 如果(查看== OK){
线程t =新的Thread(){
公共无效的run(){
postLoginData(); result.post(新的Runnable(){
公共无效的run(){
result.setText(resultText);
}
});
}
};
t.start(); }
}}
登录猫
04-04 19:04:20.504:E /性反应 - >(457):HttpClient的后
04-04 19:04:20.517:E /性反应 - >(457):后httppost
04-04 19:04:20.544:E /性反应 - >(457):使用列表名称对后
04-04 19:04:20.544:W / SENCIDE(457):执行HTTP POST请求
04-04 19:04:20.824:E /性反应 - >(457):执行HTTP响应之后
04-04 19:04:20.834:E /性反应 - >(457):真
04-04 19:04:20.834:W / SENCIDE(457):TRUE
04-04 19:04:20.844:W / dalvikvm(457):主题ID = 9:螺纹未捕获的异常(组= 0x40015560)退出
04-04 19:04:20.912:E / AndroidRuntime(457):致命异常:螺纹10
04-04 19:04:20.912:E / AndroidRuntime(457):$ android.view.ViewRoot CalledFromWrongThreadException:只有创建视图层次可以触摸其观点原来的线程。
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.ViewRoot.checkThread(ViewRoot.java:2932)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.ViewRoot.requestLayout(ViewRoot.java:629)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.widget.TextView.checkForRelayout(TextView.java:5521)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.widget.TextView.setText(TextView.java:2724)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.widget.TextView.setText(TextView.java:2592)
04-04 19:04:20.912:E / AndroidRuntime(457):在android.widget.TextView.setText(TextView.java:2567)
04-04 19:04:20.912:E / AndroidRuntime(457):在com.sencide.AndroidLogin $ 1.run(AndroidLogin.java:136)
04-04 19:04:23.464:I /流程(457):发送信号。 PID:457 SIG:9
PHP code
< PHP
$主机=localhost的; //主机名
$用户名=根; // MySQL用户名
$密码=根; // mysql的密码
$ DB_NAME =TESTLOGIN; //数据库名称
$ tbl_name表=成员; //表名//连接到服务器,然后选择DATABSE。
mysql_connect($主机,$用户名,密码$)或死亡(无法连接);
mysql_select_db($ DB_NAME)或死亡(不能选择DB);//用户名和密码形式发送
$名为myusername = $ _ POST [用户名];
$输入mypassword = $ _ POST ['密码'];//为了保护MySQL的注入
$名为myusername =的stripslashes($名为myusername);
$输入mypassword =的stripslashes($输入mypassword);
$名为myusername = mysql_real_escape_string($名为myusername);
$输入mypassword = mysql_real_escape_string($输入mypassword);$ SQL =SELECT * FROM $ tbl_name表其中username ='$名为myusername'和密码= $输入mypassword';
$结果= mysql_query($的SQL);// Mysql_num_row计数表行
$数= mysql_num_rows($结果);//如果结果匹配$名为myUsername,$输入mypassword,表行必须是1排
如果($计数== 1){
回声真;
}
其他{
回声登录失败;
}
?>
好吧,我做了一些修改,以您的code
它仍然是丑陋的,需要大量的重构
但告诉我,如果它引发任何异常。
编辑:
新增你的用户名
和密码
传递给请求
作为参数传递给你的 postLoginData(密码字符串,字符串用户名)
方法。
这应该做到这一点。
进口java.io.IOException异常;
进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;
进口org.apache.http.protocol.HTTP;
进口org.apache.http.util.EntityUtils;进口android.os.Bundle;
进口android.os.StrictMode;
进口android.app.Activity;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.TextView;公共类AndroidLogin扩展活动实现OnClickListener {
OK按钮,背部,退出;
TextView的结果;
EditText上的uname;
的EditText PWORD; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
StrictMode.ThreadPolicy政策=
。新StrictMode.ThreadPolicy.Builder()permitAll()建();
StrictMode.setThreadPolicy(政策); //登录按钮点击
OK =(按钮)findViewById(R.id.btn_login);
ok.setOnClickListener(本);
的uname =(EditText上)findViewById(R.id.txt_username);
PWORD =(EditText上)findViewById(R.id.txt_password);
结果=(的TextView)findViewById(R.id.lbl_result);
} @覆盖
公共无效的onClick(查看视图){
// TODO自动生成方法存根
最后弦乐resultText; 。最终的字符串username = uname.getText()的toString();
。最终的字符串密码= pword.getText()的toString();
如果(查看== OK){
线程t =新的Thread(){ 公共无效的run(){
postLoginData(用户名,密码);
}
};
t.start(); }
} 私人无效postLoginData(字符串用户名,字符串密码){ 尝试{
//创建一个新的HttpClient和邮政头
HttpClient的HttpClient的=新DefaultHttpClient();
Log.e(回应 - >中之后的HttpClient);
/ *如果login.php中的用户名和密码,等于saranga返回true * /
HttpPost httppost =新HttpPost(http://10.0.2.2/login.php);
Log.e(回应 - >中之后httppost);
清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
nameValuePairs.add(新BasicNameValuePair(用户名的用户名));
nameValuePairs.add(新BasicNameValuePair(密码,密码)); httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
Log.e(性反应 - >中,使用列表名称对之后); //执行HTTP POST请求
Log.w(SENCIDE,执行HTTP POST请求);
HTT presponse响应= httpclient.execute(httppost);
Log.e(性反应 - >中后,再执行HTTP响应);
字符串str = EntityUtils.toString(response.getEntity(),HTTP.UTF_8); 如果(str.toString()。equalsIgnoreCase(真)){ runOnUiThread(新的Runnable(){
公共无效的run(){
result.setText(登录成功); }
});
}其他{
runOnUiThread(新的Runnable(){
公共无效的run(){
result.setText(咄); }
});
} }赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} }
}
I am creating a simple app for login using Android and PHP but I get an error, can anyone help me? I am trying to make a relation between the Android as the client side and PHP/MySQL as the server side but still have not get the response successfully.
AndroidLogin.java
package com.sencide;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidLogin extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Login button clicked
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.lbl_result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
Log.e("Responce-->","after httpclient");
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://10.0.2.2/login.php");
Log.e("Responce-->","after httppost");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("Responce-->","after using the list name pair");
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
Log.e("Responce-->","after execute the http response");
// String str = inputStreamToString(response.getEntity().getContent()).toString();
String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
//Log.w("SENCIDE", str);
Log.e("Responce-->",""+str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
result.setText("Login successful");
}else
{
Log.w("SENCIDE", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
/* login.php returns true if username and password is equal to test1 */
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
final String resultText;
if(str.toString().equalsIgnoreCase("true")) {
resultText = "Login successful";
}else {
resultText = str;
}
if(view == ok){
Thread t = new Thread(){
public void run(){
postLoginData();
result.post(new Runnable() {
public void run() {
result.setText(resultText);
}
});
}
};
t.start();
}
}
}
log cat
04-04 19:04:20.504: E/Responce-->(457): after httpclient
04-04 19:04:20.517: E/Responce-->(457): after httppost
04-04 19:04:20.544: E/Responce-->(457): after using the list name pair
04-04 19:04:20.544: W/SENCIDE(457): Execute HTTP Post Request
04-04 19:04:20.824: E/Responce-->(457): after execute the http response
04-04 19:04:20.834: E/Responce-->(457): true
04-04 19:04:20.834: W/SENCIDE(457): TRUE
04-04 19:04:20.844: W/dalvikvm(457): threadid=9: thread exiting with uncaught exception (group=0x40015560)
04-04 19:04:20.912: E/AndroidRuntime(457): FATAL EXCEPTION: Thread-10
04-04 19:04:20.912: E/AndroidRuntime(457): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.ViewRoot.requestLayout(ViewRoot.java:629)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.view.View.requestLayout(View.java:8267)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.widget.TextView.checkForRelayout(TextView.java:5521)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.widget.TextView.setText(TextView.java:2724)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.widget.TextView.setText(TextView.java:2592)
04-04 19:04:20.912: E/AndroidRuntime(457): at android.widget.TextView.setText(TextView.java:2567)
04-04 19:04:20.912: E/AndroidRuntime(457): at com.sencide.AndroidLogin$1.run(AndroidLogin.java:136)
04-04 19:04:23.464: I/Process(457): Sending signal. PID: 457 SIG: 9
php code
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="testlogin"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
echo "true";
}
else {
echo "Login Failed";
}
?>
OK I made some modifications to your code it's still ugly and requires lots of refactoring but tell me if it throws any exceptions.
EDIT:
Added your username
and password
passing to the request
as parameters to your postLoginData(String password,String username)
method.
That should do it.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidLogin extends Activity implements OnClickListener {
Button ok, back, exit;
TextView result;
EditText uname;
EditText pword;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
uname = (EditText) findViewById(R.id.txt_username);
pword = (EditText) findViewById(R.id.txt_password);
result = (TextView) findViewById(R.id.lbl_result);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
final String resultText;
final String username = uname.getText().toString();
final String password = pword.getText().toString();
if (view == ok) {
Thread t = new Thread() {
public void run() {
postLoginData(username,password);
}
};
t.start();
}
}
private void postLoginData(String username,String password) {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
Log.e("Response-->", "after httpclient");
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://10.0.2.2/login.php");
Log.e("Response-->", "after httppost");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("Responce-->", "after using the list name pair");
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
Log.e("Responce-->", "after execute the http response");
String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
if (str.toString().equalsIgnoreCase("true")) {
runOnUiThread(new Runnable() {
public void run() {
result.setText("Login Successful");
}
});
} else {
runOnUiThread(new Runnable() {
public void run() {
result.setText("Duh");
}
});
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这篇关于错误&QUOT;只有创建视图层次可以触摸其观点和QUOT原线;在Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!