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