0
ボタンを使ってメインレイアウトとMainActivity javaにTCP/IPバッファーを読み書きできます。メインのコードからAndroid tcp/ip読み書き可能バッファー
しかし、別の断片やレイアウトではできません。
エラーメッセージは次のとおりです。
のjava.lang.NullPointerException:nullオブジェクト上の仮想メソッド '空com.example.murat.ev.TcpClient.sendMessage(java.lang.String)を' 呼び出すための試み
を参照するマイコード:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public TcpClient mTcpClient;
public Thread send_data;
public Button button;
public byte data[]=new byte[1024];
public DatabaseConstruction db;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseConstruction(getApplicationContext());
new datasync().execute("");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment1=new Fragment1();
fragmentTransaction.replace(R.id.container, fragmen1_layout);
fragmentTransaction.commit();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
send_data_pre();
}
});
}
public class datasync extends AsyncTask<String, String, TcpClient>
{
@Override
protected TcpClient doInBackground(String... message)
{
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived()
{
@Override
//here the messageReceived method is implemented
public void messageReceived(String message)
{
Log.i("Debug","Input message: " + message);
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
@Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
Log.i("onProgressUpdate",values[0]);
}
}
public void send_data_pre()
{
send_data = new Thread(new send_data("hello"));
send_data.start();
}
public class send_data implements Runnable
{
private String message;
public send_data (String message)
{
this.message = message;
}
@Override
public void run()
{
mTcpClient.sendMessage(message);
Log.i("Debug", "mesaj did send");
}
}
}
Fragment1.java
public class Fragment1 extends Fragment {
Button button1;
MainActivity main=new MainActivity();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
button1 =(Button)view.findViewById(R.id.buton_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
main.send_data(); ////THIS HERE IS APP STOP AND ERROR
}
});
return view;
}
}