使用意图从类向MainActivity发送数据时出错

时间:2019-02-28 16:57:32

标签: android

在我的MainActivity中,我需要知道一个布尔型变量的状态以隐藏或放置图标可见,但是此变量是在另一个名为TcpClient的类中生成的,该类被MainActivity多次调用,我试图使用意图从TcpClient类发送此变量,但是我有错误。

这是我的MainActivity代码:

public class MainActivity extends AppCompatActivity implements 
NavigationView.OnNavigationItemSelectedListener {
private TcpClient mTcpClient;
public boolean statusWIFI = false;
.
.
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
    @Override
    protected TcpClient doInBackground(String... message) {
        mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {           //we create a TCPClient object and
                publishProgress(message);                   //this method calls the onProgressUpdate
            }
        });
        mTcpClient.run();
        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //arrayList.add("RX: " + values[0]);                 //in the 
    arrayList we add the messaged received from server
        mDumpTextView.append( values[0] );
        mDumpTextView.append( "\n" );
        mScrollView.smoothScrollTo( 0, mDumpTextView.getBottom() );

        mAdapter.notifyDataSetChanged();                   // notify the 
    adapter that the data set has changed. This means that new message 
    received
        // from server was added to the list
    }

}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

MenuItem IconWIFI = menu.findItem(R.id.bt1_wifi);

Intent intent = getIntent();
Bundle bundle = null;
bundle = getIntent().getExtras();

if (bundle !=null) {
    statusWIFI = bundle.getBoolean( "mstatusWIFI");
}

if (statusWIFI == true){
    IconUsbON.setVisible(true);
}else{
    IconUsbON.setVisible(false);
}

return true;
}

这是我的TcpClient类的代码:

public class TcpClient {
private Boolean statusWIFIX = false;
.
.
public void stopClient() {

statusWIFIX = false;
Intent intent = new Intent( this, MainActivity.class );
intent.putExtra( "mstatusWIFI", statusWIFIX );
startActivityForResult( intent, 0 );

sendMessage(Constants.CLOSED_CONNECTION+": " + Modelox);                
// send message that we are closing the connection
mRun = false;
if (mBufferOut != null) {
    mBufferOut.flush();
    mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}

这是错误;有人可以告诉我该如何纠正

enter image description here

2 个答案:

答案 0 :(得分:0)

您必须必须将活动上下文传递给Intent构造函数。 TCPClient似乎没有任何活动或服务。

答案 1 :(得分:0)

我没有看到mTcpClient的任何初始化,您需要像这样初始化它:

mTcpClient= TcpClient(); 

,如果您的变量在TcpClient类中,则可以通过mTcpClient.statusWIFIX

进行访问

您还需要像这样将statusWIFIX范围公开:

public Boolean statusWIFIX = false;

在您的TcpClient班上。

您还可以通过意图发送数据,但是仅用于访问状态WIFIX以再次启动活动不是一个好方法。