null指针引用android java

时间:2013-06-04 04:20:08

标签: java android

嘿伙计们,我有一个有趣的小虫子,我一直在努力想到现在记住我是学生。想知道为什么它会发生错误显示类和错误发生的地方。谢谢你先进。

                package com.example.assignment;


          import android.app.Activity;
          import android.content.Intent;
          import android.database.Cursor;
          import android.database.SQLException;
          import android.database.sqlite.SQLiteDatabase;
          import android.os.Bundle;
          import android.util.Log;
          import android.view.Menu;
          import android.view.MenuInflater;
          import android.view.MenuItem;
          import android.view.View;
          import android.view.View.OnClickListener;
          import android.widget.Button;
          import android.widget.EditText;
          import android.widget.TextView;


    public class ViewRate extends Activity implements  OnClickListener {

private int rowID;
private TextView codetv;
private TextView signtv;
private TextView ratetv;
private final String dbName="CurrencyDB";
private final String tableName="Rates";
SQLiteDatabase sampleDB=null;   
//
EditText torate, fromrate;
Button convertto,convertfrom;
TextView conRate;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewrate);
    setViews();     
    Bundle extra=getIntent().getExtras();
    rowID=extra.getInt(MainActivity.ROW_ID); 
    fillViews();        
    convertto = (Button)findViewById(R.id.convertto);       
    convertfrom =(Button)findViewById(R.id.convertfrom);
    convertfrom.setOnClickListener(from);
    convertto.setOnClickListener(to);}

private OnClickListener to = new OnClickListener() { <-------ERROR

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //converttocur();
                       conRate.setText("pressed"); <------testing still wont work
    }
};
   private OnClickListener from = new OnClickListener() { <--------ERROR

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //convertfromcur();
        conRate.setText("pressed"); <--------testing
    }
      };

        private void convertfromcur() {
    // TODO Auto-generated method stub
    try {
        double val = Double.parseDouble(ratetv.getText().toString());
        double val2 = Double.parseDouble(fromrate.getText().toString());
        double com = (val / val2);

        conRate.setText("RATE:" + com);


    } catch (Exception e) {
        // TODO: handle exception
        conRate.setText("Error");
    }
}



private void converttocur() {
    // TODO Auto-generated method stub
    try {
        double val = Double.parseDouble(ratetv.getText().toString());
        double val2 = Double.parseDouble(torate.getText().toString());
        double com = (val * val2);          
        conRate.setText("RATE:" + com);         

    } catch (Exception e) {
        // TODO: handle exception
        conRate.setText("Error");
    }

}

private void fillViews() {
    // TODO Auto-generated method stub
    try{
        sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
        Cursor c = sampleDB.rawQuery("Select * from " +tableName+" where id                      ?", new String[] {String.valueOf(rowID)}); 
        if(c!=null && c.moveToFirst()==true){               
            String code=c.getString(c.getColumnIndex("Code"));
            String sign=c.getString(c.getColumnIndex("Sign"));
            String rate=c.getString(c.getColumnIndex("Rate"));
            codetv.setText(code);
            signtv.setText(sign);
            ratetv.setText(rate);         
        }           
    }
    catch(SQLException e){
        Log.e(getClass().getSimpleName(),"Could not open database");
    }
    finally{
        if(sampleDB!=null){
            sampleDB.close();
        }
    }
}

private void setViews() {
    // TODO Auto-generated method stub
    codetv=(TextView)findViewById(R.id.code);
    signtv=(TextView)findViewById(R.id.sign);
    ratetv=(TextView)findViewById(R.id.rate);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.viewtask,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub

    switch(item.getItemId()){
    case R.id.edit:
        getEdit();
        return true;
    case R.id.delete:
        getDelete();
        return true;
    default:
         return super.onOptionsItemSelected(item);
    }
}

private void getDelete() {
    //TODO Auto-generated method stub
    try{
        sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE,null);
        sampleDB.delete(tableName, "id= "+rowID,null);
    }

    catch(SQLException e){
        Log.e(getClass().getSimpleName(),"Could not open dB");
    }
    finally {
        if(sampleDB!=null){
            sampleDB.close();
        }

    }
}

private void getEdit(){
    //TODO Auto-generated method stub
    Intent addEdit=new Intent(this,AddEdit.class);
    addEdit.putExtra("ID",rowID);
    addEdit.putExtra("code",codetv.getText().toString());
    addEdit.putExtra("sign",signtv.getText().toString());
    addEdit.putExtra("rate",ratetv.getText().toString());
    startActivity(addEdit);
}



@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

}

   }

所以错误是按钮点击,我收到此错误消息

  E/AndroidRuntime(2524): FATAL EXCEPTION: main
  E/AndroidRuntime(2524): java.lang.NullPointerException
  E/AndroidRuntime(2524):at .example.assignment.ViewRate.converttocur(ViewRate.java:96)
  E/AndroidRuntime(2524):at com.example.assignment.ViewRate.access$0(ViewRate.java:86)
  E/AndroidRuntime(2524):at com.example.assignment.ViewRate$1.onClick(ViewRate.java:55)
  E/AndroidRuntime(2524):   at android.view.View.performClick(View.java:4202)
  E/AndroidRuntime(2524):   at android.view.View$PerformClick.run(View.java:17340)
  E/AndroidRuntime(2524):   at android.os.Handler.handleCallback(Handler.java:725)
  E/AndroidRuntime(2524):   at android.os.Handler.dispatchMessage(Handler.java:92)
  E/AndroidRuntime(2524):   at android.os.Looper.loop(Looper.java:137)
  E/AndroidRuntime(2524):at android.app.ActivityThread.main(ActivityThread.java:5039)
  E/AndroidRuntime(2524):at java.lang.reflect.Method.invokeNative(Native Method)
  E/AndroidRuntime(2524):   at java.lang.reflect.Method.invoke(Method.java:511)
  E/AndroidRuntime(2524):at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   E/AndroidRuntime(2524):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 E/AndroidRuntime(2524):    at dalvik.system.NativeStart.main(Native Method)

所以这是另一个logcat

  E/AndroidRuntime(2743): FATAL EXCEPTION: main
  E/AndroidRuntime(2743): java.lang.NullPointerException
  E/AndroidRuntime(2743):   at com.example.assignment.ViewRate$1.onClick(ViewRate.java:56)
  E/AndroidRuntime(2743):   at android.view.View.performClick(View.java:4202)
  E/AndroidRuntime(2743):   at android.view.View$PerformClick.run(View.java:17340)
  E/AndroidRuntime(2743):   at android.os.Handler.handleCallback(Handler.java:725)
  E/AndroidRuntime(2743):   at android.os.Handler.dispatchMessage(Handler.java:92)
  E/AndroidRuntime(2743):   at android.os.Looper.loop(Looper.java:137)
  E/AndroidRuntime(2743):   at android.app.ActivityThread.main(ActivityThread.java:5039)
  E/AndroidRuntime(2743):   at java.lang.reflect.Method.invokeNative(Native Method)
  E/AndroidRuntime(2743):   at java.lang.reflect.Method.invoke(Method.java:511)
  E/AndroidRuntime(2743):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 E/AndroidRuntime(2743):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  E/AndroidRuntime(2743):   at dalvik.system.NativeStart.main(Native Method)

5 个答案:

答案 0 :(得分:1)

其中一个值为null:

  • ratetv
  • torate
  • ratetv.getText()
  • torate.getText()

你不能取消引用null(实质上,你不能在null值上调用方法),所以你得到NullPointerException

答案 1 :(得分:1)

我见过您的代码,您在onCreate方法下错过了这一行来初始化 Textview conRate 所以默认情况下它初始化为null而您指的是 conRate.setText(“”)< / strong>其中 conRate 为null,这就是为什么在OnClick上获得NullPointerException的原因。

conRate =(TextView)findViewById(R.id.conRate);

希望这会对你有所帮助...... :)

答案 2 :(得分:0)

我认为您错过了onCreate()

中的以下内容
torate = (EditText) findViewById(R.id.to_rate) 
ratetv = (TextView) findViewById(R.id.rate_tv)

答案 3 :(得分:0)

Plz首先检查你的所有UI组件是否在java文件中被很好地引用。 这可能是你获得NPE的地方。

您也正在访问onCreate()方法中其他活动的意图值,因此olz确认您将获得意图值或获得空值

答案 4 :(得分:0)

  

块引用

只需更改您的代码::

  

块引用

你已经在你的活动中实现了onClickListener,所以你将获得它的覆盖方法onClick所以只需在该方法中有条件地写你的按钮点击事件

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 if(v.getId == R.id.convertto)
 {
   //Here write you code when converTo button Clicked
 }
 else if(v.getId == R.id.converfrom)
 {
    //Here write your code when converfrom button clicked 
 }

}