【问题标题】:how to get RadioButtons Id using HashTable and Key from HasTable如何使用哈希表和哈希表中的键获取单选按钮 ID
【发布时间】:2015-03-22 11:09:07
【问题描述】:

我不太熟悉 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 所以我将能够进一步移动 在此先感谢

【问题讨论】:

    标签: java android hashtable


    【解决方案1】:

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

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

    【讨论】:

    • 感谢代码,但仍然无法获取 RadioButton id
    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 2021-12-30
    • 1970-01-01
    • 2013-03-21
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多