簡體   English   中英

如何從EditText框中獲取IP地址?

[英]How do I get an IP address from an EditText box?

嗨,我是android的新手,很抱歉,這是一個愚蠢的問題。

如何使用EditText框而不是對IP地址進行硬編碼。 從下面的代碼中可以看到,我必須將即時通訊連接到的計算機IP地址放入其中,我想要做的就是創建它,因此我改用EditText框,例如:

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

但是我無法使它工作。 任何幫助將非常感激。

謝謝

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);
}
}

這是我的活動如下:

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();
    }
}

}

您錯過了轉換值並生成了錯誤的存根。 您需要刪除findViewByid函數。 試試這個代碼:

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

請注意,您應該通過活動將IP直接傳遞給類,例如通過構造函數:

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

在那里,成員變量ip中有IP。 您可以這樣設置:

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

您應該從Activity(從Activity擴展的類)獲取EditText實例,您的“ findViewById”函數在那里沒有意義。 “ findViewById”是從Activity繼承的方法。 然后,例如,您可以將在該EditText中鍵入的文本從Activity傳遞到Client實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM