2015-04-12 73 views
0

我正在嘗試創建指向主頁並激活主頁屏幕的活動,並且「數據庫現在已更新」。但是,我不知道如何在收到意圖時才吐氣。但我不知道如何很好地收到意圖,這裏是我的代碼。Android:意圖收到,如果 - 其他

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. 
    */ 
} 
+0

您的設計是錯誤的。您正在主UI線程中調用數據庫操作。在某些情況下,此操作可能會很長,您的應用程序可能會被操作系統用ANR殺死。 – greywolf82

+0

因此,如果我想從數據庫中獲取某些內容並在頁面啓動時顯示出來,我該怎麼辦?如果這是.MainActivity類? – CHANist

+0

使用單獨的線程,intentservice,asyncTask或任何你想要的,但避免在主線程上執行數據庫操作。在這種情況下,也許一個簡單的asynctask就可以。 – greywolf82

回答

0

那種檢查你目前想要做的所有活動都是由一個意圖(Android的設計這種方式)開始不建議,他們總是會返回一個意圖。你應該做的是檢查用於啓動活動的意圖是否有你想要提取的數據。你顯然只會要求意圖,因爲你需要來自意圖的某種數據正確嗎?因此,不要檢查一個意圖是否被返回,你應該檢查你是否從意圖中獲得了額外的東西。例如,如果你想提取與字符串「你好」作爲關鍵的額外費用,您將使用:

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 
} 

如果你要檢查是否收到意圖,你總是會得到一個值回

+0

這工作完美...謝謝 – CHANist

相關問題