如何使用HashTable获取Radio Buttons Id和来自Hash Table的Key

时间:2015-01-23 11:59:35

标签: java android hashtable

我不熟悉HashTable并使用HashTable动态生成RadioButtons。我可以使用HashTable制作RadioButtons,但无法获取RadioButtons id,而错误显示 java.lang.NullPointerException

这是我使用的代码

Map<String, List<String>> map = new HashMap<String, List<String>>();
    	       
    final   Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); 
    ht.put(1, "sachin"); 
    ht.put(2, "sehwag"); 
    ht.put(3, "dhoni"); 
    final Enumeration<Integer> values = ht.keys(); 
    	        
    	 while (values.hasMoreElements()) 
    	 {  str = (Integer) values.nextElement(); 
    	    System.out.println(str + ":" + ht.get(str));
    	    RadioButton radioButtonView = new RadioButton(this);
            radioButtonView.setText(ht.get(str));
            radioGroup.addView(radioButtonView, p);
          } 
    	        
    	      
    	Button button =(Button)findViewById(R.id.button1);
    	button.setOnClickListener(new OnClickListener() {

    	@Override
    	public void onClick(View arg0) {
    		// TODO Auto-generated method stub
    		// checking Correct Answer
    		RadioButton selectedButton=   (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId()); 
    		String q_ans = selectedButton.getText().toString();
    		int selectedId = radioGroup.getCheckedRadioButtonId();
    	}
    	  });	

这是CatLog

中显示的错误

  FATAL EXCEPTION: main
  java.lang.NullPointerException
 at com.example.testing.HashMaps$1.onClick(HashMaps.java:73)
 at android.view.View.performClick(View.java:3517)
 at android.view.View$PerformClick.run(View.java:14155)
 at android.os.Handler.handleCallback(Handler.java:605)
 at android.os.Handler.dispatchMessage(Handler.java:92)
 at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)

请建议如何从HashTable获取RadioButtons id和Key 所以我将能够进一步发展 在此先感谢

1 个答案:

答案 0 :(得分:1)

您可以使用Key.set()从hashmap获取Key,以获取更多信息,请查看此链接Java Doc示例

&#13;
&#13;
Set<String> keys = h.keySet();
// Loop over String keys.
for (String key : keys) {
   System.out.println(key);
}
&#13;
&#13;
&#13; 你能告诉我你收到RadioButtons id的目的吗? 之后,我可以为您提供最适合您问题的精确解决方案 谢谢