我正在使用Websocket android应用程序。我想用websocket创建Register和Login应用程序。我可以使用websocket android project连接到websocket服务器。我已经创建了在线参考的注册,登录活动。在注册活动中,当我使用"发送"将注册数据存储到服务器时websocketclient Java类I的方法获取 " java.lang.NullPointerException:尝试调用虚方法' void org.java_websocket.client.WebSocketClient.send(java.lang .String)'在我的Log-cat窗口上的空对象引用" 错误。
这是我的主要活动:
package org.asperohgedgetws.a7.hgadgetws;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
public class MainActivity extends Activity implements View.OnClickListener {
Button bLogout;
UserLocalStore userLocalStore;
private WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
connectWebSocket();
}
@Override
protected void onStart() {
super.onStart();
if (authenticate()== true){
displayUserDetails();
} else{
Toast.makeText(getApplicationContext(), "Not Registered User :(", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Login.class));
}
}
private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}
private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bLogout:
startActivity(new Intent(this,Login.class));
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Toast.makeText(getApplicationContext(), "Logout :)", Toast.LENGTH_SHORT).show();
break;
}
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
//mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
mWebSocketClient.send("{\"1512BD002\":\"SO@0\":\"2\"}");
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
//TextView textView = (TextView)findViewById(R.id.messages);
//textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
public void sendMessage(View view) {
// EditText editText = (EditText)findViewById(R.id.message);
// mWebSocketClient.send(editText.getText().toString());
//editText.setText("");
}
}
RegisterActivity
package org.asperohgedgetws.a7.hgadgetws;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.java_websocket.client.WebSocketClient;
public class Register extends AppCompatActivity implements View.OnClickListener {
Button bRegister;
EditText etName, etAge, etUsername, etPassword;
WebSocketClient nwebsocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
// Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show();
String name = etName.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
User user = new User(name, age, username, password);
registerUser(user);
break;
}
}
private void registerUser(User user) {
String strtosend = "";
JSONObject object = new JSONObject();
try {
// Add the id to the json
object.put("name", user.name);
object.put("age", user.age);
object.put("username", user.username);
object.put("password", user.password);
strtosend = object.toString();
} catch (JSONException e) {
// Handle impossible error
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), strtosend, Toast.LENGTH_SHORT).show();
nwebsocket.send("Hi!");
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
}
Logcat输出:
05-27 11:49:54.331 19459-19459/org.asperohgedgetws.a7.hgadgetws E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.asperohgedgetws.a7.hgadgetws, PID: 19459
java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference
at org.asperohgedgetws.a7.hgadgetws.Register.registerUser(Register.java:73)
at org.asperohgedgetws.a7.hgadgetws.Register.onClick(Register.java:51)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
我是否必须在注册活动中的代码下方再次使用?
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
nWebsocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
nWebsocketClient.connect();
}
答案 0 :(得分:1)
问题是,您的nwebsocket
从未初始化,其值为null
,这就是您在尝试执行send
方法时遇到此错误的原因。
您需要在某处初始化它:
nwebsocket = new WebSocketClient(...);
注意:如果您想在WebSocketClient
和MainActivity
活动之间共享Register
的同一个实例,可以在public static
中将其设为MainActivity
public static WebSocketClient mWebSocketClient;
然后从WebSocketClient nwebsocket
移除Register
并改为使用MainActivity.mWebSocketClient
。