因此,我需要在Android上开发一个Client应用程序,该应用程序将与服务器通信并使用OPCUA协议访问服务器的地址空间。
我有一个如下所示的异步任务,它构成了连接。
我无法在主要活动中访问客户端的属性。给我一个空指针异常。请引导我。
PS:OOP和Android Ofcourse的初学者。
主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectButton = findViewById(R.id.connectButton);
textView = findViewById(R.id.textView);
ConnectAndReadTask task = new ConnectAndReadTask();
task.execute();
try{
System.out.println("NSI" +client.getAddressSpace().getNamespaceTable().getIndex("opc.tcp://192.168.4.1:4840")); //getting a nullpointer here
}
catch (Exception e)
{
e.printStackTrace();
}
异步任务
public class ConnectAndReadTask extends AsyncTask<Void, Void, String> {
public ConnectAndReadTask() {
}
@Override
public String doInBackground(Void... params) {
UaClient client = null;
String result = null;
try {
System.out.println("Connecting...");
client = new UaClient("opc.tcp://192.168.4.1:4840");
//System.out.println("Connected");
ApplicationDescription appDescription = new ApplicationDescription();
appDescription.setApplicationName(new LocalizedText("SimpleAndroidClient",
Locale.ENGLISH));
String android_id = Settings.Secure.getString(
getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
appDescription.setApplicationUri("urn:" + android_id + ":UA:SimpleAndroidClient");
appDescription.setProductUri("urn:prosysopc.com:UA:SimpleAndroidClient");
appDescription.setApplicationType(ApplicationType.Client);
PkiFileBasedCertificateValidator validator = new PkiFileBasedCertificateValidator(
getFilesDir().getPath() + "/PKI/CA");
validator.setValidationListener(new CertificateValidationListener() {
@Override
public PkiFileBasedCertificateValidator.ValidationResult onValidate(
Cert cert, ApplicationDescription applicationDescription,
EnumSet<PkiFileBasedCertificateValidator.CertificateCheck> enumSet) {
return PkiFileBasedCertificateValidator.ValidationResult.AcceptPermanently;
}
});
client.setCertificateValidator(validator);
ApplicationIdentity identity = ApplicationIdentity.loadOrCreateCertificate(
appDescription, "Sample Organisation", "opcua",
new File(validator.getBaseDir(), "private"), true);
identity.setApplicationDescription(appDescription);
client.setApplicationIdentity(identity);
client.setTimeout(60000);
client.setSecurityMode(SecurityMode.NONE);
client.setUserIdentity(new UserIdentity());
System.out.println("Lets connect");
client.connect();
} catch (Exception e) {
result = e.toString();
}
// return result;
return client;
textView.setText(s);
protected void onPostExecute(UaClient client) {
textView.setText(client.toString());
}
}
}