App crashes with intent method - java

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.

Related

Unable to start activity ComponentInfo{Activity}: android.view.InflateException: Binary XML file line #12: Error inflating class fragment

I am developing an application which uses google map APIs. In my application i want to show google map and set marker on my current location by getting my device latitude and longitude from GPS. In beginning when i was implement following code that works well, i test it on my device but after installing 15 or 20 times on my mobile device it starts crashing automatically although i didn't do anything on that activity.
The logs which are showing me android studio are following
Logs
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: FATAL EXCEPTION: main
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: Process: com.example.nabeelfarooq.mapsnavapplication, PID: 9110
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nabeelfarooq.mapsnavapplication/com.example.nabeelfarooq.mapsnavapplication.MainActivity}: android.view.InflateException: Binary XML file line #12: Error inflating class fragment
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:162)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.os.Looper.loop(Looper.java:189)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5529)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class fragment
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at com.example.nabeelfarooq.mapsnavapplication.MainActivity.onCreate(MainActivity.java:59)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5966)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:162) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.os.Looper.loop(Looper.java:189) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5529) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
09-24 16:30:43.414 9110-9110/com.example.nabeelfarooq.mapsnavapplication E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to get length of null array
MainActivity
import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.Console;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener, GoogleApiClient.OnConnectionFailedListener {
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
public static double latitude;
public static double longitude;
private Button button;
private LatlngAdapter databasedata = null;
final int REQUEST_CODE_ASK_PERMISSIONS = 123;
#TargetApi(Build.VERSION_CODES.M)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SearchActivity.class);
i.putExtra("latitude", latitude);
i.putExtra("longitude", longitude);
startActivity(i);
}
});
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else {
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = fm.getMap();
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE_ASK_PERMISSIONS);
return;
}
else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
buildGoogleApiClient();
onMapReady(mMap);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
supportMapFragment.getMapAsync(this);
}
public void turnGPSOn() {
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
alertDialogBuilder
.setMessage("GPS is disabled in your device. Enable it?")
.setCancelable(false)
.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
/** Here it's leading to GPS setting options*/
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onPause(){
super.onPause();
mGoogleApiClient.disconnect();
}
//obtain the supportMapFragment and get notified when the map is ready to be used
protected synchronized void buildGoogleApiClient(){
if(mGoogleApiClient==null){
mGoogleApiClient=new GoogleApiClient.Builder(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager=getFragmentManager();
android.support.v4.app.FragmentManager fragmentManager1=getSupportFragmentManager();
// Handle navigation view item clicks here.
int id = item.getItemId();
if(supportMapFragment.isAdded()) {
fragmentManager1.beginTransaction().hide(supportMapFragment).commit();
}
if (id == R.id.nav_home) {
//fragmentManager1.beginTransaction().add(R.id.map,supportMapFragment).commit();
// Handle the home action
} else if (id == R.id.nav_about_us) {
Intent intent=new Intent(this,About_us_Activity.class);
startActivity(intent);
} else if (id == R.id.nav_contact_us){
Intent intent=new Intent(this,Contact_us_Activity.class);
startActivity(intent);
} else if (id == R.id.nav_Rate_app) {
Intent intent=new Intent(this,TipsActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap =googleMap;
LatLng lahore=new LatLng(latitude,longitude);
//mMap.addMarker(new MarkerOptions().title("lahore").snippet("lahore HQ").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position(sydney));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onMyLocationChange(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
LatLng latLng=new LatLng(latitude,longitude);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
LatLng lahore=new LatLng(latitude,longitude);
//mMap.addMarker(new MarkerOptions().title("You are here").snippet("lahore").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position(lahore));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(lahore));
}
public void onConnected(Bundle bundle){
Log.d("CONNECTED", "I am connected");
mLastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation!=null){
Log.d("Latitude",String.valueOf(mLastLocation.getLatitude()));
Log.d("Longitude",String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
static String latString =Double.toString(latitude);
static String lonString =Double.toString(longitude);
}
content_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context=".MainActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:layout_alignParentBottom="true"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"
tools:layout="#layout/abc_action_bar_up_container"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Me Somewhere"
android:id="#+id/button"
android:background="#5368ed"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="31dp"
/>
</RelativeLayout>
EDIT: A user has pointed that this bug is happening also in 7.0 devices, so keep in mind that you may change android:maxSdkVersion="22" to an appropiate Sdk version.
The problem is only happening in 5.1.1 devices with custom roms like Resurrection Remix. I don't know the reason, but you can solve it adding this to your manifest, as seen in https://stackoverflow.com/a/39696819/4208583.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="22" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="22" />
Remove action bar in manifest by specifying NoActionBar theme

error java app Android

I have a problem and I do not understand the reason why. I'm working on Android Studio on Linux. The bitmap size is 10x10 pixels. I searched in google, but it gave me nothing. I would be grateful if someone could help me.
This problem is something with this:
"Bitmap suweren = BitmapFactory.decodeResource(getResources(), R.drawable.suweren);"
and this is error log:
"12-30 07:16:36.125 9336-9336/com.example.szczesciarz.sawa E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.szczesciarz.sawa, PID: 9336
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.szczesciarz.sawa/com.example.szczesciarz.sawa.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:98)
at android.support.v7.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:91)
at android.support.v7.app.ToolbarActionBar.<init>(ToolbarActionBar.java:73)
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:205)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at com.example.szczesciarz.sawa.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
12-30 07:21:36.565 9336-9336/com.example.szczesciarz.sawa I/Process: Sending signal. PID: 9336 SIG: 9"
Main Activity_code:
package com.example.szczesciarz.sawa;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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);
}
}
GameView code:
package com.example.szczesciarz.sawa;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
class GameView extends View{
public GameView(Context context){
super(context);
}
#Override
public void onDraw(Canvas canvas ){
Bitmap suweren = BitmapFactory.decodeResource(Context.getResources(), R.drawable.suweren);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(suweren, 0, 0, null);
}
}
Thanks):-
Toolbar cannot be found :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
So when you call
setSupportActionBar(toolbar);
You have a NullPointerException at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
try to remove setSupportActionBar(toolbar)
Make sure that your layout file contains toolbar or you have included the toolbar layout.
This exception occurs when your layout file does not contain the id, so android is unable to get the view from that id and returns null when you call findViewById(R.id.toolbar);

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.)

Function in fragment makes emulator crash

Error occurs when I place a function inside onCreateView in menu1_Fragment.java. Sorry in advance as I will be placing my logs in as well so it might make my post a bit big so I will tell you the layout. I am new sorry for the loads of questions.
The code works perfectly if I just don't put the function setClick() inside my fragment. quick note the function basically makes my image in menu1_layout.xml a 3 way button aka start stop reset where when you reset, it pops up a toast of exact time you got
1) menu1_Fragment.java
public class menu1_Fragment extends Fragment {
Chronometer mChronometer;
int loop = 0;
double startTime;
double millis;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
setClick();
return rootview;
}
Button button;
public void setClick() {
mChronometer = (Chronometer) getActivity().findViewById(R.id.aChronometer);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
}
View.OnClickListener mStartListener = new View.OnClickListener() {
public void onClick(View v) {
if (loop == 0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
startTime = System.currentTimeMillis();
loop++;
} else if (loop == 1) {
mChronometer.stop();
millis = System.currentTimeMillis()-startTime;
loop++;
} else if (loop == 2) {
mChronometer.setBase(SystemClock.elapsedRealtime());
Context context = getActivity().getApplicationContext();
CharSequence text = "Your Time is: " + (millis/1000);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
loop = 0;
}
}
};
}
2) LOGS
10-28 16:52:26.552 2912-2912/app.z0nen.menu D/AndroidRuntime: Shutting down VM
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: FATAL EXCEPTION: main
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Process: app.z0nen.menu, PID: 2912
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{app.z0nen.menu/app.z0nen.slidemenu.MyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.setClick(menu1_Fragment.java:39)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.onCreateView(menu1_Fragment.java:26)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Fragment.performCreateView(Fragment.java:2220)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.BackStackRecord.run(BackStackRecord.java:793)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentController.execPendingActions(FragmentController.java:325)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Activity.performStart(Activity.java:6252)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
10-28 16:52:28.662 2912-2912/? I/Process: Sending signal. PID: 2912 SIG: 9
3) MyActivity.Java
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.my, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
4) Menu1_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Chronometer
android:id="#+id/aChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textColor="#111111"
android:layout_marginTop="27dp"
android:layout_below="#+id/stopWatch"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/stopWatch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/stopwatch2"
android:layout_marginTop="38dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
You can't use getActivity() from onCreateView() as the fragment's activity has not been created yet. You should use not use getActivity() until onActivityCreated() is called, or better yet, use the rootview you inflated to do your findViewByID() calls.
Also, you are initializing your button three times. You should get rid on two of them :)
Change
button = (Button) getActivity().findViewById(R.id.stopWatch);
to this:
button = (Button) findViewById(R.id.stopWatch);
Your button is inside your fragment's layout, not the activity's.
EDIT:
Make your button a member variable, so that you could access it from the onCreateView & setClick methods:
private Button mButton;
And we need to save a reference of your button in the onCreateView method to this: (rootview is your fragment's inflated layout)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
mButton = rootview.findViewById(R.id.stopWatch);
setClick();
return rootview;
}
and in the setClick method put this instead :
mButton.setOnClickListener(mStartListener);

Nullpointer exception - FragmentActivity

I have received a nullpointer exception error in my fragmentactivity.
Below is the log cat:
11-04 06:29:51.550: E/AndroidRuntime(19286): FATAL EXCEPTION: main
11-04 06:29:51.550: E/AndroidRuntime(19286): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.MainActivity}: java.lang.NullPointerException
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.os.Looper.loop(Looper.java:137)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-04 06:29:51.550: E/AndroidRuntime(19286): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 06:29:51.550: E/AndroidRuntime(19286): at java.lang.reflect.Method.invoke(Method.java:511)
11-04 06:29:51.550: E/AndroidRuntime(19286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-04 06:29:51.550: E/AndroidRuntime(19286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 06:29:51.550: E/AndroidRuntime(19286): at dalvik.system.NativeStart.main(Native Method)
11-04 06:29:51.550: E/AndroidRuntime(19286): Caused by: java.lang.NullPointerException
11-04 06:29:51.550: E/AndroidRuntime(19286): at com.dooba.beta.MainActivity.onCreate(MainActivity.java:51)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.Activity.performCreate(Activity.java:5008)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-04 06:29:51.550: E/AndroidRuntime(19286): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-04 06:29:51.550: E/AndroidRuntime(19286): ... 11 more
I believe the error occurs within these lines:
mDrawerList.setAdapter(new ArrayAdapter<String>(getActionBar()
.getThemedContext(), android.R.layout.simple_list_item_1,
mOptionMenu));
Below is the entire activity code:
import android.app.ActionBar;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mOptionMenu = new String[] { "Opción 1", "Opción 2", "Opción 3" };
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout)
findViewById(R.id.left_drawer);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(getActionBar()
.getThemedContext(), android.R.layout.simple_list_item_1,
mOptionMenu));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mTitleSection = mOptionMenu[position];
getActionBar().setTitle(mTitleSection);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
});
mDrawerList.setItemChecked(0, true);
mTitleSection = getTitle();
mTitleApp = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
;
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
If any clarification is needed, let me know.
Thanks in advance.
Since you are importing import android.support.v7.app.ActionBarActivity , I guess you should use
getSupportActionBar()
instead of
getActionBar()
Instead of
getActionBar().getThemedContext()
use this

Categories