我有2个应用。 App1和App2。 App1:编辑文字+按钮 App2:只是一个文本视图。
这是按钮onClick
@Override
public void onClick(View v) {
Intent sendIntent = getPackageManager().getLaunchIntentForPackage("com.example.app2");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
App1应该启动App2设置App2的文本视图
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
text.setText(sharedText);
}
}
}
但我有nullpointerexception。请帮助和thx
答案 0 :(得分:9)
所以你需要从APP1向APP2发送一些数据。
在你的代码中,NullPointer因为你没有通过调用EditText text
来初始化findViewById()
而发生。此外,您可以简化编码。请尝试以下方法:
APP1:
@Override
public void onClick(View v) {
Intent sendIntent = getPackageManager().getLaunchIntentForPackage("com.example.app2");
sendIntent.putExtra("my_text", "This is my text to send.");
startActivity(sendIntent);
}
APP2:
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(EditText)findViewById(R.id.edittext1);// This was missing in your code.
Intent intent = getIntent();
if (intent.hasExtra("my_text")) {
String sharedText = intent.getStringExtra("my_text");
text.setText(sharedText);
}
}