This is a test app using simple android webview function. But I encountered fatal error in below when I pressed back button to go back to previous web page;
"java.lang.NullPointerException: Attempt to invoke virtual method
'boolean android.webkit.WebView.canGoBack()' on a null object
reference"
There are main page (MainActivity.java) and Web view page (WebviewPage.java).
I tried to fix this error through googling over and over ... but I couldn't.
Thanks in advance.
MainActivity.java
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);}
public void onClick(View view) {
Intent intent1 = new Intent (this, WebViewPage.class);
intent1.putExtra("name","https://Google.com");
startActivity(intent1);
}
}
WebViewPage.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewPage extends Activity {
Intent intent;
WebView webView;
//key down
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
WebView webView =(WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
intent = getIntent();
String name = intent.getExtras().getString("name");
webView.loadUrl(name);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(getString(R.string.app_name));
mToolbar.setNavigationIcon(R.drawable.ic_home_black_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
You have two webView variables inside of class and inside of 'onCreate'
Remove webView variables in onCreate.
Example)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewPage extends Activity {
Intent intent;
WebView webView;
//key down
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
intent = getIntent();
String name = intent.getExtras().getString("name");
webView.loadUrl(name);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(getString(R.string.app_name));
mToolbar.setNavigationIcon(R.drawable.ic_home_black_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
Related
I am learning Android and I have build a simple Android app that shows Toasts for starters.
In the main activity I have a button that when I press it it shows a Toast and another button that takes you to another activity. This is the code:
package ro.serbab.notes;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.addnotexml);
}
});
Button button2 = (Button) findViewById(R.id.button5);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Serban Android",
Toast.LENGTH_SHORT).show();
}
});
}
}
This is the second activity:
package ro.serbab.notes;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import ro.serbab.notes.R;
public class addnote extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addnotexml);
Button button3 = (Button) findViewById(R.id.button2);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Serban
Android",Toast.LENGTH_SHORT).show();
}
});
}
}
The button from the second activity doesn't show any toast. I keep pressing it and it doesn't work.
remove setContentView(R.layout.addnotexml); this line from onClick and add
when you want to go 2nd activity onClick the button this code will help you out
Intent intent = new Intent(MainActivity.this, 2ndActivity.class);
startActivity(intent);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
i just followed a video tutorial on youtube to make a note application and I've done the same exact code with the tutorial. So whenever i want to go to Edit activity from detail activity by clicking the menu icon, the app just crashed and show an error log like this.
java.lang.NullPointerException: Attempt to invoke virtual method 'long com.example.dairyapp.Diary.getID()' on a null object reference
at com.example.dairyapp.Details.onOptionsItemSelected(Details.java:67)
I've read the similiar question but i still dont understand what's wrong with it, any tips ?
the error log refer to this lines in detail activity
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.editDiary){
Intent i = new Intent(this,Edit.class);
i.putExtra("ID",diary.getID());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
details.java
package com.example.dairyapp;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends AppCompatActivity {
TextView mDetails;
DiaryDatabase db;
Diary diary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDetails = findViewById(R.id.detailsDairy);
Intent i = getIntent();
Long id = i.getLongExtra("ID",0);
db = new DiaryDatabase(this);
Diary diary = db.getDiary(id);
getSupportActionBar().setTitle(diary.getJudul());
mDetails.setText(diary.getIsi());
Toast.makeText(this, "Tittle => "+ diary.getJudul(), Toast.LENGTH_SHORT).show();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.deleteDiary(diary.getID());
Toast.makeText(getApplicationContext(), "Kegiatan Berhasil Dihapus", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.editDiary){
Intent i = new Intent(this,Edit.class);
i.putExtra("ID",diary.getID());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Edit.java
package com.example.dairyapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import java.util.Calendar;
public class Edit extends AppCompatActivity {
Toolbar toolbar;
EditText juduldiary,isidiary;
Calendar c;
String todaysDate;
String currentTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
Intent i = getIntent();
Long id = i.getLongExtra("ID",0);
DiaryDatabase db = new DiaryDatabase(this);
Diary diary = db.getDiary(id);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(diary.getJudul());
}
}
Its because the dairy object at class never has never been initialized. Update the Details class onCreate method as follows:
public class Details extends AppCompatActivity {
TextView mDetails;
DiaryDatabase db;
Diary diary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDetails = findViewById(R.id.detailsDairy);
Intent i = getIntent();
Long id = i.getLongExtra("ID",0);
db = new DiaryDatabase(this);
diary = db.getDiary(id); // use class level variable here
getSupportActionBar().setTitle(diary.getJudul());
mDetails.setText(diary.getIsi());
Toast.makeText(this, "Tittle => "+ diary.getJudul(), Toast.LENGTH_SHORT).show();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.deleteDiary(diary.getID());
Toast.makeText(getApplicationContext(), "Kegiatan Berhasil Dihapus", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
i get some problem when i use the intent, he said "cannot resolve constructor Intent('....')" , i dont know what is wrong in my code but you can see what i m importing here
package com.example.noen.myintentapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn_move);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_move:
Intent intn = new Intent(MainActivity.this,target1.class);
break;
}
}
}
In order to extend AppCompatActivity in a MainActivity.java file, the following was migrated from:
package me.site.site;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://third.second.tld/");
mWebView.setWebViewClient(new com.androidwebviewapp.karthik.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
return super.onCreateOptionsMenu(menu);
}
}
To
package me.site.site;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("https://third.second.tld/");
mWebView.setWebViewClient(new me.site.site.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item=menu.findItem(R.id.share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
** mShareActionProvider.setOnShareTargetSelectedListener(this); **
return(super.onCreateOptionsMenu(menu));
}
}
complains with an error referring to the code highlighted above
Error:(67, 33) error: method setOnShareTargetSelectedListener in class
ShareActionProvider cannot be applied to given types;
required: OnShareTargetSelectedListener
found: MainActivity
reason: actual argument MainActivity cannot be converted to OnShareTargetSelectedListener by method invocation conversion
I have been having a issue with a webview backbutton. I've never had this issue before regarding webview backbutton.
When I push the back button the logcat gives me the following error:
12-05 23:56:23.264: W/KeyCharacterMap(3743): Load KCM of non-default device may incur unexpected result
12-05 23:56:23.264: W/UnimplementedWebViewApi(3743): Unimplemented WebView method onKeyDown called from: android.webkit.WebView.onKeyDown(WebView.java:2323)
I've never seen this error before. Does anyone have a idea on what could be causing this?
Code:
package org.development;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class ImagenesActivity extends Activity {
ListView list;
Intent intent;
TextView toma_foto;
Button button_foto;
ImageAdapter adapter;
private WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagenesactivity);
toma_foto = (TextView) findViewById(R.id.toma_foto);
button_foto = (Button) findViewById(R.id.button_foto);
list=(ListView)findViewById(R.id.list);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);
mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new WebViewClient());
mWebView.clearCache(true);
mWebView.loadUrl("about:blank");
mWebView.clearView();
mWebView.loadUrl("http://mysite23.com/activity");
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
//view.loadUrl("javascript:document.getElementsByClassName('elgg-page-header').style.visibility='hidden';alert('testing');");
}
});
File file = new File(Environment.getExternalStorageDirectory() + "/genx/");
String[] filas = file.list();
if(filas==null)
filas = new String[0];
adapter=new ImageAdapter(this, filas);
list.setAdapter(adapter);
}
public void foto (View view){
/**We send to the camera Activity*/
//Intent j = new Intent(this, CameraActivity.class);
//startActivity(j);
//finish();
mWebView.loadUrl("about:blank");
mWebView.clearView();
mWebView.loadUrl("http://mysite23.com/activity");
}
public class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack() == true) {
mWebView.goBack();
} else {
ImagenesActivity.super.onBackPressed(); //Replace MyActivity With the name of your activity.
}
}
}