简体   繁体   English

如何将EditText作为Json的输入发送到Java服务器?

[英]How to send input from EditText as Json to Java server?

Recently I have done my first client-server project. 最近,我完成了我的第一个客户端-服务器项目。 It is cool actually but i have a little problem. 其实很酷,但我有一个小问题。 There is no message but I wanted to have JSON with name and password full field. 没有消息,但我想使用名称和密码完整字段的JSON。 I am using GSON jar library for JsonObject . 我正在为JsonObject使用GSON jar库。

My Server 我的服务器

public class Server extends Thread {

private static final int port = 8607;
protected static String server_IP;

public static void main(String[] args)  {


    try {
        InetAddress iAddress = InetAddress.getLocalHost();
        server_IP = iAddress.getHostAddress();
        System.out.println("Server IP : " + server_IP);

    } catch (UnknownHostException e){

    }

    try {
        //Server
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server has started");

        //Accepting client
        System.out.println("Waiting");
        Socket socket = serverSocket.accept();
        System.out.println("Client has been added");

        //Send message to client
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("Connection accepted");
        bw.newLine();
        bw.flush();

        //receive json from client
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String json_string = br.readLine();
        JsonParser jsonParser = new JsonParser();
        JsonObject user = jsonParser.parse(json_string).getAsJsonObject();

        System.out.println("JSON: " +user.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }

 }
}

My server console 我的服务器控制台

Server IP : 192.168.123.2
Server has started
Waiting
Client has been added
JSON: {"name":""}

Process finished with exit code 0

And my Android app 还有我的Android应用

public class MainActivity extends AppCompatActivity {

    private EditText editName;
    private EditText editPassword;
    private Button send_todata;
    private ProgressBar progressBar;
    private Button category;
    private TextView output;
    private Socket socket;
    private String name;
    private String password;
    private static final String debug = "debug";
    private static final String info = "INFO";
    protected static String server_IP = "192.168.0.101";
    protected static final int server_Port = 8607;
    private static final String result = "";

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

        editName = (EditText) findViewById(R.id.user_name);
        editPassword = (EditText) findViewById(R.id.user_password);
        send_todata = (Button) findViewById(R.id.button_submit);
        progressBar = (ProgressBar) findViewById(R.id.login_progress);
        output = (TextView) findViewById(R.id.output);
        name = editName.getText().toString();
        password = editPassword.getText().toString();

        send_todata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new SendDataToServer().execute(name,password);
            }
        });

        category = (Button) findViewById(R.id.category);
        category.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,Items.class);
                startActivity(intent);
            }
        });
    }

    class SendDataToServer extends AsyncTask<String,Void,Void> {

        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
            output.setText("Connecting ...");
        }

        @Override
        protected Void doInBackground(final String... data) {

            final Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        Log.i(debug,"Attempt to connect to server");

                        socket = new Socket(server_IP,server_Port);
                        Log.i(debug,"Connection established");

                        JsonObject user =  new JsonObject();

                        user.addProperty("name", data[0]);
                        user.addProperty("name", data[1]);

                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        bw.write(user.toString());
                        bw.newLine();
                        bw.flush();
                        Log.i(info,"JSON has sent");

                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        br.readLine();
                        Log.i(info,br.readLine());

                    } catch (IOException e) {
                        Log.e(debug,"Failed");
                    }

                }
            });thread.start();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            progressBar.setVisibility(View.GONE);
            output.setText("");
        }
    }
}

Thanks. 谢谢。

Your problem is here: 您的问题在这里:

name = editName.getText().toString();
password = editPassword.getText().toString();

You are already assigning the name and password variables in the onCreate() method, when you didn't yet have the chance to input any text into the fields. 当您还没有机会在字段中输入任何文本时,您已经在onCreate()方法中分配了namepassword变量。 They will always be empty. 他们将永远是空的。

What you should do is move those 2 lines inside the onClick(View) method of the click listener. 您应该做的是将这两行移动到点击监听器的onClick(View)方法中。 Like so: 像这样:

send_todata.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        name = editName.getText().toString();
        password = editPassword.getText().toString();

        new SendDataToServer().execute(name, password);
    }
});

This way, you will assign the 2 variables, name and password only when you click the button. 这样,仅在单击按钮时才分配两个变量,即namepassword At that point you will probably have something inside the 2 input fields. 届时,您可能会在2个输入字段中包含一些内容。

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

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