Android:如果 - 否则收到意向
Android: Intent Received if - else
我正在尝试使用 "Database is now updated" 创建返回主页并启动主页屏幕的活动。但是,只有在收到意图时,我才知道如何吐司。但是我不确定如何很好地接收 Intent,这是我的代码。
public class MainActivity extends Activity {
TextView time;
Button viewStock, descriptionSearch;
String lastUpdateStandard = "Last Update Time: ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewStock = (Button) findViewById(R.id.detailSearchButton);
descriptionSearch = (Button) findViewById(R.id.descriptionSearchButton);
time = (TextView) findViewById(R.id.time);
// retrieve time from database to see last update time
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lastUpdateTime = db.getLastUpdate();
time.setText(lastUpdateStandard + lastUpdateTime.get(0));
Intent receivedIntent = getIntent();
/**
*
* What should I write if there is no received Intent?
* Probably I need an if-else statement, but I have no idea how it should be made.
*/
}
不建议您当前想要执行的检查类型,因为所有活动都是由一个意图启动的(Android 是这样设计的),它们总是 return 一个意图。相反,您应该做的是检查用于启动 activity 的意图是否包含您希望提取的数据。您显然只需要意图,因为您需要来自意图的某种数据,对吗?因此,与其检查意图是否被 returned,不如检查从意图中获得的任何额外信息。例如,如果您想使用字符串 "hello" 作为键来提取额外内容,您将使用:
Intent receivedIntent = getIntent();
if(receivedIntent.getStringExtra("hello") != null) {
// Means the intent has the data you expect
} else {
// It does not have the data you expect
// Do some processing here
}
如果你要检查是否收到了一个意图,你总是会得到一个值
我正在尝试使用 "Database is now updated" 创建返回主页并启动主页屏幕的活动。但是,只有在收到意图时,我才知道如何吐司。但是我不确定如何很好地接收 Intent,这是我的代码。
public class MainActivity extends Activity {
TextView time;
Button viewStock, descriptionSearch;
String lastUpdateStandard = "Last Update Time: ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewStock = (Button) findViewById(R.id.detailSearchButton);
descriptionSearch = (Button) findViewById(R.id.descriptionSearchButton);
time = (TextView) findViewById(R.id.time);
// retrieve time from database to see last update time
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lastUpdateTime = db.getLastUpdate();
time.setText(lastUpdateStandard + lastUpdateTime.get(0));
Intent receivedIntent = getIntent();
/**
*
* What should I write if there is no received Intent?
* Probably I need an if-else statement, but I have no idea how it should be made.
*/
}
不建议您当前想要执行的检查类型,因为所有活动都是由一个意图启动的(Android 是这样设计的),它们总是 return 一个意图。相反,您应该做的是检查用于启动 activity 的意图是否包含您希望提取的数据。您显然只需要意图,因为您需要来自意图的某种数据,对吗?因此,与其检查意图是否被 returned,不如检查从意图中获得的任何额外信息。例如,如果您想使用字符串 "hello" 作为键来提取额外内容,您将使用:
Intent receivedIntent = getIntent();
if(receivedIntent.getStringExtra("hello") != null) {
// Means the intent has the data you expect
} else {
// It does not have the data you expect
// Do some processing here
}
如果你要检查是否收到了一个意图,你总是会得到一个值