为DBHelper类创建新实例时出现NullPointerException

时间:2014-07-30 07:57:10

标签: java android dynamic nullpointerexception android-spinner

我试图通过调用loadSpinnerData()来填充微调器数据,但它会出现NullPointerException错误。

这是MyLayoutOperation类的代码: -

public class MyLayoutOperation extends Activity{

    static Spinner products;

    public static void display(final Activity activity, Button btn)
    {
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);

                java.util.ArrayList<String> msg = new ArrayList<String>();

                for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
                {
                    LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
                    products = (Spinner) innerLayout.findViewById(R.id.spinner1);
                    EditText edit = (EditText) innerLayout.findViewById(R.id.editDescricao);

                    msg.add(products.getSelectedItem().toString());
                    msg.add(edit.getText().toString());

                }

                Toast t = Toast.makeText(activity.getApplicationContext(), msg.toString(), Toast.LENGTH_SHORT);
                t.show();
            }
        });
    }

    public static void add(final Activity activity, ImageButton btn)
    {
        final LinearLayout linearLayoutForm = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);

        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                final LinearLayout newView = (LinearLayout)activity.getLayoutInflater().inflate(R.layout.rowdetail, null);

                newView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                 try {
                        MyLayoutOperation mlo = new MyLayoutOperation();
                        loadSpinnerData();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                ImageButton btnRemove = (ImageButton) newView.findViewById(R.id.btnRemove);
                btnRemove.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        linearLayoutForm.removeView(newView);
                    }
                });

                linearLayoutForm.addView(newView);
            }
        });
    }

    private void loadSpinnerData() throws IOException {

        // database handler
        DBHelper db = new DBHelper(getApplicationContext());

        // Spinner Drop down elements
        List<String> productslist = db.getAllProducts();

        // Creating adapter
        ArrayAdapter<String> dataAdapterP = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, productslist);

        // Drop down layout style - list view with radio button
        dataAdapterP
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        products.setAdapter(dataAdapterP);

    }
}

MainActivity.java: -

public class MainActivity extends Activity {

    Button btnDisplay;
    ImageButton btnAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAdd = (ImageButton) findViewById(R.id.btnAdd);
        btnDisplay = (Button) findViewById(R.id.btnDisplay);

        MyLayoutOperation.add(this, btnAdd);
        MyLayoutOperation.display(this, btnDisplay);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

这是我的LogCat: -

07-30 02:47:40.500: E/AndroidRuntime(1284): FATAL EXCEPTION: main
07-30 02:47:40.500: E/AndroidRuntime(1284): Process: com.example.teste1, PID: 1284
07-30 02:47:40.500: E/AndroidRuntime(1284): java.lang.NullPointerException
07-30 02:47:40.500: E/AndroidRuntime(1284):     at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
07-30 02:47:40.500: E/AndroidRuntime(1284):     at com.example.teste1.MyLayoutOperation.loadSpinnerData(MyLayoutOperation.java:88)
07-30 02:47:40.500: E/AndroidRuntime(1284):     at com.example.teste1.MyLayoutOperation.access$0(MyLayoutOperation.java:85)
07-30 02:47:40.500: E/AndroidRuntime(1284):     at com.example.teste1.MyLayoutOperation$2.onClick(MyLayoutOperation.java:65)
07-30 02:47:40.500: E/AndroidRuntime(1284):     at android.view.View.performClick(View.java:4438)
07-30 02:47:40.500: E/AndroidRuntime(1284):     at android.view.View$PerformClick.run(View.java:18422)

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您在loadSpinnerData()打电话的活动未初始化为Context

您使用new自己实例化了另一个实例。切勿使用new实例化活动。

在这种情况下,您可以使用this来引用Android框架为您设置的当前活动实例。取代

MyLayoutOperation mlo = new MyLayoutOperation();
mlo.loadSpinnerData();

loadSpinnerData();

隐式调用this上的方法。

答案 1 :(得分:0)

最后这个有效: -

public class TestActivity extends Activity {  
    Button btnDisplay;
    ImageButton btnAdd;
    LinearLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        container = findViewById(R.id.linearLayoutForm);
        btnAdd = (ImageButton) findViewById(R.id.btnAdd);
        btnDisplay = (Button) findViewById(R.id.btnDisplay);

        btnAdd.setOnClickListener(addListener);
        //TODO: btnDisplay
    }

    /*
     * We define our OnClickListener that will act when we click on the btn.
     */
    View.OnClickListener addListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final LinearLayout newView = (LinearLayout) getLayoutInflater().inflate(R.layout.rowdetail, null);

            newView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            ImageButton btnRemove = (ImageButton) newView.findViewById(R.id.btnRemove);
            btnRemove.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    container.removeView(newView);
                }
            });

            container.addView(newView);

            //Now we load your data into your spinner
            Spinner s = newView.findViewById(R.id.spinner1);
            try {
                loadSpinnerData(s);
            } catch (IOException e) {
                //TODO: catch exception
                e.printStackTrace();
            }

        }
    };

    /*
     * This function is supposed to load the data into the given spinner.
     * It would be better to load the data an other way, i.e.: using ASyncTask
     */
    private void loadSpinnerData(Spinner s) throws IOException {

        // database handler
        DBHelper db = new DBHelper(getApplicationContext());

        // Spinner Drop down elements
        List<String> products = db.getAllProducts();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, products);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        s.setAdapter(dataAdapter);

    }
}