简体   繁体   English

为什么此应用程序中的 Toast 不显示任何内容?

[英]Why Toast in this application does not show anything?

I wrote an application that connect to wamp server ( with a MySQl datatbase that one of its rows in table users have Username="pooriya" and Password="123") This application checks if Username "pooriya" exist then Toast the password and if does not exist Toast "no user"我写了一个连接到 wamp 服务器的应用程序(带有一个 MySQl 数据库,它在表用户中的一行有用户名 =“pooriya”和密码 =“123”)这个应用程序检查用户名“pooriya”是否存在,然后吐司密码,如果不存在 Toast“无用户”

When i run this app on emulator , it should Toast "123", but empty Toast is shown .当我在模拟器上运行这个应用程序时,它应该 Toast“123”,但显示空的 Toast。 Why ?为什么 ? Even when i change the User to a not existing Username , like "poori" , again empty Toast is shown .即使我将用户更改为不存在的用户名,例如“poori”,也会再次显示空 Toast。 Why ?为什么 ? database name is "note_test_2_db" And when i enter the address " http://127.0.0.1:8080/mysite1/index.php " in my browser , it shows "no user" , then i guess that the php file works correctly and the problem is in my android code .数据库名称是“note_test_2_db”当我在浏览器中输入地址“ http://127.0.0.1:8080/mysite1/index.php ”时,它显示“没有用户”,那么我猜php文件工作正常,并且问题出在我的 android 代码中。 Thanks谢谢

package com.example.GetDataFromServer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyActivity extends Activity {

    public static String res = "";
    Button btn;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.button);
        new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
            }
        });

    }
}




package com.example.GetDataFromServer;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * Created with IntelliJ IDEA.
 * User: Farid
 * Date: 3/15/19
 * Time: 4:09 PM
 * To change this template use File | Settings | File Templates.
 */
public class getdata extends AsyncTask {
    private String Link = "";
    private String User = "";

    public getdata(String link, String user) {
        Link = link;
        User = user;
    }

    @Override
    protected String doInBackground(Object... objects) {
        try {
            String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");

            URL mylink  = new URL(Link);
            URLConnection connect = mylink.openConnection();

            connect.setDoOutput(true);
            OutputStreamWriter wr= new OutputStreamWriter(connect.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
            StringBuilder sb = new StringBuilder();

            String line = null;
                while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            MyActivity.res = sb.toString();

        } catch (Exception e) {
        }

        return "";  //To change body of implemented methods use File | Settings | File Templates.
    }
}




     $con=mysql_connect("localhost","root","");
        mysql_select_db("note_test_2_db",$con);
        $user=$_POST['username'];
        $sqlQ="select * from users where Username='$user'";
        $result= mysql_Query($sqlQ);
        $row=mysql_fetch_array($result);
        if($row[0]){
            print $row[1];
        }
        else{
            print "no user";
        }
        mysql_close($con);

Problem: It seems your code to show Toast is incorrect.问题:您显示Toast的代码似乎不正确。

new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
    }
});

When the first line is executed, the app will start the AsyncTask which connects to your server to get the response ( "123" or "No User" ).执行第一行时,应用程序将启动连接到您的服务器的AsyncTask以获取响应( "123""No User" )。

If you click on the button btn before the AsyncTask completed, at this time, the value of res is "" , that why you always get empty Toast .如果你在AsyncTask完成之前点击按钮btn ,此时res值为"" ,这就是为什么你总是得到空的Toast

Solution: You can do the following steps解决方法:您可以按照以下步骤进行

Step 1: Because getdata is a separate class, so you need to define an interface to pass data ( "123" or "No User" or any value) back to MyActivity .第 1 步:因为getdata是一个单独的类,所以您需要定义一个接口来将数据( "123""No User"或任何值) MyActivityMyActivity

public interface OnDataListener {
    void onData(String result);
}

Step 2: Modify getdata class第二步:修改getdata

public class getdata extends AsyncTask<Object, Void, String> {
    private String Link = "";
    private String User = "";
    private WeakReference<OnDataListener> mListener;

    public getdata(String link, String user, OnDataListener listener) {
        Link = link;
        User = user;
        mListener = new WeakReference<>(listener);
    }

    @Override
    protected String doInBackground(Object... objects) {
        try {
            String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");

            URL mylink = new URL(Link);
            URLConnection connect = mylink.openConnection();

            connect.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // This string will pass as param of onPostExecute method.
            return sb.toString(); // Will return "123" or "No User" if there is no exception occurs.
        } catch (Exception e) {
        }

        // If your app reach this line, it means there is an exception occurs, using a unique string for debugging.
        // This string will pass as param of onPostExecute method
        return "An exception has been caught!!!";
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // Pass the result back to MyActivity's onData method.
        if (mListener != null && mListener.get() != null) {
            mListener.get().onData(result);
        }
    }
}

Step 3: Let MyActivity implements OnDataListener interface.第三步:MyActivity实现OnDataListener接口。

public class MyActivity extends AppCompatActivity implements OnDataListener {

    public static String res = "";
    Button btn;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.button);
        new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya", this).execute();

        // TODO: Comment-out this code
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
//            }
//        });
    }

    @Override
    public void onData(String result) {
        // result is passed from the AsyncTask's onPostExecute method.
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }
}

Note: Because you do not use any loading indicator while connecting to the server, so you need to wait a few seconds to see the Toast on the screen.注意:因为您在连接服务器时没有使用任何加载指示器,所以您需要等待几秒钟才能在屏幕上看到 Toast。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM