App crashes when webview.loadUrl is used in onCreate - java

I have a webview and i want it to load a url as soon as the app starts.
If I call loadURL() on the press of a button it works perfectly but when I try to load the url inside onCreate() the app crashes.
WebView myWebView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void loadURL(View view) {
myWebView = (WebView) findViewById(R.id.WebView);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("http://www.google.com");
}
The app crashes when I use this:
WebView myWebView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
myWebView = (WebView) findViewById(R.id.WebView);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("http://www.google.com");
}
EDIT**
This is what i am getting in my console.
[2014-06-14 19:33:58 - ddms] Can't bind to local 8700 for debugger
[2014-06-14 19:34:11 - ddms] null
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:200)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:665)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
[2014-06-14 19:34:12 - ddms] null
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:200)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:665)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
EDIT**
Here is the logcat output
06-14 19:53:22.677: D/AndroidRuntime(8075): Shutting down VM
06-14 19:53:22.677: W/dalvikvm(8075): threadid=1: thread exiting with uncaught exception (group=0x41c11c80)
06-14 19:53:22.677: E/AndroidRuntime(8075): FATAL EXCEPTION: main
06-14 19:53:22.677: E/AndroidRuntime(8075): Process: com.myapp.myapp, PID: 8075
06-14 19:53:22.677: E/AndroidRuntime(8075): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.MainActivity}: java.lang.NullPointerException
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2277)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.ActivityThread.access$800(ActivityThread.java:145)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.os.Handler.dispatchMessage(Handler.java:102)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.os.Looper.loop(Looper.java:136)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.ActivityThread.main(ActivityThread.java:5088)
06-14 19:53:22.677: E/AndroidRuntime(8075): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 19:53:22.677: E/AndroidRuntime(8075): at java.lang.reflect.Method.invoke(Method.java:515)
06-14 19:53:22.677: E/AndroidRuntime(8075): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
06-14 19:53:22.677: E/AndroidRuntime(8075): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-14 19:53:22.677: E/AndroidRuntime(8075): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:133)
06-14 19:53:22.677: E/AndroidRuntime(8075): at dalvik.system.NativeStart.main(Native Method)
06-14 19:53:22.677: E/AndroidRuntime(8075): Caused by: java.lang.NullPointerException
06-14 19:53:22.677: E/AndroidRuntime(8075): at com.myapp.myapp.MainActivity.onCreate(MainActivity.java:27)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.Activity.performCreate(Activity.java:5310)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-14 19:53:22.677: E/AndroidRuntime(8075): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
06-14 19:53:22.677: E/AndroidRuntime(8075): ... 12 more
Just for any use here is the complete MainActivity.java
package com.myapp.myapp;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
myWebView = (WebView) findViewById(R.id.WebView);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}

Solved it!
I finally came across this.
#Override
protected void onStart()
{
super.onStart();
myWebView = (WebView) findViewById(R.id.WebView);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("http://www.google.com");
}
Apparently the fragment wasn't loaded immediately
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
This takes some time to process so onStart which is executed after this did the work perfectly.

this works on mine
For Local File
WebView webView =(WebView) findViewById(R.id.webView1);
webView.loadUrl("file:///android_asset/programs.htm");
make sure you have the file in this case the file programs.htm is stored on the Assets folder on android
For Website
WebView webView =(WebView) findViewById(R.id.webView1);
webView.loadUrl("http://www.facebook.com");
it will direct you whatever destination you desire in this case Facebok.com
hope this helps you...

Related

App crashes with intent method

my app crash every time when I try to use the intentmethod.
MainActivity.java
package de.kwietzorek.fulcrumwebview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String selected;
Spinner spinner;
WebView myWebView;
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(this, AddIP.class);
this.startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//WebView
myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
//JavaScript enable
webSettings.setJavaScriptEnabled(true);
//Server name spinner
ArrayList<String> server_name_list = getIntent().getStringArrayListExtra(
"int_new_server_name");
spinner = (Spinner) findViewById(R.id.server_spinner);
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
//WebVie Client
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}
AddIP.java
package de.kwietzorek.fulcrumwebview;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class AddIP extends AppCompatActivity {
Button btn_back, btn_add;
EditText server_ip, server_name;
String new_server_ip, new_server_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ip);
server_ip = (EditText)this.findViewById(R.id.edit_server_address);
server_name = (EditText)this.findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button)findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button)findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*new_server_ip = server_ip.getText().toString();
MainActivity.server_array_ip.add(new_server_ip);*/
ArrayList<String> server_name_list = new ArrayList<String>();
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
Intent intent = new Intent(AddIP.this, MainActivity.class);
intent.putStringArrayListExtra("int_server_name_list", server_name_list);
}
});
}
}
Error
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: FATAL EXCEPTION: main
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: Process: de.kwietzorek.fulcrumwebview, PID: 4035
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsSpinner.setAdapter(AbsSpinner.java:115)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.Spinner.setAdapter(Spinner.java:508)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.widget.AppCompatSpinner.setAdapter(AppCompatSpinner.java:383)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at de.kwietzorek.fulcrumwebview.MainActivity.onCreate(MainActivity.java:75)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6237)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
11-13 22:13:49.542 4035-4035/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Look in MainActivity
//Server name spinner
ArrayList<String> server_name_list = getIntent().getStringArrayListExtra(
"int_new_server_name");
And in AddIP
intent.putStringArrayListExtra("int_server_name_list", server_name_list);
Your key (name) is different, so you are trying to get something that doesn't exist, thats why NullPointerException is thrown.
Code for your MainActivity
package de.kwietzorek.fulcrumwebview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String selected;
Spinner spinner;
WebView myWebView;
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(this, AddIP.class);
this.startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//WebView
myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
//JavaScript enable
webSettings.setJavaScriptEnabled(true);
//Server name spinner
ArrayList<String> server_name_list = getIntent().getStringArrayListExtra(
"int_new_server_name");
if (server_name_list != null) {
spinner = (Spinner) findViewById(R.id.server_spinner);
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
//WebVie Client
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}
Change
ArrayList<String> server_name_list = null;
to
ArrayList<String> server_name_list = new ArrayList<String>();
since server_name_list is null, a NullPointerException is thrown when you get to server_name_list.add(new_server_name);, and the execution fails.

When I clicked the generate1 button, It crashes. SharedPreferences Related Issue

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
SharedPreferences mySharedPreferences;
TextView t1,t2;
Button generate1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
t1 = (TextView) findViewById(R.id.textView3);
t2 = (TextView) findViewById(R.id.textView8);
generate1 = (Button) findViewById(R.id.button);
generate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random rand = new Random();
int num1 = rand.nextInt(100);
int num2 = mySharedPreferences.getInt("INT_KEY", -1);
if(num2 == -1) {
num2 = 0; //initialize the total count value to 0
}
if (num1 % 2 == 0) {
num2 += 1;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("INT_KEY", num2);
editor.commit();
t1.setText("" + num2);
}
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
What I want to do is :
1.Check Whether Num2 value is exist or not, If not set to zero.
2.Randomly Generate new numbers 0~100 in num1
3.If num1 is Even, Increase num2 by 1.
4.Save Value and Repeat.
When I clicked the button, It crashes. What could be the reason?
Logcat:
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 D/AndroidRuntime: Shutting down VM
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x423dcc08)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: FATAL EXCEPTION: main
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: Process: com.example.tans.goldminer1, PID: 30860
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: java.lang.NullPointerException
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at com.example.tans.goldminer1.MainActivity$1.onClick(MainActivity.java:35)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at android.view.View.performClick(View.java:4753)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:19567)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:733)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:146)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5635)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
10-30 13:39:36.418 30860-30860/com.example.tans.goldminer1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
Add mySharedPreferences = PreferenceManeger.getDefaultSharedPreferences(this) to your code before you use it. (As assumed that you want to use default preferences.)

Null pointer exception on CursorAdapter

I am getting a NullPointerException. Below you can find my Logcat and the relevant code.
Logcat:
12-23 00:17:35.330: E/AndroidRuntime(2019): FATAL EXCEPTION: main
12-23 00:17:35.330: E/AndroidRuntime(2019): Process: com.android.timesheet, PID: 2019
12-23 00:17:35.330: E/AndroidRuntime(2019): java.lang.NullPointerException
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.timesheet.adapter.CustomCursorAdapter$1.onClick(CustomCursorAdapter.java:54)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View.performClick(View.java:4438)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View$PerformClick.run(View.java:18422)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.handleCallback(Handler.java:733)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.dispatchMessage(Handler.java:95)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Looper.loop(Looper.java:136)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.app.ActivityThread.main(ActivityThread.java:5017)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invoke(Method.java:515)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-23 00:17:35.330: E/AndroidRuntime(2019): at dalvik.system.NativeStart.main(Native Method)
CustomCursorAdapter.java:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.android.timesheet.ModifyMember;
import com.android.timesheet.R;
public class CustomCursorAdapter extends CursorAdapter {
Button delete_btn;
TextView memID_tv, memName_tv;
#SuppressWarnings("deprecation")
public CustomCursorAdapter(Activity context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
memID_tv = (TextView)v.findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
String memberID_val = memID_tv.getText().toString();; ---->54th Line
String memberName_val = memName_tv.getText().toString();
Intent i = new Intent(context,
ModifyMember.class);
i.putExtra("memberName", memberName_val);
i.putExtra("memberID", memberID_val);
((Activity)context).startActivity(i);
}
});
}
}
I am using a delete button to delete all the listview row items. At that point I am getting the NullPointerException.
Use view(view of row) instead of v parameter of onClick method which is view of Button :
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setTag(view);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowview=(View)v.getTag();
memID_tv = (TextView)rowview.findViewById(R.id.member_id);
memName_tv = (TextView)rowview.findViewById(R.id.member_name);
}
});
Use view instead of v
memID_tv = (TextView)view.findViewById(R.id.member_id);
In bindview try this-
if (view == null) {
view = inflater.inflate(R.layout.single_row_item, parent, null);
}
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
.
.
.
you are getting the view from clicked view, but you have to get the views from the root view.
memID_tv = (TextView)v. findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
change these lines into this:
memID_tv = (TextView)view. findViewById(R.id.member_id);
memName_tv = (TextView)view.findViewById(R.id.member_name);

Error while building test sliding menu

Hi I followed a tutorial I am trying to test sliding menu (Navigation drawer) in android but I am continuously getting these error in logcat. Please help me or give me some idea so that I can proceed to resolve the issue.HELP................
2-12 18:37:43.976: E/Trace(698): error opening trace file: No such file or directory (2)
02-12 18:37:44.666: I/System.out(698): activity started-----------
02-12 18:37:44.666: I/System.out(698): 3
02-12 18:37:44.676: D/AndroidRuntime(698): Shutting down VM
02-12 18:37:44.676: W/dalvikvm(698): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-12 18:37:44.696: E/AndroidRuntime(698): FATAL EXCEPTION: main
02-12 18:37:44.696: E/AndroidRuntime(698): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.navigationdrawertest/com.example.navigationdrawertest.HomeActivity}: java.lang.NullPointerException
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.os.Looper.loop(Looper.java:137)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 18:37:44.696: E/AndroidRuntime(698): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 18:37:44.696: E/AndroidRuntime(698): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 18:37:44.696: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 18:37:44.696: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 18:37:44.696: E/AndroidRuntime(698): at dalvik.system.NativeStart.main(Native Method)
02-12 18:37:44.696: E/AndroidRuntime(698): Caused by: java.lang.NullPointerException
02-12 18:37:44.696: E/AndroidRuntime(698): at com.example.navigationdrawertest.HomeActivity.onCreate(HomeActivity.java:40)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.Activity.performCreate(Activity.java:5008)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
02-12 18:37:44.696: E/AndroidRuntime(698): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
02-12 18:37:44.696: E/AndroidRuntime(698): ... 11 more
02-12 18:37:48.396: I/Process(698): Sending signal. PID: 698 SIG: 9
Also my HomeActivity.java file
package com.example.navigationdrawertest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.navigationdrawertest.operatingsystemfragment.*;
public class HomeActivity extends Activity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence title;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
System.out.println("activity started-----------");
title = getActionBar().getTitle();
mPlanetTitles = getResources().getStringArray(R.array.operating_systems);
System.out.println(mPlanetTitles.length);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.nav_drawer,R.id.content_frame, mPlanetTitles));
System.out.println("adapater set to list");
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(title);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Open Drawer");
}
};
// Set the drawer toggle as the DrawerListener and then Drawer layout will listen on Drawertoggle
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
System.out.println("on create method completed");
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
System.out.println("DrawerItemClickListener");
selectItem(position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings selected", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
System.out.println("selectItem called");
// create a new fragment and specify the planet to show based on position
Fragment fragment = new OperatingSystemFragment();
Bundle args = new Bundle();
args.putInt(OperatingSystemFragment.ARG_OS, position);
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
getActionBar().setTitle((mPlanetTitles[position]));
mDrawerLayout.closeDrawer(mDrawerList);
}
}
I have to use navigation drawer in API 8 so using support packages. Please help me.
Either your mDrawerList is null or mPlanetTitles is null. Check them both at the debugger.
2-12 18:37:43.976: E/Trace(698): error opening trace file: No such file or directory (2)
The error You are facing is in this line of code
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.nav_drawer,R.id.content_frame, mPlanetTitles));
mPlanetTitles seems to be null

Android nullPointerException error

Eclipse finds no errors in my code, but when I try to run the app on an emulator, it opens and then immediately crashes. Logcat gives me the vague nullPointerException error. I can comment out the onKeyDown method, and then it runs just fine. But of course, I can't use the back key to go back, it will just close out the app.
My code is as follows:
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class MainActivity extends Activity {
static String[] items = {"Campaign", "Multiplayer", "Zombies"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
listView.setAdapter(new BaseAdapter(){
public int getCount() {
return items.length;
}
public Object getItem(int position) {
return items[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_row, null);
TextView textView = (TextView) view.findViewById(R.id.TextView01);
textView.setText(items[position]);
textView.setTextColor(Color.rgb(255,106,0));
textView.setTextSize(24);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setTextColor(Color.rgb(255,106,0));
return view;
}});
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (position == 0) {
viewflipper.showNext();
}if (position == 1) {
viewflipper.showNext();
viewflipper.showNext();
}if (position == 2) {
viewflipper.showNext();
viewflipper.showNext();
viewflipper.showNext();
}}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if(viewflipper.getDisplayedChild() == 0){
viewflipper.showPrevious();
}if(viewflipper.getDisplayedChild() == 1){
viewflipper.showPrevious();
viewflipper.showPrevious();
}if(viewflipper.getDisplayedChild() == 2){
viewflipper.showPrevious();
viewflipper.showPrevious();
viewflipper.showPrevious();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
};
My Logcat is as follows:
01-21 11:38:46.151: E/AndroidRuntime(760): FATAL EXCEPTION: main
01-21 11:38:46.151: E/AndroidRuntime(760): java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.blackopsiiexperience/com.example.blackopsiiexperience.MainActivity}: java.lang.NullPointerException
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.os.Looper.loop(Looper.java:137)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 11:38:46.151: E/AndroidRuntime(760): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-21 11:38:46.151: E/AndroidRuntime(760): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-21 11:38:46.151: E/AndroidRuntime(760): at dalvik.system.NativeStart.main(Native Method)
01-21 11:38:46.151: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.Activity.findViewById(Activity.java:1839)
01-21 11:38:46.151: E/AndroidRuntime(760): at com.example.blackopsiiexperience.MainActivity.<init>(MainActivity.java:73)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.Class.newInstanceImpl(Native Method)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.Class.newInstance(Class.java:1319)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
01-21 11:38:46.151: E/AndroidRuntime(760): ... 11 more
Any suggestions?
move
ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
inside onCreate of Activity after setting layout for Activity
EDIT :
declare Viewflipper as class level field to access it through out class instead of method level as :
public class MainActivity extends Activity {
static String[] items = {"Campaign", "Multiplayer", "Zombies"};
ListView listView;
ViewFlipper viewflipper; //<<<< declare here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
//your code here.....

Categories