runtime error on emulator but not on phone nullpointer exception - java

Got my code in a try-catch loop. It runs fine on my phone (Samsung Galaxy S3, but give a runtime error in the Eclipse emulator.
The error appeared after I added a color setting to the method and used a GradientDrawable as the background for my button (even though this seems to work fine at other locations).
I'm totally lost here... Please have a look, THANKS!!
Code that generates the error
Note: I put a breakpoint on "return super.onContextItemSelected(item);", runtime error is generated on/after the return statement.
#SuppressLint("NewApi") #SuppressWarnings("deprecation")
#Override
public boolean onContextItemSelected(MenuItem item) {
int timerLocation = findTimer(item.getGroupId());
if (timerLocation > -1)
{
final MyCountDownTimer selectedFrag = this.myTimersList.get(timerLocation).fragmentRef;
switch (item.getItemId()) {
case R.id.timer_settings:
// Open timer specific options menu:
defaultSettingsMenu(selectedFrag);
return true;
default:
return super.onContextItemSelected(item);
}
}
else timerClickScreen.setText("ERROR: timer not found: " + String.valueOf(item.getGroupId()) + ", "+ String.valueOf(timerLocation));
return super.onContextItemSelected(item);
}
Main method:
private void defaultSettingsMenu(MyCountDownTimer selectedFragIN)
{
try
{
final MyCountDownTimer selectedFrag = selectedFragIN;
final Dialog dialog_settings = new Dialog(this);
dialog_settings.setContentView(R.layout.timer_set_options);
if (selectedFrag == null) dialog_settings.setTitle(R.string.default_settings_for_timer);
else dialog_settings.setTitle(R.string.timer_settings);
if (selectedFrag == null)
{
// Set title color:
dialog_settings.getWindow().setTitleColor(getDefaultColor());
// Set divider color:
int dividerTop = dialog_settings.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider1 = dialog_settings.findViewById(dividerTop);
divider1.setBackgroundColor(getDefaultColor());
}
else
{
// Set title color:
dialog_settings.getWindow().setTitleColor(selectedFrag.getTimerColor());
// Set divider color:
int dividerTop = dialog_settings.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider1 = dialog_settings.findViewById(dividerTop);
divider1.setBackgroundColor(selectedFrag.getTimerColor());
}
final TextView[] settingsItems = new TextView[8];
settingsItems[0]= (TextView) dialog_settings.findViewById(R.id.timerSettings_item1);
settingsItems[1]= (TextView) dialog_settings.findViewById(R.id.timerSettings_item2);
...
final Spinner[] settingsSetting = new Spinner[7];
settingsSetting[0]= (Spinner) dialog_settings.findViewById(R.id.timerSettings_setting1);
settingsSetting[1]= (Spinner) dialog_settings.findViewById(R.id.timerSettings_setting2);
...
settingsItems[0].setText(R.string.settings_title1);
settingsItems[1].setText(R.string.settings_title2);
// Give some padding on left side:
for (int i = 0; i<8; i++) settingsItems[i].setPadding(10, 0, 0, 0);
// Create menu items:
final String[] items1 = new String[]{getString(R.string.settings_menu1_item1), getString(R.string.settings_menu1_item2), getString(R.string.settings_menu1_item3), getString(R.string.settings_menu1_item4)};
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items1);
settingsSetting[0].setAdapter(adapter1);
if (selectedFrag == null) settingsSetting[0].setSelection(defaultTimerSettings.OnTapResponseValue.ordinal());
else settingsSetting[0].setSelection(selectedFrag.getTapBehavior().ordinal());
<... MORE SAME CODE HERE ...>
SpinnerColorSelector mySpinnerColorSelector = new SpinnerColorSelector(this);
settingsSetting[6].setAdapter(mySpinnerColorSelector);
if (selectedFrag == null) settingsSetting[6].setSelection(findIntArraylist(mySpinnerColorSelector.colors, defaultTimerSettings.colorTimer));
else settingsSetting[6].setSelection(findIntArraylist(mySpinnerColorSelector.colors,selectedFrag.getTimerColor()));
dialog_settings.show();
Button cancelButtonOptions = (Button) dialog_settings.findViewById(R.id.buttonTimerCancelOptions);
int[] gradientColors = new int[3];
if (selectedFrag == null) gradientColors = generateGradientColors(getDefaultColor());
else gradientColors = generateGradientColors(selectedFrag.getTimerColor());
if (android.os.Build.VERSION.SDK_INT >= 16) {
GradientDrawable gdDefault = new GradientDrawable();
gdDefault.setColors(gradientColors);
gdDefault.setCornerRadius(10);
gdDefault.setStroke(1, Color.GRAY);
cancelButtonOptions.setBackground(gdDefault);
} else {
// Fallback for APIs under 16.
GradientDrawable newGdDefault = new GradientDrawable(Orientation.BOTTOM_TOP, gradientColors);
newGdDefault.setCornerRadius(10);
newGdDefault.setStroke(1, Color.GRAY);
cancelButtonOptions.setBackgroundDrawable(newGdDefault);
}
// if decline button is clicked, close the custom dialog
cancelButtonOptions.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog_settings.dismiss();
}
});
<...REMOVED TESTED CODE...>
}
// Close dialog
dialog_settings.dismiss();
//selectedFrag.setTimerValue(hour*60*60*1000+minutes*60*1000+seconds*1000);
}
});
}
catch (Exception e)
{
Log.e("MainActivityError: defaultSettingsMenu function: Error in dialog function.",Log.getStackTraceString(e));
}
}
mySpinnerColorSelector CLASS:
public class SpinnerColorSelector extends BaseAdapter {
ArrayList<Integer> colors;
Context context;
public SpinnerColorSelector(Context context)
{
this.context=context;
colors = new ArrayList<Integer>();
colors.add(Color.parseColor("#57b947")); // Time Boss green
colors.add(Color.parseColor("#33B5E5")); // Android blue
colors.add(Color.parseColor("#0099CC")); // blue
colors.add(Color.parseColor("#AA66CC")); // purple light
colors.add(Color.parseColor("#9933CC")); // purple
colors.add(Color.parseColor("#FFBB33")); // orange light
colors.add(Color.parseColor("#FF8800")); // orange
colors.add(Color.parseColor("#FF4444")); // red light
colors.add(Color.parseColor("#CC0000")); // red
}
#Override
public int getCount()
{
return colors.size();
}
#Override
public Object getItem(int arg0)
{
return colors.get(arg0);
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
#SuppressLint({ "ViewHolder", "InflateParams" }) #Override
public View getView(int pos, View view, ViewGroup parent)
{
LayoutInflater inflater=LayoutInflater.from(context);
view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
TextView txv=(TextView)view.findViewById(android.R.id.text1);
txv.setBackgroundColor(colors.get(pos));
txv.setTextSize(20f);
txv.setTextColor(colors.get(pos));
txv.setText(colors.get(pos).toString());
return view;
}
}
LOGCAT OUTPUT:
09-24 15:14:24.631: E/AndroidRuntime(1698): FATAL EXCEPTION: main
09-24 15:14:24.631: E/AndroidRuntime(1698): Process: com.xpresspe.stopwatch, PID: 1698
09-24 15:14:24.631: E/AndroidRuntime(1698): java.lang.NullPointerException
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.TextView.makeNewLayout(TextView.java:6113)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.TextView.onMeasure(TextView.java:6408)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.Spinner.setUpChild(Spinner.java:632)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.Spinner.makeView(Spinner.java:585)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.Spinner.getBaseline(Spinner.java:431)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1089)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.forceUniformWidth(LinearLayout.java:940)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:920)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1226)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.ScrollView.onMeasure(ScrollView.java:326)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-24 15:14:24.631: E/AndroidRuntime(1698): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2321)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.View.measure(View.java:16648)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1959)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1145)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1340)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1032)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5657)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer.doFrame(Choreographer.java:544)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.os.Handler.handleCallback(Handler.java:733)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.os.Handler.dispatchMessage(Handler.java:95)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.os.Looper.loop(Looper.java:136)
09-24 15:14:24.631: E/AndroidRuntime(1698): at android.app.ActivityThread.main(ActivityThread.java:5026)
09-24 15:14:24.631: E/AndroidRuntime(1698): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 15:14:24.631: E/AndroidRuntime(1698): at java.lang.reflect.Method.invoke(Method.java:515)
09-24 15:14:24.631: E/AndroidRuntime(1698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
09-24 15:14:24.631: E/AndroidRuntime(1698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
09-24 15:14:24.631: E/AndroidRuntime(1698): at dalvik.system.NativeStart.main(Native Method)
Please help me...

In the SpinnerColorSelector class, I changed:
view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
To:
view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
And the runtime error is gone! It now runs on the emulator without problems... Still strange that try-catch didn't catch this one (maybe because the dialog is made at a later time under the hood). Anyway, back to being a happy puppy!!
This also got rid of the #SuppressLint({ "InflateParams" })

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

ClassCastException when using Fragment in Android

I've recently studyed android by myself.
and I tried Using Fragment by following my Textbook
but I met an error even though I typed codes exactly the same as my textbook.
Can you guys explain to me what is wrong?
This is MainActivity.java
package com.example.ex_1;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static class CounterFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.counterfragment, container, false);
Button btnIncrease = (Button)root.findViewById(R.id.btnincrease);
final TextView textCounter = (TextView)root.findViewById(R.id.txtcounter);
btnIncrease.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = Integer.parseInt(textCounter.getText().toString());
textCounter.setText(Integer.toString(count + 1));
}
});
return root;
}
}
}
This is activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="~~"/>
<fragment
android:name="com.example.ex_1.MainActivity$CounterFragment"
android:id="#+id/counterfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And the error is
09-24 07:40:08.329: E/AndroidRuntime(1794): FATAL EXCEPTION: main
09-24 07:40:08.329: E/AndroidRuntime(1794): Process: com.example.ex_1, PID: 1794
09-24 07:40:08.329: E/AndroidRuntime(1794): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ex_1/com.example.ex_1.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.access$800(ActivityThread.java:144)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.os.Handler.dispatchMessage(Handler.java:102)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.os.Looper.loop(Looper.java:135)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.main(ActivityThread.java:5221)
09-24 07:40:08.329: E/AndroidRuntime(1794): at java.lang.reflect.Method.invoke(Native Method)
09-24 07:40:08.329: E/AndroidRuntime(1794): at java.lang.reflect.Method.invoke(Method.java:372)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
09-24 07:40:08.329: E/AndroidRuntime(1794): Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Activity.setContentView(Activity.java:2144)
09-24 07:40:08.329: E/AndroidRuntime(1794): at com.example.ex_1.MainActivity.onCreate(MainActivity.java:19)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Activity.performCreate(Activity.java:5937)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
09-24 07:40:08.329: E/AndroidRuntime(1794): ... 10 more
09-24 07:40:08.329: E/AndroidRuntime(1794): Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.ex_1.MainActivity$CounterFragment that is not a Fragment
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Fragment.instantiate(Fragment.java:606)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Fragment.instantiate(Fragment.java:582)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2108)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.app.Activity.onCreateView(Activity.java:5286)
09-24 07:40:08.329: E/AndroidRuntime(1794): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
09-24 07:40:08.329: E/AndroidRuntime(1794): ... 20 more
09-24 07:40:08.329: E/AndroidRuntime(1794): Caused by: java.lang.ClassCastException
09-24 07:40:08.329: E/AndroidRuntime(1794): ... 25 more
problem is that you set your api level too low, so it use "support" version of fragment, instead of "base" fragment
put "min api level" at 11 in your androidmanifest, remove dependency to "support" library, remove "import android.support.v4.app.Fragment" and replace it with "import android.app.fragment" and it should work
change
public class MainActivity extends Activity {
to
public class MainActivity extends FragmentActivity {

Checkbox in the popupMenu

I have popupMenu and CheckBox. I need make write status CheckBox to boolean.
This code not working:
MenuItem fast_result;
boolean fast=false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.FastResult:
fast_result = item.getSubMenu().getItem(R.id.FastResult);//This is 182 line
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
}
}
It is errors:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.alexvsalex.HelpforMath.RootsActivity.onOptionsItemSelected(RootsActivity.java:182)
at android.app.Activity.onMenuItemSelected(Activity.java:2502)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
at android.widget.AbsListView$1.run(AbsListView.java:3168)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
What to do?
The problem is solved:
case R.id.FastResult:
fast_result = item; //There was an error
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;

httpDelete Async Task #4

Here is my doInBackground func:
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(type.equals("POST") || type.equals("PUT")){
params.add(new BasicNameValuePair("id", pid));
params.add(new BasicNameValuePair("name", name));
}else if(type.equals("DELETE")){
Log.d("DELETE:", pid);
params.add(new BasicNameValuePair("id", pid));
}
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
if(type.equals("GET")){
try {
jsonRows = json.getJSONArray("rows");
for(int i = 0; i<jsonRows.length();i++){
JSONObject p = (JSONObject)jsonRows.get(i);
aList.add(p.getString("ID") + " - " +p.getString("Name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
try{
String result = json.getString("results");
return result;
}catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
my httpDelete code :
else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
and node.js server :
app.delete('/api/db/:id', function(req, res){
var id = req.params.id;
res.setHeader('content-type', 'application/json');
dbPool.getConnection(function(objErr, objConn){
if(objErr){
sendError(res, 503, 'error', 'connection', objErr); //503 - Service Unavailable
}else{
objConn.query("DELETE FROM person WHERE ID = ? ",[id], function(Err, Rows, Fields){
if(Err){
sendError(res, 500, 'error', 'query', Err);
}else{
res.send({
results : 'success'
});
objConn.release();
gcmSend();
}//else
});
}//else
});
});
Errors:
09-24 06:35:12.386: E/AndroidRuntime(1908): FATAL EXCEPTION: AsyncTask #4
09-24 06:35:12.386: E/AndroidRuntime(1908): java.lang.RuntimeException: An error occured while executing doInBackground()
09-24 06:35:12.386: E/AndroidRuntime(1908): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-24 06:35:12.386: E/AndroidRuntime(1908): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.lang.Thread.run(Thread.java:841)
09-24 06:35:12.386: E/AndroidRuntime(1908): Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 36: -----192.168.1.11:3030/api/db/9
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.net.URI.create(URI.java:727)
09-24 06:35:12.386: E/AndroidRuntime(1908): at org.apache.http.client.methods.HttpDelete.<init>(HttpDelete.java:68)
09-24 06:35:12.386: E/AndroidRuntime(1908): at com.argenit.monitor.JSONParser.makeHttpRequest(JSONParser.java:86)
09-24 06:35:12.386: E/AndroidRuntime(1908): at com.argenit.monitor.MainPage$HttpAsyncTask.doInBackground(MainPage.java:137)
09-24 06:35:12.386: E/AndroidRuntime(1908): at com.argenit.monitor.MainPage$HttpAsyncTask.doInBackground(MainPage.java:1)
09-24 06:35:12.386: E/AndroidRuntime(1908): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-24 06:35:12.386: E/AndroidRuntime(1908): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-24 06:35:12.386: E/AndroidRuntime(1908): ... 4 more
Anyone help me?
Last logcat before error :
Log.d("url = ", url); -> 09-24 06:40:45.066: D/url =(1978):
----/192.168.1.11:3030/api/db/8

FATAL EXCEPTION: main on Android 4.x but not Android 2.X

I am getting some errors when trying to run my android app on an emulator that is running any version of Android 4.x but it works fine on any version of Android 2.X.
package com.EXCLUDED_FOR_PRIVACY.EXCLUDED_FOR_PRIVACY;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.ImageView;
import android.graphics.Color;
public class EXCLUDED_FOR_PRIVACY extends Activity {
public int WebView1Bool=0;
public int WebView2Bool=0;
public int WebView3Bool=0;
public int WebView4Bool=0;
private TabHost tabs;
private void setupTabHost() {
tabs = (TabHost) findViewById(R.id.my_tabhost);
tabs.setup();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupTabHost();
tabs.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
setupTab(new ImageView(this), 1);
setupTab(new ImageView(this), 2);
setupTab(new ImageView(this), 3);
setupTab(new ImageView(this), 4);
WebView mWebView1;
mWebView1 = (WebView) findViewById(R.id.webview1);
mWebView1.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView1.setBackgroundColor(0);
mWebView1.getSettings().setJavaScriptEnabled(true);
mWebView1.setWebViewClient(new MobileClient());
mWebView1.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView1Bool=1;
tabs.getTabWidget().getChildAt(0).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(0);
if(WebView1Bool==0){
WebView mWebView1;
mWebView1 = (WebView) findViewById(R.id.webview1);
mWebView1.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView1.setBackgroundColor(0);
mWebView1.getSettings().setJavaScriptEnabled(true);
mWebView1.setWebViewClient(new MobileClient());
mWebView1.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView1Bool=1;
}
}
});
tabs.getTabWidget().getChildAt(2).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(1);
if(WebView2Bool==0){
WebView mWebView2;
mWebView2 = (WebView) findViewById(R.id.webview2);
mWebView2.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView2.setBackgroundColor(0);
mWebView2.getSettings().setJavaScriptEnabled(true);
mWebView2.setWebViewClient(new MobileClient());
mWebView2.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView2Bool=1;
}
}
});
tabs.getTabWidget().getChildAt(4).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(2);
if(WebView3Bool==0){
WebView mWebView3 = (WebView) findViewById(R.id.webview3);
mWebView3.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView3.setBackgroundColor(0);
mWebView3.getSettings().setJavaScriptEnabled(true);
mWebView3.setWebViewClient(new MobileClient());
mWebView3.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView3Bool=1;
}
}
});
tabs.getTabWidget().getChildAt(6).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(3);
if(WebView4Bool==0){
WebView mWebView4;
mWebView4 = (WebView) findViewById(R.id.webview4);
mWebView4.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView4.setBackgroundColor(0);
mWebView4.getSettings().setJavaScriptEnabled(true);
mWebView4.setWebViewClient(new MobileClient());
mWebView4.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView4Bool=1;
}
}
});
}
private class MobileClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private void setupTab(final View view, final int i) {
View createTabView_view = LayoutInflater.from(tabs.getContext()).inflate(R.layout.tabs_bg, null);
ImageView createTabView_tv = (ImageView) createTabView_view.findViewById(R.id.tabsImage);
if(i==1){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_discounts);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview1);
tabs.addTab(tabSpec);
} else if(i==2){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_specials);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview2);
tabs.addTab(tabSpec);
} else if(i==3){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_directory);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview3);
tabs.addTab(tabSpec);
} else if(i==4){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_membership);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview4);
tabs.addTab(tabSpec);
}
}
}
Here are the errors I am seeing
09-24 13:11:25.329: E/Trace(1151): error opening trace file: No such file or directory (2)
09-24 13:11:25.539: D/dalvikvm(1151): GC_FOR_ALLOC freed 43K, 4% free 8316K/8583K, paused 42ms, total 45ms
09-24 13:11:25.549: I/dalvikvm-heap(1151): Grow heap (frag case) to 8.829MB for 691216-byte allocation
09-24 13:11:25.669: D/dalvikvm(1151): GC_CONCURRENT freed <1K, 4% free 8990K/9287K, paused 75ms+6ms, total 124ms
09-24 13:11:25.829: D/gralloc_goldfish(1151): Emulator without GPU emulation detected.
09-24 13:11:26.209: I/Choreographer(1151): Skipped 42 frames! The application may be doing too much work on its main thread.
09-24 13:11:26.379: I/Choreographer(1151): Skipped 44 frames! The application may be doing too much work on its main thread.
09-24 13:11:27.509: I/Choreographer(1151): Skipped 54 frames! The application may be doing too much work on its main thread.
09-24 13:11:28.319: D/AndroidRuntime(1151): Shutting down VM
09-24 13:11:28.319: W/dalvikvm(1151): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-24 13:11:28.379: E/AndroidRuntime(1151): FATAL EXCEPTION: main
09-24 13:11:28.379: E/AndroidRuntime(1151): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.EXCLUDED.EXCLUDED/com.EXCLUDED.EXCLUDED.EXCLUDED}: java.lang.NullPointerException
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.os.Looper.loop(Looper.java:137)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.main(ActivityThread.java:4745)
09-24 13:11:28.379: E/AndroidRuntime(1151): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 13:11:28.379: E/AndroidRuntime(1151): at java.lang.reflect.Method.invoke(Method.java:511)
09-24 13:11:28.379: E/AndroidRuntime(1151): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-24 13:11:28.379: E/AndroidRuntime(1151): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-24 13:11:28.379: E/AndroidRuntime(1151): at dalvik.system.NativeStart.main(Native Method)
09-24 13:11:28.379: E/AndroidRuntime(1151): Caused by: java.lang.NullPointerException
09-24 13:11:28.379: E/AndroidRuntime(1151): at com.EXCLUDED.EXCLUDED.EXCLUDED.onCreate(EXCLUDED.java:85)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.Activity.performCreate(Activity.java:5008)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
09-24 13:11:28.379: E/AndroidRuntime(1151): ... 11 more
09-24 13:11:30.289: I/Process(1151): Sending signal. PID: 1151 SIG: 9
I apologize if this is something really simple that any java developer would know, I have to admit I barely know what I am doing in Java but am under the gun to get this built. Thank you very much for any help.
Get rid of all the tabs.getTabWidget().getChildAt(...).setOnClickListener() crap, replacing it with a single TabHost.OnTabChangeListener that you register with your TabHost, to find out when the user changes tabs. Your existing code assumes a particular internal structure of a TabWidget, and that assumption is unreliable, as you are discovering.

Categories