【问题标题】:Http Request inside an AsyncTask AndroidAsyncTask Android 中的 Http 请求
【发布时间】:2013-11-22 13:46:18
【问题描述】:

我正在尝试制作一个应用程序,该应用程序在应用程序中获取用户名和密码并使用 http 请求将它们发送到 mysql 数据库,如果用户存在,则在检查数据库后,我看到 textview 中显示的文本说应用程序“正确的用户名和密码”,如果它不存在,我会看到显示文本“用户名或密码不正确” 我既看不到正确也看不到不正确单击按钮登录后我什么也看不到

Logindb 类

    public class Logindb extends Activity {
    Button login;
    EditText u, p;
    TextView res;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logindb);

        login = (Button) findViewById(R.id.login);
        u = (EditText) findViewById(R.id.u);
        p = (EditText) findViewById(R.id.p);
        res = (TextView) findViewById(R.id.res);
        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new MyAsyncTask().execute(u.getText().toString(), p.getText()
                        .toString());
            }
        });
    }

    private class MyAsyncTask extends AsyncTask<String, Integer, Double> {
        @Override
        protected Double doInBackground(String... params) {
            postData(params[0], params[1]);
            return null;
        }

        protected void onPostExecute(Double result) {
            Toast.makeText(getApplicationContext(), "command sent",
                    Toast.LENGTH_LONG).show();
        }

        protected void onProgressUpdate(Integer... progress) {}

        public void postData(String a, String b) {
            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("username", a));
            postParameters.add(new BasicNameValuePair("password", b));

            String response = null;
            try {
                response = CustomHttpClient.executeHttpPost(
                        "http://192.168.1.11/new/check.php", postParameters);
                String result = response.toString();
                result = result.replaceAll("\\s+", "");
                if (!result.equals("0")) {
                    res.setText("A Correct Username and Password");
                }
                else
                    res.setText("Incorrect Username or Password");
            } catch (Exception e) {
                res.setText(e.toString());
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.logindb, menu);
        return true;
    }
}

PHP 文件检查.php

     <?php
     $un=$_POST['username'];
     $pw=$_POST['password'];
     //connect to the db

     $host="localhost"; // Host name 
     $user="root"; // Mysql username 
     $pswd="123"; // Mysql password 
     $db="pet_home"; // Database name 
     $tbl_name="users"; // Table name

    $conn = mysql_connect($host, $user, $pswd);
    mysql_select_db($db, $conn);
    //run the query to search for the username and password the match
      $query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";

$result = mysql_query($query) or die("Unable to verify user because : ".mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
echo mysql_result($result,0);  // for correct login response
else
 echo 0; // for incorrect login response
 ?>

logindb.xml `

     <EditText
     android:id="@+id/u"
     android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="56dp"
    android:ems="10" />

      <EditText
    android:id="@+id/p"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/u"
    android:layout_below="@+id/u"
    android:layout_marginTop="22dp"
    android:ems="10"
    android:inputType="textPassword" />

    <Button
    android:id="@+id/login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/p"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="67dp"
    android:text="Login" />

    <TextView
    android:id="@+id/res"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/login"
    android:layout_below="@+id/p"
    android:layout_marginTop="27dp"
    android:text="OK"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textColor="@android:color/black" />

     </RelativeLayout>`

【问题讨论】:

    标签: php android mysql android-asynctask httprequest


    【解决方案1】:

    它不起作用,因为您正在修改 doInBackground 中的 TextView。您的所有视觉修改都必须在您的onPostExecute 中调用 所以这里你需要做的是从postData返回字符串结果,并将以下代码移动到你的onPostExecute中:

      if (!result.equals("0")) {
        //  Intent in = new Intent(Logindb.this, Welcome.class);
        // LoadPreferences();
        res.setText("A Correct Username and Password");
        //startActivity(in);
      }
      else
         res.setText("Incorrect Username or Password");
    

    【讨论】:

      【解决方案2】:

      我对这项工作感到惊讶并且没有崩溃,您正在尝试从 doInBackground 访问 UI(通过在 postData 中调用 res.setText),这是不可能的。您应该在 doInBackground 中返回一个布尔值,并据此在 onPostExecute 中相应地更改 TextViews。

      使用它作为类定义:

      private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>
      

      然后在公共的末尾 boolean postData(String a,String b) :

      return result.equals("0")
      

      在 doInBackground 中:

      boolean success = postData(params[0],params[1]);
      return success;
      

      最后

      protected void onPostExecute(Boolean result){
          // change the text for your TextViews here according to the Boolean result
          if (result){
              res.setText("A Correct Username and Password");
          }else{
              res.setText("Incorrect Username or Password");
          }
          Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
      }
      

      【讨论】:

        【解决方案3】:

        当您执行任何类型的网络操作时,您必须使用线程/异步任务来执行此操作。另一方面,当您必须访问或修改任何 UI 元素时,您必须在 MainThread(UIThread) 中执行此操作。 现在你正在做的是从一个不是 UIThread 的线程内部调用 res.setText() 。 AsyncTask 由几个方法组成,其中一些方法在 UIThread 中运行,例如 onPostExecute、onProgressUpdate .. 但 doInBackground 不在 UIThread 中运行,这就是您面临这个问题的原因。

        为了解决您的问题,您现在可以遵循其他答案,因为他们建议实际上应该是处理此问题的方法。在这种情况下,您必须调整您的代码才能像这样工作。

        还有另一种方法可以解决您的问题,但遗憾的是它消除了使用 asynctask 的必要性,因为您没有利用 AsyncTask 的任何优势,您可以只使用 Thread 代替。

        当您从 postData(params[0], params[1]) 内部对任何 UI 元素进行任何修改时,请使用 runOnUiThread。

        像这样:

           runOnUiThread(new Runnable() {
        
                            public void run() {
                                // TODO Auto-generated method stub
                                // do what you have to do
                             res.setText("A Correct Username and Password");
                            }
                    });
        

        试试这个方法应该可以的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-04
          • 1970-01-01
          • 1970-01-01
          • 2012-11-30
          相关资源
          最近更新 更多