2011-08-05 66 views
0

我是一名學生,也是編程新手。這可能是一個簡單的錯誤,任何人都可以幫我修復它。我必須從一個活動傳遞數組列表到另一個活動。在這個活動中,我有5個單選按鈕RB1,RB2 ....我想將消息[]的內容傳遞給另一個稱爲顯示的活動。創建數組列表並將其從一個活動傳遞給另一個活動

public void onClick(View v) { 
     String[] news; 
     news = new String[5]; 

     news[0] = "bbc"; 
     news[1] = "guardian"; 
     news[2] = "yahoo"; 
     news[3] = "sky"; 
     news[4] = "fox news"; 

     final ArrayList<String> arr = new ArrayList<String>(); 
     if (RB1.isChecked() == true) 
      arr.add(news[0]); 
     if (RB2.isChecked() == true) 
      arr.add(news[1]); 
     if (RB3.isChecked() == true) 
      arr.add(news[2]); 
     if (RB4.isChecked() == true) 
      arr.add(news[3]); 
     if (RB5.isChecked() == true) 
      arr.add(news[4]); 
if (v == Done) 
     { 
      Button done = (Button) findViewById(R.id.DONE); 
      done.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View view) 
       { 
        Intent myIntent = new Intent(Read.this, display.class); 
        myIntent.putExtra("pass",arr); 
        startActivity(myIntent); 
       } 
      }); 
     } 

爲下一個活動的代碼如下所示

    Intent myintent = getIntent(); 
     String[] Array = myintent.getStringArrayExtra("pass"); 

     for (int i = 0; i < Array.length; i++) 
      Log.v(LOG_TAG, "THE website Is :" +Array[i]); 

我在上述兩線歌廳一個顯示java.lang.NullPointerException即

for (int i = 0; i < Array.length; i++) 
       Log.v(LOG_TAG, "THE website Is :" +Array[i]); 

u能請告訴我爲什麼? 在此先感謝

+0

檢查此鏈接:http://stackoverflow.com/questions/4780835/pass-arraylist-from-one-activity-to-other/4781032#4781032 –

+0

看看這個鏈接可能會有所幫助。 .. http://stackoverflow.com/questions/6355787/how-to-pass-arraylist-from-one-activity-to-another – Uttam

+0

對於你的NullPointerException問題,'Array'變量可能是null,這將會發生如果你沒有正確地從之前的活動中傳入。在'String [] Array = ...'之後再次使用log語句檢查它,就像'Log.v(LOG_TAG,「Array is null?」+(Array [i] == null));'。 – Josh

回答

2

首先,一些約定:啓動變量名稱小寫,所以array而不是Array。這會讓你稍後避免混淆。

試試如下,從this螺紋:

Bundle b=new Bundle(); 
b.putStringArray(key, new String[]{value1, value2}); 
Intent i=new Intent(context, Class); 
i.putExtras(b); 

Bundle b=this.getIntent().getExtras(); 
String[] array=b.getStringArray(key); 
1

使用捆綁這樣的:

Bundle bundle = new Bundle(); 
bundle.putStringArray(key, news); 
myIntent.putExtra("pass",bundle); 
startActivity(myIntent); 
+0

非常感謝您的幫助。真的很感激它。恐怕它劑量幫助我解決java.lang.NullPointerException錯誤。你能幫我解決這個錯誤嗎? – Divya

+0

你是否仍然得到java.lang.NullPointerException錯誤..解釋你在哪裏得到它....... –

+0

請看問題的最後部分..同一點..在for循環..可以ü請告訴我,如果我將arraylist傳遞給第二個活動,而不使用包,只使用intent,就像我最初做的那樣,會有什麼不同? – Divya

相關問題