简体   繁体   English

空指针引用android java

[英]null pointer reference android java

Hey guys i have funny little bug that i have been trying to figure now keep in mind i am student. 大家好,我有一个有趣的小虫子,现在我想着要记住,我是学生。 Would like to know why it is happening ill display the class and where the error is occuring. 想知道为什么会发生这种情况,因为在类显示时以及错误发生在哪里。 Thankyou in advanced. 谢谢。

                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

}

   }

And so the error is on the button clicks and i getting this error message 所以错误是在按钮点击,我得到这个错误信息

  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)

so here is the other logcat 所以这是另一个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)

One of these values is null: 这些值之一为null:

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

You cannot dereference null (essentially, you cannot call methods on a null value), so you get a NullPointerException . 您不能取消引用null(本质上,您不能在null值上调用方法),因此您会收到NullPointerException

I have seen your code, you missed this line under onCreate method to initialize the Textview conRate so by default it initialize by null and you are referring conRate.setText("") where conRate is null thats why you are getting NullPointerException on OnClick. 我已经看到你的代码,你错过下onCreate方法这一行初始化的TextView conRate所以默认情况下它由空初始化和你是指conRate.setText(“”),其中conRate就是为什么你在的OnClick得到NullPointerException异常空,多数民众赞成。

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

Hope this will help you...:) 希望这个能对您有所帮助...:)

I think you have missed the following in your onCreate() 我认为您在onCreate()错过了以下内容

torate = (EditText) findViewById(R.id.to_rate) 
ratetv = (TextView) findViewById(R.id.rate_tv)

Plz first check your all UI components are referenced well in your java file means in activity. 请先检查您的所有UI组件是否在您的java文件中被良好引用。 this may be the place where you get NPE. 这可能是您获得NPE的地方。

also you are accessing intent value from other activity in onCreate() method so olz confirm that you will get value in intent or you get null value 同样,您正在onCreate()方法中从其他活动访问意图值,所以olz确认您将获得意图中的值或获得空值

Blockquote 大段引用

just change your code:: 只需更改您的代码::

Blockquote 大段引用

you have implemented onClickListener in your activity so definetly you will get it's override method onClick so just in that method write your button click event conditionally like 您已经在活动中实现了onClickListener,因此可以肯定地得到它的覆盖方法onClick,因此只需在该方法中有条件地编写按钮click事件,例如

 @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 
 }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM