2017-06-14 73 views
-2

我得到「嘗試上的調用虛擬方法‘android.text.Editable android.widget.EditText.getText()’空對象引用「每當我點擊按鈕。請幫助「android.text.Editable android.widget.EditText.getText()」上的空對象引用

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

     edt = (EditText) findViewById(R.id.edit); 
     b1 = (Button) findViewById(R.id.button); 

     b1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(MainActivity.this, Main2Activity.class); 
       startActivity(i); 
      } 
     }) 
    } 

    String tt(){ 
     return (edt.getText()+""); 
    } 


public class Main2Activity extends AppCompatActivity { 
    MainActivity ob = new MainActivity(); 
    private WebView mywebview; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main2); 
     mywebview=(WebView)findViewById(R.id.abc); 
     WebSettings webSettings=mywebview.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     mywebview.loadUrl(ob.tt()); 
     mywebview.setWebViewClient(new WebViewClient()); 
    } 
} 

回答

1

MainActivity ob = new MainActivity();會得到你這個類而不是實際的當前正在運行如此ob在這種情況下無用的一個簡單的對象,刪除ob相關的代碼,並使用Intent來傳遞數據

在第一MainActivity

b1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(MainActivity.this, Main2Activity.class); 
       i.putExtra("data",edt.getText().toString()); 
       //    ^^^^ pass data 
       startActivity(i); 
      } 
     }) 

Main2Activity

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main2); 
     mywebview=(WebView)findViewById(R.id.abc); 
     WebSettings webSettings=mywebview.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     mywebview.loadUrl(getIntent().getStringExtra("data")); 
            // ^^^^^ 
     mywebview.setWebViewClient(new WebViewClient()); 
    } 

也讀取How do I pass data between Activities in Android application?

相關問題