Android客户端将输入消息设置为textview

标签 android sockets client

我是 android 和 java 编程的新手,我正在尝试对服务器客户端连接进行编程。

服务器在我的电脑上运行没有问题,客户端在我的安卓智能手机上运行。

我可以从手机向服务器发送消息,但无法从服务器向客户端发送消息。

当我发送此消息时,客户端崩溃并自行关闭。

我在this site上找到了一个类似的客户端并将此客户端的 listView 更改为 textView。进行此更改后,我的问题发生了。我真的希望有人能帮助我解决我的问题。

这是我的 Activity :

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MyActivity extends Activity {

public static final String MY_LOCAL_BROADCAST = "myLocalBroadCast";
public static final String KEY_RESPONSE = "key_response";
public static final String KEY_FIRSTRUN = "first_run";

Button btn;
EditText textOut;
TextView textIn;
TextView problems;
Button send;
private TCPClient myTcpClient;

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

    editText = (EditText)findViewById(R.id.editText);
    textIn = (TextView)findViewById(R.id.textin);
    send = (Button)findViewById(R.id.send_button);

    new ConnectTask(this.getApplicationContext()).execute("");

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

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

            //sends the message to the server
            if (myTcpClient != null) {
                myTcpClient.sendMessage(message);
            }
        }
    });
    if (savedInstanceState==null) {
        new ConnectTask(this.getApplicationContext()).execute("");
    }
    }

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(KEY_FIRSTRUN, false);
    super.onSaveInstanceState(outState);
}

    @Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter(MY_LOCAL_BROADCAST));
}

@Override
protected void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String responseData = intent.getStringExtra(KEY_RESPONSE);
        Toast.makeText(MainActivity.this, responseData, Toast.LENGTH_LONG).show();
    }
};

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


    private Context context;

         public ConnectTask(Context context) {
             this.context = context;
         }

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

        //we create a TCPClient object and
        myTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {

            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {
                //this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        myTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        Intent intent = new Intent(MainActivity.MY_LOCAL_BROADCAST);
        intent.putExtra(MainActivity.KEY_RESPONSE, values);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        textIn.setText(values[0]);
    }
}
}

这是我的 TCPClient 类:

package com.example.sercerclient2zweidreidrei;

import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;


public class TCPClient {

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

PrintWriter out;
BufferedReader in;

/**
 * constructor of the class. OnMessageReceived listens for the messages 
 * received from server
 */
public TCPClient(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 {
        // here you must put your computer's IP address.
        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 send 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. It is not possible to reconnect to this socket
            //after it is closed, which means a new socket instance has to be created.
            socket.close();
        }
    } catch (Exception e) {
        Log.e("TCP", "C:Error", e);
    }
}

/*
 * Declare the interface. The method messageReceived(String message must be
 * implemented in the MyActivity class at on asynckTask doInBackground
 */
public interface OnMessageReceived {
    public void messageReceived(String message);
}
}

终于在这里你可以看到我的 main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MyActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/Textausgabe" />

<EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="34dp"
    android:ems="10" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/send_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/editText"
    android:layout_marginTop="26dp"
    android:text="@string/Senden" />

<TextView
    android:id="@+id/textin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:text="@string/EinkommenderText"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 </RelativeLayout>

和我的 LogCat:

E/TCP Client(548): C: Connecting...

E/TCP Client(548): C: Sent.

E/TCP Client(548): C:Done.

D/AndroidRuntime(548): Shutting down VM

: W/dalvikvm(548): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)

E/AndroidRuntime(548): FATAL EXCEPTION: main

E/AndroidRuntime(548): java.lang.NullPointerException

E/AndroidRuntime(548):at com.example.sercerclient2zweidreidrei.MyActivity$connectTask.onProgressUpdate(MyActivity.java:72)

E/AndroidRuntime(548): at com.example.sercerclient2zweidreidrei.MyActivity$connectTask.onProgressUpdate(MyActivity.java:1)

E/AndroidRuntime(548): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)

E/AndroidRuntime(548): at android.os.Handler.dispatchMessage(Handler.java:99)

最佳答案

出现空指针是因为您的 TextView 等未正确初始化。

您全局声明它们,但初始化未链接到全局的新局部变量。因此全局值仍然为空。

改变MyActivity将是

public class MyActivity extends Activity {

      Button btn;
      EditText textOut;
      TextView textIn;
      TextView problems;
      Button send;
      private TCPClient myTcpClient;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);  
         editText = (EditText) findViewById(R.id.editText);
         textIn = (TextView) findViewById(R.id.textin);
         send = (Button)findViewById(R.id.send_button);

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

send.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

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

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

关于Android客户端将输入消息设置为textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092689/

相关文章:

sockets - 如何查询文件描述符的套接字类型?

sockets - 从 C 套接字读取十六进制缓冲区时出现问题

java - 连接两个客户端套接字

java - 查找 Java 服务器时间和客户端时间

Android 布局 - 不显示 ImageView

java - 访问旧应用程序时 list 合并失败

c++ - 使用 istream 从 boost::asio UDP 套接字中检索 float

java - 开发网络游戏

java - 如何通知当前图层位置变化

android - android 中的后台服务未运行某些设备,如 oppo、vivo 等