我在android文件中有错误

时间:2016-11-15 14:00:32

标签: android error-handling

addMember.java

EditText name,paid;
Button add;
final MyDBHandler db = new MyDBHandler(this);
String unpaid, inout="0";




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_new_member);
    name=(EditText)findViewById(R.id.userName);
    paid=(EditText)findViewById(R.id.PaidAmount);
    add=(Button)findViewById(R.id.addMember);


    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            unpaid=Integer.toString(250-(Integer.parseInt(paid.getText().toString())));

            Log.d("Insert: ", "Inserting ..");
            db.add(new backService(name.getText().toString(),paid.getText().toString(),unpaid,inout));
            Intent intent=new Intent(addMember.this,MainActivity.class);
            startActivity(intent);


        }
    });




}

backService.java

private int _id;
private String message,number,con_name,date;

public backService(){}

public backService(String msg,String num,String con_na,String dat){
    this.message=msg;
    this.number=num;
    this.con_name=con_na;
    this.date=dat;
}


  //SETTERS
 public void set_id(int _id) {
    this._id = _id;
}

public void setMessage(String message) {
    this.message = message;
}

public void setNumber(String number) {
    this.number = number;
}

public void setCon_name(String con_id) {
    this.con_name = con_id;
}

public void setDate(String date) {
    this.date = date;
}

//END SETTERS


 //GETTERS
public int get_id() {
    return _id;
}

public String getMessage() {
    return message;
}

public String getCon_name() {
    return con_name;
}

public String getNumber() {
    return number;
}

public String getDate() {
    return date;
}

//END GETTERS

CustomAdapter.java

Activity context;
String name[];
String paid[];
String unpaid[];
int state[];

public CustomAdapter(Activity context, String[] name, String[] paid, String[] unpaid, int[] state) {
    super();
    this.context = context;
    this.name = name;
    this.paid = paid;
    this.unpaid=unpaid;
    this.state=state;
}

public int getCount() {
    // TODO Auto-generated method stub
    return name.length;
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

private class ViewHolder {
    TextView txtViewName;
    TextView txtViewPaid;
    TextView txtViewUnpaid;
    Switch in_outSwitch;
}

public View getView(int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    ViewHolder holder;
    LayoutInflater inflater =  context.getLayoutInflater();

    if (convertView == null)
    {
        convertView = inflater.inflate(R.layout.listview_text, null);
        holder = new ViewHolder();
        holder.txtViewName = (TextView) convertView.findViewById(R.id.patricipants);
        holder.txtViewPaid = (TextView) convertView.findViewById(R.id.money_paid);
        holder.txtViewUnpaid = (TextView) convertView.findViewById(R.id.money_due);
        holder.in_outSwitch= (Switch) convertView.findViewById(R.id.inorout);
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtViewName.setText(name[position]);
    holder.txtViewPaid.setText(paid[position]);
    holder.txtViewUnpaid.setText(unpaid[position]);
    if(state[position]==0){
        holder.in_outSwitch.setChecked(false);
    }
    else{
        holder.in_outSwitch.setChecked(true);
    }

    return convertView;
}

MainActivity.java

ListView lv;
CustomAdapter ca;
String[] name,paid,unpaid;
int[] state,ids;
MyDBHandler dbh;
int positions;
updater upd;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    name=dbh.ret_name();
    paid=dbh.ret_paidAmt();
    unpaid=dbh.ret_unpaidAmt();
    ids=dbh.ret_id();
    state=dbh.ret_inORout();


    lv=(ListView) findViewById(R.id.nameSpace);
    ca=new CustomAdapter(this,name,paid,unpaid,state);

    lv.setAdapter(ca);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showPopup(view);
        }
    });


    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            showcontextmenu(view,position);
            return true;
        }
    });

}




public void showcontextmenu(View v,int position) {
    PopupMenu popupMenu=new PopupMenu(this,v);
    popupMenu.setOnMenuItemClickListener(this);
    MenuInflater inflater = popupMenu.getMenuInflater();
    inflater.inflate(R.menu.listviewpress,popupMenu.getMenu());
    positions=position;
    popupMenu.show();

}


public void showPopup(View v)
{
    PopupMenu popupMenu=new PopupMenu(this,v);
    popupMenu.setOnMenuItemClickListener(this);
    MenuInflater inflater = popupMenu.getMenuInflater();
    inflater.inflate(R.menu.menu_main,popupMenu.getMenu());
    popupMenu.show();

}







@Override
public boolean onMenuItemClick(MenuItem item) {
    Intent intent;

    //Handle ItemClicks HERE
    switch(item.getItemId()) {
        case R.id.delete:
            dbh.deleteuser(name[positions]);
            return true;
        case R.id.update:
            upd.name=name[positions];
            upd.paid=paid[positions];
            upd.id=Integer.toString(ids[positions]);
            intent=new Intent(MainActivity.this,updater.class);
            startActivity(intent);
           return true;
        case R.id.addMember:
            intent=new Intent(MainActivity.this,addMember.class);
            startActivity(intent);
            return true;
        case R.id.delAll:
            dbh.deldb();
            return true;



        default:
            return false;
    }
}














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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    onMenuItemClick(item);

    return super.onOptionsItemSelected(item);
}

MyDBHandler.java

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "picnic.db";
private static final String TABLE_NAME="members";
private static final String COLUMN_ID="_id";
private static final String COLUMN_MSG="_name";
private static final String COLUMN_NUM="_paid";
private static final String COLUMN_NAME="_unpaid";
private static final String COLUMN_TIME="_inORout";

public long s;
public int size;

public MyDBHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

 // FINDS THE SIZE OF A COLUMN IN A DATABASE
public void get_dbSize(){
    SQLiteDatabase db= getWritableDatabase();
    s= DatabaseUtils.queryNumEntries(db, TABLE_NAME);

}


@Override
public void onCreate(SQLiteDatabase db) {
    String query= "CREATE TABLE " + TABLE_NAME + " ( " +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
            COLUMN_NUM + " TEXT " +
            COLUMN_NAME + " TEXT " +
            COLUMN_MSG + " TEXT " +
            COLUMN_TIME + " TEXT " +
            ");";

    db.execSQL(query);
    get_dbSize();
    size=(int)s;

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
    onCreate(db);

}


public void deldb(){
    SQLiteDatabase db =getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);


}


 // ADD A NEW DATA IN THE DATA BASE
public void add(backService BackService){
    ContentValues values =new ContentValues();
    values.put(COLUMN_NUM, BackService.getNumber());
    values.put(COLUMN_NAME, BackService.getCon_name());
    values.put(COLUMN_MSG, BackService.getMessage());
    values.put(COLUMN_TIME,BackService.getDate());

    SQLiteDatabase db =getWritableDatabase();
    db.insert(TABLE_NAME,null,values);
    db.close();
}


public void deleteuser(String name){
    SQLiteDatabase db =getWritableDatabase();
    db.execSQL("DELETE FROM "+ TABLE_NAME + " WHERE "+ COLUMN_MSG + "= \"" + name +"\";");
}




public void updateuser(String Value1, String Value2, String id){
    SQLiteDatabase db=getWritableDatabase();
    db.execSQL("UPDATE "+TABLE_NAME+" SET "+COLUMN_MSG+ " = \'"+Value1+"\' WHERE "+COLUMN_ID+" = \'"+id+"\' ;");
    db.execSQL("UPDATE "+TABLE_NAME+" SET "+COLUMN_NUM+ " = \'"+Value2+"\' WHERE "+COLUMN_ID+" = \'"+id+"\' ;");

}


/*
//
//
//
 */


public String[] ret_paidAmt(){
    String[] phn_num=new String[size];
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    String query = "SELECT "+COLUMN_NUM+" FROM " + TABLE_NAME + " WHERE 1";               `enter code here`
    int count=0;
    Cursor cursor = sqLiteDatabase.rawQuery(query, null); //Cursor point to a location in results.
    cursor.moveToFirst(); //Move to the first row in results.
    while (!cursor.isAfterLast()) {
        if (cursor.getString(cursor.getColumnIndex(COLUMN_NUM)) != null) {
            phn_num[count] = cursor.getString(cursor.getColumnIndex(COLUMN_NUM));
            count++;
        }
        cursor.moveToNext();
    }
    cursor.close();

    sqLiteDatabase.close();
    return phn_num;
}

// GET NAME FROM THE DB
public String[] ret_name(){
    String[] phn_msg=new String[size];
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    String query = "SELECT "+COLUMN_MSG+" FROM " + TABLE_NAME + " WHERE 1";
             //Select every column, select every row.
    int count=0;
    Cursor cursor = sqLiteDatabase.rawQuery(query, null); //Cursor point to a location in results.
    cursor.moveToFirst(); //Move to the first row in results.
    while (!cursor.isAfterLast()) {
        if (cursor.getString(cursor.getColumnIndex(COLUMN_MSG)) != null) {
            phn_msg[count] = cursor.getString(cursor.getColumnIndex(COLUMN_MSG));
            count++;
        }
        cursor.moveToNext();
    }
    cursor.close();

    sqLiteDatabase.close();
    return phn_msg;

}

 // GET UNPAID AMOUNT FROM DB
public String[] ret_unpaidAmt(){
    String[] phn_conna=new String[size];
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
   String query = "SELECT "+COLUMN_NAME+" FROM " + TABLE_NAME + " WHERE 1";
    //Select every column, select every row.
    int count=0;
    Cursor cursor = sqLiteDatabase.rawQuery(query, null); //Cursor point to a location in results.
    cursor.moveToFirst(); //Move to the first row in results.
    while (!cursor.isAfterLast()) {
        if (cursor.getString(cursor.getColumnIndex(COLUMN_NAME)) != null) {
            phn_conna[count] = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
            count++;
        }
        cursor.moveToNext();
    }
    cursor.close();

    sqLiteDatabase.close();
    return phn_conna;


}

  // GET ID OF CONTACT FROM DB
public int[] ret_id(){
    int[] con_id=new int[size];
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    String query = "SELECT "+COLUMN_ID+" FROM " + TABLE_NAME + " WHERE 1"; 
    //Select every column, select every row.
    int count=0;
    Cursor cursor = sqLiteDatabase.rawQuery(query, null); 
     //Cursor point to a location in results.
    cursor.moveToFirst(); //Move to the first row in results.
    while (!cursor.isAfterLast()) {
        if (cursor.getString(cursor.getColumnIndex(COLUMN_ID)) != null) {
            con_id[count] = Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
            count++;
        }
        cursor.moveToNext();
    }
    cursor.close();

    sqLiteDatabase.close();
    return con_id;


}

 // GET IN OR OUT FROM DB
public int[] ret_inORout(){
    int[] rec_time=new int[size];
    String temp;
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    String query = "SELECT "+COLUMN_TIME+" FROM " + TABLE_NAME + " WHERE 1";  
    //Select every column, select every row.
    int count=0;
    Cursor cursor = sqLiteDatabase.rawQuery(query, null); //Cursor point to a location in results.
    cursor.moveToFirst(); //Move to the first row in results.
    while (!cursor.isAfterLast()) {
        if (cursor.getString(cursor.getColumnIndex(COLUMN_TIME)) != null) {
             temp = cursor.getString(cursor.getColumnIndex(COLUMN_TIME));
            rec_time[count] = Integer.parseInt(temp.trim());
            count++;
        }
        cursor.moveToNext();
    }
    cursor.close();

    sqLiteDatabase.close();
    return rec_time;


}

updater.java

EditText nameField,paymentField;
Button updateButton;
TextView textView;
String name,paid,id;
MyDBHandler dbh;


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

    nameField=(EditText) findViewById(R.id.nameOfMember);
    paymentField=(EditText) findViewById(R.id.amtPaidByUser);
    updateButton=(Button) findViewById(R.id.updateButton);
    textView=(TextView) findViewById(R.id.Remaining);

    nameField.setText(name);
    paymentField.setText(paid);
    updatetext();

    paymentField.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!paymentField.getText().toString().equalsIgnoreCase("")){

                updatetext();

            }

        }
    });

    updateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name=nameField.getText().toString();
            paid=paymentField.getText().toString();
            dbh.updateuser(name,paid,id);
            Toast.makeText(getApplicationContext(),name+" is updated",Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(updater.this,MainActivity.class);

        }
    });






}
public void updatetext(){
    textView.setText(Integer.toString((250-Integer.parseInt(paid))));
}

logcat的

>FATAL EXCEPTION: main
                                                                               Process: com.example.neil.picnicrecord, PID: 22647
                                                                               Theme: themes:{}
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.neil.picnicrecord/com.example.neil.picnicrecord.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] com.example.neil.picnicrecord.MyDBHandler.ret_name()' on a null object reference
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
                                                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5471)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] com.example.neil.picnicrecord.MyDBHandler.ret_name()' on a null object reference
                                                                                   at com.example.neil.picnicrecord.MainActivity.onCreate(MainActivity.java:37)
                                                                                   at android.app.Activity.performCreate(Activity.java:7125)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
                                                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:148) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5471) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) >

我有一个例外,我不知道它在哪里发生以及如果有任何更多错误请如何处理它请告诉我。

2 个答案:

答案 0 :(得分:1)

在您呼叫的MainActivity.java

name=dbh.ret_name();

dbh未被证实。

将此行添加到我上面发布的那一行:

dbh = new MyDbHandler(this);

你会解决它

答案 1 :(得分:1)

您必须实例化MyDBHandler。