无法在现有代码中声明动态按钮

时间:2013-04-03 11:43:19

标签: android

当我在下面的课程中声明gridview时,我会遇到一系列错误。

class LoadAllProducts extends Activity //get call on dynamic btn action 
{
    public void onCreate() {
        System.out.println("I have enterd in external class");
        // ***GridView gridView3 = (GridView) findViewById(R.id.gridview3);***//cant declare getting error  
        ArrayList mButtons3 = new ArrayList(); //to print button dynamically on gridview 
        Button cb3; //=new Button(this); if do so getting error 
        JSONObject json2 = null;
        json2 = jParser.makeHttpRequest(url_all_products, "GET", params);

        //  System.out.println("success to get json object for all products/t"+json2);// getting data from php an mysql database   

        JSONArray products2 = null;
        String[] Itemname = null;
        String[] rcatacode = null;
        try {
            int success2 = json2.getInt(TAG_ALLPRODUCT_SUCCESS);
            products2 = json2.getJSONArray(TAG_ALLPRODUCT_PRODUCTS);

            Itemname = new String[products2.length()];
            rcatacode = new String[products2.length()];
            if (success2 == 1) {
                cb3 = new Button(this);
                for (int i = 0; i < products2.length(); i++) {
                    JSONObject c = products2.getJSONObject(i);
                    // Storing each json item in variable 
                    String itemcode = c.getString(TAG_ALLPRODUCT_MCODE); //to store data from database 
                    String itemname = c.getString(TAG_ALLPRODUCT_ITEM_NAME);
                    String item_rate = c.getString(TAG_ALLPRODUCT_RATE);
                    String r_cata = c.getString(TAG_ALLPRODUCT_RCATA);
                    Itemname[i] = itemname;
                    rcatacode[i] = r_cata;

                }
            }
        } // try closed 
        catch (JSONException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 20; i++) {
            // Button b=new Button(this); //getting error on here also 

            System.out.println(Itemname[i]);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

我甚至不知道从哪里开始...

  1. 您延长ActivityonCreate()缺少Bundle参数
  2. 您没有致电super.onCreate()
  3. ArrayList mButtons3 = new ArrayList();无效。 ArrayList需要一种类型,例如ArrayList<Button> mButtons3 = new ArrayList<Button>();
  4. 您永远不会致电setContentView(),这意味着您的活动永远不会显示
  5. 这仅适用于第一行代码......您确定了解Android开发的基础知识吗?

答案 1 :(得分:0)

除非您调用setContentView来定义此Activity将创建的布局,否则无法调用findViewById。想一想,你从哪里拿起gridview?哪个布局?

答案 2 :(得分:0)

通过在try-catch块之外声明动态按钮来解决问题... 按钮的声明,TextViewEditText等等无法在try-catchinstance.setOnclickLisner(new Onclick..){}中完成,而是可以通过调用任务函数来完成