致命异常显示错误无法启动活动组件,当我运行此应用程序时



我正试图在列表视图应用程序中简单地显示SQLite database中的所有记录。编译器没有检测到任何错误,但当我运行应用程序时,它会出现运行时错误。

main_Activity.java

package com.example.login_userauthentication;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void Register(View v)
    {
        startActivity(new Intent(getApplicationContext(),Reg.class));
    }
    public void Login(View v)
    {
        startActivity(new Intent(getApplicationContext(),Login.class));
    }
    public void Show_allrecord(View v)
    {
        startActivity(new Intent(getApplicationContext(),Show_record.class));
    }
    public void update_record(View v)
    {
        startActivity(new Intent(getApplicationContext(),Update.class));
    }
    @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;
    }
}

Show_Record.java(这是显示listview中所有用户详细信息的主类)

package com.example.login_userauthentication;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
public class Show_record extends Activity
{
    Show_recordAdapter showrecord_adapter;
    ListView listview;
    ArrayList<Student> studentlist;
    Database helper=new Database();
    protected void onCreate(Bundle savedInstanceState)
    {
        System.out.println("show sumit");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_recordlist);
        System.out.println("show_record activity");
        System.out.println("show sumit");
        helper=new Database();
        listview = (ListView) findViewById(R.id.listView1);
        studentlist=new ArrayList<Student>();
        studentlist = helper.getAllrecord();
        System.out.println(studentlist);
        System.out.println("show sumit");
        showrecord_adapter=new Show_recordAdapter(getApplicationContext(),studentlist);
        listview.setAdapter(showrecord_adapter);
//      listview.setAdapter(new Show_recordAdapter(this, studentlist,
//              getLayoutInflater()));
    }
}

package com.example.login_userauthentication;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

show_recordAdapter.java

这是自定义适配器类

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class Show_recordAdapter extends BaseAdapter 
{
    Context context;
    ArrayList<Student> empList;
    private static LayoutInflater inflater = null;
    public Show_recordAdapter(Context context,ArrayList<Student> empList)
    {
        context=this.context;
        empList=this.empList;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    public int getCount() {
        // TODO Auto-generated method stub
        return empList.size();
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return empList.get(position);
    }
    @Override
    public long getItemId(int position) 
    {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        //final ViewItem item;
        if(convertView==null)
            convertView = inflater.inflate(R.layout.listview_iteams, null);
        //item=new ViewItem();
        TextView UemailTextview=(TextView)convertView.findViewById(R.id.uemail);
        TextView upassTextview=(TextView)convertView.findViewById(R.id.upass);
        TextView UnameTextview=(TextView)convertView.findViewById(R.id.uname);
        TextView UmobileTextview=(TextView)convertView.findViewById(R.id.umobile);
//      convertView.setTag(item);   
//      }
//      else
//      {
//          item=(ViewItem)convertView.getTag();
//      }
        Student student=new Student();
        student=empList.get(position);
        UnameTextview.setText("emailid: "+student.getEmailid());
        upassTextview.setText("password: "+student.getPassword());
        UnameTextview.setText("name: "+student.getName());
        UmobileTextview.setText("mobile: "+student.getMobileno());
        return convertView;
    }
//  private class ViewItem
//  {
//      TextView UemailTextview;
//      TextView upassTextview;
//      TextView UnameTextview;
//      TextView UmobileTextview;
//  }
}

数据库类(其中定义了表的所有文件名,也定义了方法)

package com.example.login_userauthentication;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract.Helpers;
import android.util.Log;
public class Database
{
    public static final String TABLE_NAME = "student";
    public static final String USER_EMAILID= "emailid";
    public static final String USER_PASSWORD = "password";
    public static final String USER_NAME = "name";
    public static final String USER_CONTACT = "mobileno";
    public static final String Tag = "jobplacement";
    public static Databse_helper dbhelper = null;
    public static SQLiteDatabase db = null;
    static Context context1 = null;
    public static boolean addUser(Context context, String email, String password, String name,String mobile)
    {
        context1=context;
        try {
        dbhelper=new Databse_helper(context);
        db=dbhelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(Database.USER_EMAILID,email);
        values.put(Database.USER_PASSWORD,password);
        values.put(Database.USER_NAME,name);
        values.put(Database.USER_CONTACT,mobile);
        long rowid = db.insert(Database.TABLE_NAME, null, values);
        Log.d("Users", "Inserted into TRANSACTIONS " + rowid);
        db.close();
        return true;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public static boolean userAuthentication(Context context, String uname, String password) {
        Cursor trans = null;
        try {
            dbhelper=new Databse_helper(context);
            db = dbhelper.getWritableDatabase();
            trans = db.rawQuery("select " + USER_PASSWORD + " from " + TABLE_NAME + " where " + USER_EMAILID
                    + " = '" + uname + "'", null);
            if (trans.getCount() == 0) 
            {
                Log.d("userAuthentication", "Zero record");
            } 
            else 
            {
                while (trans.moveToNext()) 
                {
                    String pass = trans.getString(trans.getColumnIndex(USER_PASSWORD));
                    if (password.equals(pass))
                    {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    public ArrayList<Student> getAllProducts() 
    {
        db = dbhelper.getWritableDatabase();
        List<Student> productList = new ArrayList<Student>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + Database.TABLE_NAME;
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Student st = new Student();
                st.setEmailid(cursor.getString(0));
                st.setPassword(cursor.getString(1));
                st.setName(cursor.getString(2));
                st.setMobileno(cursor.getString(3));
//              product.setID(Integer.parseInt(cursor.getString(0)));
//              product.setName(cursor.getString(1));
//              product.setNumber(Integer.parseInt(cursor.getString(2)));
//              product.setPieces(Integer.parseInt(cursor.getString(3)));
//              product.setPrice(Integer.parseInt(cursor.getString(4)));
//              product.setTotPrice(Integer.parseInt(cursor.getString(5)));
                // Adding contact to list
                productList.add(st);
            } while (cursor.moveToNext());
        }
        // return contact list
        return (ArrayList<Student>) productList;
    }
    public static boolean  updateEntry(Student st)
    {
        db=dbhelper.getWritableDatabase();
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put(USER_EMAILID, st.getEmailid());
        updatedValues.put(USER_NAME,st.getName());
        updatedValues.put(USER_CONTACT, st.getMobileno());
        //String where=Database.USER_EMAILID +"=+?";
       // String where="emailid +=?";
         int row_id=db.update(Database.TABLE_NAME,updatedValues, "emailid=?", new String[]{st.getEmailid()});
         Log.d("login", "updated record " +row_id);
        return true;
    }
    public ArrayList<Student> getAllrecord()
    {
        dbhelper=new Databse_helper(context1);
        db=dbhelper.getWritableDatabase();
        List<Student> emplist=new ArrayList<Student>();
        String rowquery="select * from "+TABLE_NAME;
        Cursor cursor=db.rawQuery(rowquery, null);
        if (cursor.moveToFirst()) 
        {
            do 
            {   Student st = new Student();
            st.setEmailid(cursor.getString(0));
            st.setPassword(cursor.getString(1));
            st.setName(cursor.getString(2));
            st.setMobileno(cursor.getString(3));
                // Adding Translate to list
                Student emp1=new Student();
               emplist.add(st);
            } 
            while (cursor.moveToNext());
        }
        // return Translate list
        return (ArrayList<Student>) emplist;
   }
}

Database_helper.java(其中定义了创建表和创建数据库)

package com.example.login_userauthentication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Databse_helper extends SQLiteOpenHelper
{
    static final int DATABASE_VERSION = 2;
    static final String DATABASE_NAME = "collage.db";
    public static final String Tag = "jobplacement";
    public Databse_helper(Context cxt) 
    {
        super(cxt, DATABASE_NAME, null, DATABASE_VERSION);
        Log.i(Tag, "DBHelper class constructer called");
        Log.i(Tag, "Database Created Successfully");
    }
    public void onCreate(SQLiteDatabase db) 
    {
        createTables(db);
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
         db.execSQL("DROP TABLE IF EXISTS " + Database.TABLE_NAME);
        // Create tables again
        onCreate(db);
    }
    private void createTables(SQLiteDatabase database)
    {
        String users_table_sql = "create table " + Database.TABLE_NAME + " ( " + Database.USER_EMAILID
                + " TEXT," + Database.USER_PASSWORD + " TEXT," + Database.USER_NAME
                + " TEXT," + Database.USER_CONTACT + " TEXT)";
         try {
             database.execSQL(users_table_sql);
             Log.d(Tag, "table created successfully");
    //     protected static final String player = ("CREATE TABLE " + table_player
    //              + " (" + player_id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    //              + player_name + " TEXT, " + player_dob + " INTEGER," + player_gender + " TEXT);");
    //     
    //     
    //     "CREATE TABLE " + TABLE_PRODUCTS + "("
    //     + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
    //     + KEY_NO + " TEXT," + KEY_PIECES + " TEXT,"+ KEY_PRICE + " TEXT," + KEY_TOT_PRICE + " TEXT" + ")";
        } catch (Exception ex)
        {
            Log.d("Accounts", "Error in DBHelper.onCreate() : " + ex.getMessage());
        }
    }
}

这是logcat

12-24 05:15:26.447: I/Choreographer(1009): Skipped 64 frames!  The application may be doing too much work on its main thread.
12-24 05:15:27.797: I/Choreographer(1009): Skipped 48 frames!  The application may be doing too much work on its main thread.
12-24 05:15:43.807: I/System.out(1009): show sumit
12-24 05:15:44.547: D/dalvikvm(1009): GC_FOR_ALLOC freed 88K, 9% free 2642K/2876K, paused 245ms, total 305ms
12-24 05:15:44.818: I/System.out(1009): show_record activity
12-24 05:15:44.837: I/System.out(1009): show sumit
12-24 05:15:44.857: I/jobplacement(1009): DBHelper class constructer called
12-24 05:15:44.857: I/jobplacement(1009): Database Created Successfully
12-24 05:15:44.887: D/AndroidRuntime(1009): Shutting down VM
12-24 05:15:44.887: W/dalvikvm(1009): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
12-24 05:15:45.017: E/AndroidRuntime(1009): FATAL EXCEPTION: main
12-24 05:15:45.017: E/AndroidRuntime(1009): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.login_userauthentication/com.example.login_userauthentication.Show_record}: java.lang.NullPointerException
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.os.Looper.loop(Looper.java:137)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.ActivityThread.main(ActivityThread.java:5041)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at java.lang.reflect.Method.invokeNative(Native Method)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at java.lang.reflect.Method.invoke(Method.java:511)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at dalvik.system.NativeStart.main(Native Method)
12-24 05:15:45.017: E/AndroidRuntime(1009): Caused by: java.lang.NullPointerException
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at com.example.login_userauthentication.Database.getAllrecord(Database.java:144)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at com.example.login_userauthentication.Show_record.onCreate(Show_record.java:32)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.Activity.performCreate(Activity.java:5104)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-24 05:15:45.017: E/AndroidRuntime(1009):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-24 05:15:45.017: E/AndroidRuntime(1009):     ... 11 more
12-24 05:40:30.726: D/gralloc_goldfish(1215): Emulator without GPU emulation detected.
12-24 05:43:35.957: D/gralloc_goldfish(1271): Emulator without GPU emulation detected.

在数据库类内部getAllrecord()传递的context1为null

 dbhelper = new Databse_helper(context1);//here context1 is null

您可以尝试将context传递到Database类中的getAllrecord(context context1)然后可以调用

studentlist = helper.getAllrecord(Show_record.this);

来自Show_record类。希望这将有助于解决您的问题。

相关内容

最新更新