如何从EditText框中获取IP地址?

时间:2021-01-27 07:09:09

Hi I am quite new to android and i'm sorry if its a silly question.

嗨,我对Android很新,如果这是一个愚蠢的问题,我很抱歉。

How do I use an EditText box instead of having the IP address hard coded. As you can see from the code below I have to put the computers ip address that im connecting to in, what I want to do is make it so I use an EditText box instead such as:

如何使用EditText框而不是硬编码的IP地址。正如你从下面的代码中看到的那样,我必须把我连接的计算机ip地址放进去,我想做的就是这样做,所以我使用的是EditText框,例如:

String input= edittextIP.getText().toString();

But i could not get this to work. Any help would be much appreciated.

但我无法让这个工作。任何帮助将非常感激。

Thanks

public class Client {


private String serverMessage;
public final String SERVERIP = "100.100.100.61"; //computer IP address
public final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;



PrintWriter out;
BufferedReader in;


/**
 *  Constructor of the class. OnMessagedReceived listens for the messages received from server
 */
public Client(OnMessageReceived listener) {
    mMessageListener = listener;
}

/**
 * Sends the message entered by client to the server
 * @param message text entered by client
 */
public void sendMessage(String message){
    if (out != null && !out.checkError()) {
        out.println(message);
        out.flush();
    }
}

public void stopClient(){
    mRun = false;
}

public void run() {

    mRun = true;

    try {

        InetAddress serverAddr = InetAddress.getByName(SERVERIP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVERPORT);
        try {

            //send the message to the server
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            Log.e("TCP Client", "C: Sent.");

            Log.e("TCP Client", "C: Done.");

            //receive the message which the server sends back
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //in this while the client listens for the messages sent by the server
            while (mRun) {
                serverMessage = in.readLine();

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(serverMessage);
                }
                serverMessage = null;

            }


            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");


        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. I can't reconnect to this socket
            // after it is closed, which means a new socket has to be created.
            socket.close();
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}


/// public EditText findViewByid(int edittextIP) {   <--- this was previous try please 
///                                                          disregard this
///     
///     return null;
/// }


public interface OnMessageReceived {
    public void messageReceived(String message);
}
}

This is my activity below:

这是我的活动如下:

public class MyActivity extends Activity
{
private ListView mList;
private ArrayList<String> arrayList;
private Adapter mAdapter;
private Client mTcpClient;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    arrayList = new ArrayList<String>();

    final EditText editText = (EditText) findViewById(R.id.editText);
    Button send = (Button)findViewById(R.id.send_button);



    mList = (ListView)findViewById(R.id.list);
    mAdapter = new Adapter(this, arrayList);
    mList.setAdapter(mAdapter);

    // connect to the server
    new connectTask().execute("");


    send.setOnClickListener(new View.OnClickListener()

    {
        public void onClick(View view) {

            String message = editText.getText().toString();


            arrayList.add("c: " + message);

            //sends the message to the server
            if (mTcpClient != null) {
                mTcpClient.sendMessage(message);
            }

            //refresh the list
            mAdapter.notifyDataSetChanged();
            editText.setText("");
        }
    });

}

public class connectTask extends AsyncTask<String,String,Client> {

    @Override
    protected Client doInBackground(String... message) {

        //create a TCPClient object and
        mTcpClient = new Client(new Client.OnMessageReceived() {

            //here the messageReceived is implemented
            public void messageReceived(String message) {

                publishProgress(message);
            }
        });
        mTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        arrayList.add(values[0]);

        mAdapter.notifyDataSetChanged();
    }
}

}

2 个解决方案

#1


0  

You should get the EditText instance from your Activity (the class that extends from Activity), your "findViewById" function has no sense there. "findViewById" is a method inherited from Activity. Then, you could pass the text typed in that EditText from your Activity to your Client instance, for example.

你应该从你的Activity(从Activity扩展的类)中获取EditText实例,你的“findViewById”函数没有意义。 “findViewById”是从Activity继承的方法。然后,您可以将EditText中键入的文本从Activity传递到Client实例。

#2


0  

You missed to cast the value and generated an wrong stub. You need to delete your findViewByid function. Try this code:

您错过了转换值并生成了错误的存根。您需要删除findViewByid函数。试试这段代码:

TextEdit input = (TextEdit)findViewByid(...);

Note that you should pass directly the IP to your class from your activity for example thrue the constructor:

请注意,您应该从您的活动直接将IP传递给您的类,例如thrue构造函数:

public class ConnectTask extends AsyncTask<String,String,Client> {
    private string ip;
    public ConnectTask(String ip) {
        this.ip=ip;
    }
 // ...

There you have the IP in the member variable ip. You can set it like this:

你在成员变量ip中有IP。您可以这样设置:

ConnectTask task = new ConnectTask(input.getText().toString());

#1


0  

You should get the EditText instance from your Activity (the class that extends from Activity), your "findViewById" function has no sense there. "findViewById" is a method inherited from Activity. Then, you could pass the text typed in that EditText from your Activity to your Client instance, for example.

你应该从你的Activity(从Activity扩展的类)中获取EditText实例,你的“findViewById”函数没有意义。 “findViewById”是从Activity继承的方法。然后,您可以将EditText中键入的文本从Activity传递到Client实例。

#2


0  

You missed to cast the value and generated an wrong stub. You need to delete your findViewByid function. Try this code:

您错过了转换值并生成了错误的存根。您需要删除findViewByid函数。试试这段代码:

TextEdit input = (TextEdit)findViewByid(...);

Note that you should pass directly the IP to your class from your activity for example thrue the constructor:

请注意,您应该从您的活动直接将IP传递给您的类,例如thrue构造函数:

public class ConnectTask extends AsyncTask<String,String,Client> {
    private string ip;
    public ConnectTask(String ip) {
        this.ip=ip;
    }
 // ...

There you have the IP in the member variable ip. You can set it like this:

你在成员变量ip中有IP。您可以这样设置:

ConnectTask task = new ConnectTask(input.getText().toString());