Android tcp/ip 读写缓冲区脱离主代码
Posted
技术标签:
【中文标题】Android tcp/ip 读写缓冲区脱离主代码【英文标题】:Android tcp/ip read and write buffer out of main code 【发布时间】:2017-07-10 01:50:27 【问题描述】:我可以通过一个按钮在 Main 布局和 MainActivity java 上读写 TCP/IP 缓冲区。
但不能在不同的片段或不同的布局上这样做。
错误信息是:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void 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;
【问题讨论】:
【参考方案1】:也许在你想要做的片段中
main.send_data_pre();
insted
main.send_data();
如果我很好地理解了您的问题,就像您在 MainActivity 的 OnCreate() 中所做的那样。
【讨论】:
以上是关于Android tcp/ip 读写缓冲区脱离主代码的主要内容,如果未能解决你的问题,请参考以下文章
Java TCP/IP Socket基于NIO的TCP通信(含代码)
Android 逆向代码调试器开发 ( 等待进程状态改变 | detach 脱离进程调试 PTRACE_DETACH | 调试中继续运行程序 PTRACE_CONT )