无法启动活动componentinfo --- Nullpointer异常

时间:2013-12-07 07:36:39

标签: android

当我按下“显示”按钮(btnshow)时,它显示错误无法启动活动组件信息& Nullpointer异常。我怎么能解决这个问题.plz帮帮我......

Mainactivity.java

    package com.mamun.sqltest;

    import android.app.Activity;
    import android.app.Dialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;




    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class MainActivity extends Activity implements OnClickListener {

        private Button add, delete, update, show, search;
        private EditText etname, etaddress, etcell, etsearch;

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

            add = (Button) findViewById(R.id.btnadd);
            delete = (Button) findViewById(R.id.btndelete);
            update = (Button) findViewById(R.id.btnupdate);
            show = (Button) findViewById(R.id.btnshow);
            search = (Button) findViewById(R.id.btnsearch);

            etname = (EditText) findViewById(R.id.etname);
            etaddress = (EditText) findViewById(R.id.etaddress);
            etcell = (EditText) findViewById(R.id.etcell);
            etsearch = (EditText) findViewById(R.id.etsearch);

            add.setOnClickListener(this);
            delete.setOnClickListener(this);
            update.setOnClickListener(this);
            show.setOnClickListener(this);
            search.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnadd:
                boolean didItwork = true;
                try {
                    String name = etname.getText().toString();
                    String address = etaddress.getText().toString();
                    String cell = etcell.getText().toString();

                    Dbtrial entry = new Dbtrial(MainActivity.this);
                    entry.open();
                    entry.createEntry(name, address, cell);
                    entry.close();

                } catch (Exception e) {
                    didItwork = false;

                    String error = e.toString();
                    Dialog d = new Dialog(this);
                    d.setTitle("Error found");
                    TextView tv = new TextView(this);
                    tv.setText(error);
                    d.setContentView(tv);
                    d.show();
                } finally {
                    if (didItwork) {
                        Dialog d = new Dialog(this);
                        d.setTitle("Saved");
                        TextView tv = new TextView(this);
                        tv.setText("Sucess");
                        d.setContentView(tv);
                        d.show();
                    }
                }

                break;
            case R.id.btndelete:
                try{String sRow1 = etsearch.getText().toString();
                long lRow1 = Long.parseLong(sRow1); 

                Dbtrial ex1 = new  Dbtrial(this);
                ex1.open();
                ex1.deleteEntry(lRow1);
                ex1.close();
                }catch (Exception e) {


                    String error = e.toString();
                    Dialog d = new Dialog(this);
                    d.setTitle("Error found");
                    TextView tv = new TextView(this);
                    tv.setText(error);
                    d.setContentView(tv);
                    d.show();
                }
                break;
            case R.id.btnupdate:
                try{
                    String sRow = etsearch.getText().toString();
                long lRow= Long.parseLong(sRow); 

                String upname = etname.getText().toString();
                String upaddress = etaddress.getText().toString();
                String upcell = etcell.getText().toString();
                Dbtrial ex = new  Dbtrial(this);
                ex.open();
                ex.updateEntry(lRow,upname,upaddress,upcell);
                ex.close();
            }catch (Exception e) {


                String error = e.toString();
                Dialog d = new Dialog(this);
                d.setTitle("Error found");
                TextView tv = new TextView(this);
                tv.setText(error);
                d.setContentView(tv);
                d.show();
            }

                break;
            case R.id.btnshow:
                Intent i = new Intent(this,Sqlview.class);
                startActivity(i);
                break;

            case R.id.btnsearch:
                try {
                    String s = etsearch.getText().toString();

                long l= Long.parseLong(s);
                Dbtrial hon = new Dbtrial(this);
                hon.open();
                String returnedNamed = hon.getName(l);
                String returnedAddress = hon.getAddress(l);
                String returnedCell = hon.getCell(l);
                hon.close();


                etname.setText(returnedNamed);
                etaddress.setText(returnedAddress);
                etcell.setText(returnedCell);

                }catch (Exception e) {


                    String error = e.toString();
                    Dialog d = new Dialog(this);
                    d.setTitle("Error found");
                    TextView tv = new TextView(this);
                    tv.setText(error);
                    d.setContentView(tv);
                    d.show();
                }



                break;
            default:
                break;
            }

        }

    }

Dbtrial.java

package com.mamun.sqltest;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Dbtrial {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_CELL = "cell";

    private static final String DATABASE_NAME = "Infodb";
    private static final String DATABASE_TABLE = "Info";
    private static final int DATABASE_VERSION = 3;

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper {

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
            + " INTEGER  PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
            + " TEXT NOT NULL , " + KEY_ADDRESS + " TEXT NOT NULL, "
            + KEY_CELL + " NUMBER NOT NULL );");

}

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }

    }

    public Dbtrial(Context c) {

        ourContext = c;
    }

    public Dbtrial open() throws SQLException {
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        ourHelper.close();
    }

    public long createEntry(String name, String address, String cell) {


// TODO Auto-generated method stub
            ContentValues cv = new ContentValues();
            cv.put(KEY_NAME, name);
            cv.put(KEY_ADDRESS, address);
            cv.put(KEY_CELL, cell);
            return ourDatabase.insert(DATABASE_TABLE, null, cv);

    }

    public String getData() {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        String result = "";

        int iId = c.getColumnIndex(KEY_NAME);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + c.getString(iId) + "\n";//
        }
        return result;
    }

    public String getName(long l) throws SQLException {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + l, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String name = c.getString(1);
            return name;
        }
        return null;
    }

    public String getAddress(long l) throws SQLException {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + l, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String address = c.getString(2);
            return address;
        }
        return null;
    }

    public String getCell(long l) throws SQLException {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + l, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String cell = c.getString(3);
            return cell;
        }
        return null;
    }

    public void updateEntry(long lRow, String upname, String upaddress,
            String upcell) throws SQLException {
        ContentValues cvUpdate = new ContentValues();
        cvUpdate.put(KEY_NAME, upname);
        cvUpdate.put(KEY_ADDRESS, upaddress);
        cvUpdate.put(KEY_CELL, upcell);
        ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow,
                null);
    }

    public void deleteEntry(long lRow1) throws SQLException {
        ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);

    }

    public String getData2() {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        String result = "";

        int iName = c.getColumnIndex(KEY_NAME);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + c.getString(iName) + "\n";//
        }
        return result;

    }

    public String getData3() {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        String result = "";

        int iAddress = c.getColumnIndex(KEY_ADDRESS);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + c.getString(iAddress) + "\n";
        }
        return result;

    }

    public String getData4() {
        String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS,
                KEY_CELL };//
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
                null, null);
        String result = "";

        int iCell = c.getColumnIndex(KEY_CELL);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + c.getString(iCell) + "\n";
        }
        return result;

    }
}

Sqlview.java

 package com.mamun.sqltest;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Sqlview extends Activity {

    // data source
    private String alldata;
    private Dbtrial dbAdapter;

    // adapter
    private DataAdapter adapter;

    // view
    private ListView lvinfo;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlview);

        // //
        dbAdapter = new Dbtrial(this);
        dbAdapter.open();
        alldata = dbAdapter.getData();
        dbAdapter.close();

        lvinfo = (ListView) findViewById(R.id.lvinfo);
        adapter = new DataAdapter(this, alldata);
        lvinfo.setAdapter(adapter);


        lvinfo.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> listview, View v, int position,
                    long id) {
                Toast.makeText(getApplicationContext(), "Selected Book: "+position, Toast.LENGTH_LONG).show();
            }
        });


    }

}

*的 DataAdapter的 *

 package com.mamun.sqltest;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class DataAdapter  extends ArrayAdapter<Dbtrial>{



    private Activity context;
    private static ArrayList<Dbtrial> items;
    private LayoutInflater inflater;

    public DataAdapter(Context context, String alldata) {
        super(context, R.layout.info_item, items);
        this.context=(Activity)context;
        this.items=items;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v=convertView;
        if(v==null)
        {
            // create new view
            inflater=context.getLayoutInflater();
            v=inflater.inflate(R.layout.info_item, null);

            TextView tvid=(TextView)v.findViewById(R.id.tvid);
            TextView tvname=(TextView)v.findViewById(R.id.tvname);
            TextView tvaddress=(TextView)v.findViewById(R.id.tvaddress);
            TextView tvcell=(TextView)v.findViewById(R.id.tvcell);

            Dbtrial b=items.get(position);
            tvid.setText(b.getData());
            tvname.setText(b.getData2());
            tvaddress.setText(b.getData3());
            tvcell.setText(b.getData4());

            tvname.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "I am a title", Toast.LENGTH_LONG).show();

                }
            });

        }
        else
        {

        }

        return v;
    }



}

xml文件是:

* activity_main.xml中*`

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/etname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Address"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/etaddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cell"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/etcell"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="phone" />

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/btnadd"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/btn_add" />

            <Button
                android:id="@+id/btndelete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Delete" />

            <Button
                android:id="@+id/btnupdate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Update" />

            <Button
                android:id="@+id/btnshow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Show" />
        </TableRow>

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Search here"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/etsearch"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="search by id"
            android:inputType="number" />

        <Button
            android:id="@+id/btnsearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Search" />

    </LinearLayout>

sqlview.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ListView
            android:id="@+id/lvinfo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </ListView>

    </LinearLayout>

*的 * info_item.xml *

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/tvid"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Id"
                android:layout_weight="2"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView
                android:id="@+id/tvaddress"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="address" 
                android:layout_weight="1"
                android:layout_gravity="right"
              />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/tvname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="name"
                android:layout_weight="2"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView
                android:id="@+id/tvcell"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="cell" 
                android:layout_weight="1"
                android:layout_gravity="right"/>

        </TableRow>
    </TableLayout>

</LinearLayout>

logcat的

12-07 07:42:46.945: E/AndroidRuntime(1259): FATAL EXCEPTION: main
12-07 07:42:46.945: E/AndroidRuntime(1259): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mamun.sqltest/com.mamun.sqltest.Sqlview}: java.lang.NullPointerException
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.os.Looper.loop(Looper.java:137)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.ActivityThread.main(ActivityThread.java:5039)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at java.lang.reflect.Method.invokeNative(Native Method)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at java.lang.reflect.Method.invoke(Method.java:511)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at dalvik.system.NativeStart.main(Native Method)
12-07 07:42:46.945: E/AndroidRuntime(1259): Caused by: java.lang.NullPointerException
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.widget.ListView.setAdapter(ListView.java:462)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at com.mamun.sqltest.Sqlview.onCreate(Sqlview.java:38)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.Activity.performCreate(Activity.java:5104)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-07 07:42:46.945: E/AndroidRuntime(1259):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-07 07:42:46.945: E/AndroidRuntime(1259):     ... 11 more

3 个答案:

答案 0 :(得分:1)

传递给items超级构造函数的ArrayAdapternull

答案 1 :(得分:0)

我觉得问题在于Dbtrial构造函数。您正在使用ourDatabase = ourHelper.getWritableDatabase();以写入模式getData()querymethod打开数据库。要从数据库读取数据,它应以可读模式打开。这是因为它将空数据返回到alldata = dbAdapter.getData();并且不会初始化适配器并且会抛出错误。

答案 2 :(得分:0)

尝试删除NUMBER NOT NULL后的空格