开发者

Android App Crashes on Startup due to java.lang.NullPointerException

开发者 https://www.devze.com 2023-02-04 19:45 出处:网络
Here is my .java file: package com.shoppinglist; import java.util.ArrayList; import android.app.Dialog; import android.app.ListActivity;

Here is my .java file:

package com.shoppinglist;

import java.util.ArrayList;

import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ShoppingList extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final EditText et = (EditText) findViewById(R.id.edittext);
        ListView lv = (ListView) findViewById(android.R.id.list);
        final ArrayList<String> items = new ArrayList<String>();
        final ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter<String>(
        this, android.R.layout.simple_list_item_1, items);
        lv.setAdapter(adapter);
        setContentView(R.layout.main);

        Button button1main = (Button) findViewById(R.id.add);
        button1main.setOnClickListener(new OnClickListener()  {
            @Override
            public void onClick(View v)  {
            final Dialog dialog = new Dialog(ShoppingList.this);
            dialog.setContentView(R.layout.maindialog);
            dialog.setCancelable(true);

        Button button = (Button) dialog.findViewById(R.id.cancel);
        button.setOnClickListener(new OnClickListener()  {
                @Override
                public void onClick(View v)  {
  开发者_开发问答                  dialog.dismiss();
                }
            });
            dialog.show();

        Button ok = (Button) dialog.findViewById(R.id.ok);
        ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                items.add(0, et.getText().toString());
                adapter.notifyDataSetChanged();
                dialog.dismiss();
                et.setText("");
        }

            }
        );
       }
        });
    }
}


Add

setContentView(R.layout.main);

after

super.onCreate(savedInstanceState);

that will solve your problem.


In Eclipse, use Window > Show View ...> Android > LogCat to display the log message and look for a related exception to explain the crash.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号