java.lang.NullPointerException - error when logout Android - java

I followed this tutorial (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/) for creating member system with login and logout feature. The problem is when logout it doesn't work. I'm creating logout in Fragment Navigation Drawer Menu.
This My Activity.
public class HomeActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = HomeActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private SQLiteHandler db;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
captureImage();
break;
case 2:
fragment = new ReportsFragment();
title = getString(R.string.title_reports);
break;
case 3:
title = getString(R.string.title_settings);
break;
case 4:
logoutUser();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
And this is error log.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.company.report.activity.HomeActivity.logoutUser(HomeActivity.java:251)
at com.company.report.activity.HomeActivity.displayView(HomeActivity.java:124)
at com.company.report.activity.HomeActivity.onDrawerItemSelected(HomeActivity.java:99)
at com.company.report.activity.FragmentDrawer$1.onClick(FragmentDrawer.java:79)
at com.company.report.activity.FragmentDrawer$RecyclerTouchListener.onInterceptTouchEvent(FragmentDrawer.java:160)
at android.support.v7.widget.RecyclerView.dispatchOnItemTouchIntercept(RecyclerView.java:1986)
at android.support.v7.widget.RecyclerView.onInterceptTouchEvent(RecyclerView.java:2027)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1629)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1726)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1912)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1371)
at android.app.Activity.dispatchTouchEvent(Activity.java:2364)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1860)
at android.view.View.dispatchPointerEvent(View.java:5721)
at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:2890)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2466)
at android.view.ViewRootImpl.processInputEvents(ViewRootImpl.java:845)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2475)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)

Looks like sessionand db are never initialized. Initialize it and the error will be gone.

Related

Showing error while adding 4 menu (items) in BottomNavigationView

I am new to android .. trying to build application that is having webview inside fragment and in the bottom it is having BottomNavigationView on click of particular item fragment change according to click .
every thing is working fine when having 3 items in BottomNavigationView when i add 4 app start crashing .
error is as fallows -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.xparticle.digitalkabadi, PID: 23369
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.xparticle.digitalkabadi/in.xparticle.digitalkabadi.MainActivity}: android.view.InflateException: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:940)
Caused by: android.view.InflateException: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
Caused by: android.view.InflateException: Binary XML file line #19 in in.xparticle.digitalkabadi:layout/activity_main: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:854)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1006)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
at in.xparticle.digitalkabadi.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:7824)
at android.app.Activity.performCreate(Activity.java:7813)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:940)
E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setImportantForAccessibility(int)' on a null object reference
at androidx.core.view.ViewCompat.setImportantForAccessibility(ViewCompat.java:1119)
at com.google.android.material.bottomnavigation.BottomNavigationItemView.<init>(BottomNavigationItemView.java:104)
at com.google.android.material.bottomnavigation.BottomNavigationItemView.<init>(BottomNavigationItemView.java:87)
at com.google.android.material.bottomnavigation.BottomNavigationItemView.<init>(BottomNavigationItemView.java:83)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView.getNewItem(BottomNavigationMenuView.java:606)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView.buildMenuView(BottomNavigationMenuView.java:538)
at com.google.android.material.bottomnavigation.BottomNavigationPresenter.updateMenuView(BottomNavigationPresenter.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView.inflateMenu(BottomNavigationView.java:344)
at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:226)
at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:133)
... 28 more
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_scrape_price:
selectedFragment = new ScrapePriceFragment();
break;
case R.id.nav_aboutUs:
selectedFragment = new AboutUsFragment();
break;
case R.id.nav_scrape_Process:
selectedFragment = new AboutUsFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
try this -->
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//loading the default fragment
loadFragment(new FirstFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.id1:
fragment = new FirstFragment();
break;
case R.id.id2:
fragment = new SecondFragment();
break;
case R.id.id3:
fragment = new thirsFragment();
break;
case R.id.id4:
fragment = new fourthFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}

Error when inflating class Fragment

I have bug I don't know how to fix.
I need to add a Fragment, but it won't work.
Everything happens in void firstTime() and the error shows that it's on line setContentView(R.layout.activity_main);.
I really don't know how to fix this.
I tried a lot of things, but it just does not work.
Please, help me.
MainActivity class:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private MapFragment mapsFragment;
static MainActivity can;
static FloatingActionButton fab;
static FloatingActionButton show;
private String encoded_string;
private Bitmap bitmap;
private String picturePath;
View rootView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private void initializeMapsFragment() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mapsFragment = new MapFragment();
SupportMapFragment supportMapFragment = mapsFragment;
mTransaction.add(R.id.map, supportMapFragment);
mTransaction.commitNow();
}
#RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
can = this;
Log.d("--***** MAP ", "::Loading Map");
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
can, 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(can);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(can).addApi(AppIndex.API).build();
}
public void start(){
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
can, 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(can);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(can).addApi(AppIndex.API).build();
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
#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);
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!mapsFragment.isAdded())
sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
else
sFm.beginTransaction().show(mapsFragment).commit();
} else if (id == R.id.nav_share) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Check this app out --> link.kys";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void firstTime() {
setContentView(R.layout.firsttime);
(findViewById(R.id.cancelBut))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//View view = can.findViewById(android.R.id.content);
//Log.d("a", "" + ((ViewGroup)view).getChildCount() );
//((ViewGroup) view).removeView(view);
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
sFm.beginTransaction().remove(mapsFragment).commitNow();
if(mapsFragment.isAdded()){
Log.d("--***** FRAGMENT ", "::Still On");
}
start();
}
});
}
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime();
//SharedPreferences.Editor editor = prefs.edit();
//editor.putBoolean("firstTime", true);
//editor.commit();
}
}
private void stats() {
setContentView(R.layout.stats);
RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
ratingbar.setRating((float) 2.0);
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
ratingBar.setRating((float) 2.0);
}
});
((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.content_main);
}
});
}
}
Xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.robertas.parking.bestfreeparking.MainActivity"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.robertas.parking.test.MapsActivity"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="0.68" />
<EditText
android:id="#+id/searchView1"
android:inputType="textPersonName"
android:layout_width="250dp"
android:layout_height="34dp"
android:layout_marginTop="14dp"
android:hint="Search Location"
android:ems="10"
android:textColor="#android:color/black"
android:background="#android:color/white"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:background="#drawable/places_ic_search"
android:layout_alignBottom="#+id/searchView1"
android:layout_alignRight="#+id/searchView1"
android:layout_alignEnd="#+id/searchView1"
android:layout_alignTop="#+id/searchView1"
android:layout_marginLeft="216dp"
android:layout_marginStart="216dp"
android:layout_alignLeft="#+id/searchView1"
android:layout_alignStart="#+id/searchView1" />
</RelativeLayout>
Error:
android.view.InflateException: Binary XML file line #12: Error inflating class fragment
Log:
03-10 20:21:45.036 31937-31937/com.robertas.parking.bestfreeparking D/AndroidRuntime: Shutting down VM
03-10 20:21:45.036 31937-31937/com.robertas.parking.bestfreeparking E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robertas.parking.bestfreeparking, PID: 31937
android.view.InflateException: Binary XML file line #12: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #12: Duplicate id 0x7f0f00e8, tag null, or parent id 0x7f0f00e7 with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2427)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:77)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802) 
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143) 
at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161) 
at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356) 
at android.view.View.performClick(View.java:4780) 
at android.view.View$PerformClick.run(View.java:19866) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
03-10 20:21:45.039 1499-1878/system_process W/ActivityManager: Force finishing activity 1 com.robertas.parking.bestfreeparking/.MainActivity
[ 03-10 20:21:45.046 1499: 1878 D/ ]
HostConnection::get() New Host Connection established 0x7ffc98084ec0, tid 1878
03-10 20:21:45.051 1123-1123/? E/EGL_emulation: tid 1123: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
03-10 20:21:45.152 1499-1558/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
03-10 20:21:45.194 1499-1558/system_process W/EGL_emulation: eglSurfaceAttrib not implemented
03-10 20:21:45.194 1499-1558/system_process W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7ffca953fb40, error=EGL_SUCCESS
03-10 20:21:45.612 1499-1518/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{38e88b4d u0 com.robertas.parking.bestfreeparking/.MainActivity t155 f}
03-10 20:21:45.645 1756-2040/com.google.android.googlequicksearchbox W/EGL_emulation: eglSurfaceAttrib not implemented
03-10 20:21:45.645 1756-2040/com.google.android.googlequicksearchbox W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe1c93620, error=EGL_SUCCESS
03-10 20:21:46.616 1622-1622/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000
03-10 20:21:46.616 1622-1622/com.android.systemui W/PackageManager: Failure retrieving resources for com.robertas.parking.bestfreeparking: Resource ID #0x0
03-10 20:21:46.832 1756-1756/com.google.android.googlequicksearchbox I/Choreographer: Skipped 69 frames! The application may be doing too much work on its main thread.
03-10 20:21:47.332 1756-2040/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer...
03-10 20:21:47.448 1499-1577/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
03-10 20:21:47.465 31937-31937/? I/Process: Sending signal. PID: 31937 SIG: 9
03-10 20:21:47.474 1499-14634/system_process I/WindowState: WIN DEATH: Window{394fad98 u0 com.robertas.parking.bestfreeparking/com.robertas.parking.bestfreeparking.MainActivity}
03-10 20:21:47.474 1499-1874/system_process I/ActivityManager: Process com.robertas.parking.bestfreeparking (pid 31937) has died
03-10 20:21:47.475 1499-1874/system_process W/ActivityManager: Scheduling restart of crashed service com.robertas.parking.bestfreeparking/com.android.tools.fd.runtime.InstantRunService in 1000ms
03-10 20:21:47.480 1123-1123/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
03-10 20:21:47.521 1499-1558/system_process D/OpenGLRenderer: endAllStagingAnimators on 0x7ffc9dfec000 (RippleDrawable) with handle 0x7ffca9734500
03-10 20:21:47.525 1499-1753/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 31937 uid 10058
03-10 20:21:47.537 1956-32415/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
03-10 20:21:47.537 1956-32414/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi#c6aa4d0
03-10 20:21:47.568 1135-1912/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
03-10 20:21:47.569 1135-32418/? I/AudioFlinger: AudioFlinger's thread 0xf59c4000 ready to run
03-10 20:21:47.581 2146-32417/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated.
03-10 20:21:47.584 1956-32414/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi#c6aa4d0
03-10 20:21:47.602 1956-1956/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady
03-10 20:21:47.629 2146-2248/com.google.android.gms W/Settings: Setting adb_enabled has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
03-10 20:21:47.629 2146-2248/com.google.android.gms I/Icing: Usage reports 1 indexed 1 rejected 0 imm upload true
03-10 20:21:47.634 2146-2248/com.google.android.gms W/Icing: App history upload skipped 1 0 0
03-10 20:21:48.101 1135-1535/? W/AudioFlinger: write blocked for 469 msecs, 16 delayed writes, thread 0xf58ac000
03-10 20:21:48.503 32429-32429/? I/art: Not late-enabling -Xcheck:jni (already on)
03-10 20:21:48.507 1499-1518/system_process I/ActivityManager: Start proc 32429:com.robertas.parking.bestfreeparking/u0a58 for service com.robertas.parking.bestfreeparking/com.android.tools.fd.runtime.InstantRunService
03-10 20:21:48.775 32429-32429/com.robertas.parking.bestfreeparking I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
03-10 20:21:48.777 32429-32429/com.robertas.parking.bestfreeparking I/InstantRun: Starting Instant Run Server for com.robertas.parking.bestfreeparking
03-10 20:21:48.777 1499-14635/system_process W/ActivityManager: getRunningAppProcesses: caller 10058 does not hold REAL_GET_TASKS; limiting output
Everything happens in firstTime() void and error shows that it's on line setContentView(R.layout.activity_main);.
You can't do this.
start() and firstTime() are not the entrypoints to your activity/application.
onCreate() is and that is where you can only call setContentView(R.layout.activity_main).
Even so, static methods that "load" any Activity aren't going to work.
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime(); // This doesn't work like this
}
}
Especially if you did MainActivity.load() somewhere else in your other classes.
Reading your error, see that start() -> setContentView() is causing the problem...
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
at android.view.View.performClick(View.java:4780)
And the real error message
Duplicate id 0x7f0f00e8, tag null, or parent id 0x7f0f00e7 with another fragment for com.google.android.gms.maps.SupportMapFragment
Meaning that the Fragment "#+id/maps" has already been added into the FragmentManger of the Activity class, so it has been duplicated.
Activities should ideally not call setContentView outside of onCreate.
Reason being = You call setContentView, therefore removing the MapFragment (and other Views) entirely from the root view, so 1) the FragmentManger cannot find anything previously added, 2) Any view you had used findViewById before (probably) no longer exists.
If you are wanting to "replace" the content of some Activity, then you should use Fragments + a FrameLayout + a FragmentTransaction.replace() method call.
Make sure you compile com.google.android.gms.maps in your build.gradle file. Add this to your dependencies if it's not there:
dependencies {
<other dependencies>
compile 'com.google.android.gms:play-services-maps:10.2.0'
}
And remember to import it in your java file:
import com.google.android.gms.maps.SupportMapFragment;
And on the tools:context, it should be .MainActivity

Preference fragment returns null on transaction

I'm trying to implement a preference fragment in my app, so I set preferences.xml file, fragment that is supposed to show preferences, and fragment transaction. When I try to show SettingsFragment, the app crashes with this error log:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:431)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:481)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:472)
at com.ikurek.pwr.MainActivity.onNavigationItemSelected(MainActivity.java:145)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:153)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:328)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Why is this object null? How else am I supposed to set up a setting fragment? I know that solution for this is proably very simple, but somehow I cannot figure this out by myself. Here's my code:
Part that calls fragment transaction from MainActivity:
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
Class fragmentClass = null;
int id = item.getItemId();
if (id == R.id.nav_news) {
fragmentClass = NewsFragment.class;
} else if (id == R.id.nav_map) {
fragmentClass = CatFragment.class;
} else if (id == R.id.nav_buildings) {
fragmentClass = BuildingsFragment.class;
} else if (id == R.id.nav_settings) {
fragmentClass = SettingsFragment.class;
} else if (id == R.id.nav_info) {
fragmentClass = AppInfoFragment.class;
} else if (id == R.id.nav_bugreport) {
fragmentClass = ContactFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frameLayoutForFragments, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
My preferences.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:defaultValue="false"
android:key="saveLastPosition"
android:summary="1st check box"
android:title="Check"/>
<CheckBoxPreference
android:defaultValue="true"
android:key="keepScreenOn"
android:summary="2nd check box"
android:title="Box"/>
</PreferenceScreen>
And my SettingsFragment:
public class SettingsFragment extends PreferenceFragment {
public SettingsFragment() {
// Required empty public constructor
}
public static SettingsFragment newInstance() {
SettingsFragment fragment = new SettingsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Well from what I can tell you are passing a null fragment to your fragment manager. As you will notice:
Fragment fragment = null;
Class fragmentClass = SettingsFragment.class;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frameLayoutForFragments, fragment).commit();
You have:
Fragment fragment = null;
You never actually declare this as a SettingsFragment. You should either have:
Fragment fragment = new SettingsFragment();
Or declare it in your replace statement.
Class fragmentClass = SettingsFragment.class;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frameLayoutForFragments, new SettingsFragment()).commit();

How to get ListView data from one activity to another using setOnClickListener

In my listview there are to feilds,ward number and the date.i want to get these data to new activity when i'am clicking a listview.but in this there is a runtime error and i have no idea to how to fix it.
this is my dashboardActivity.java file,
public class DashboardActivity extends ListActivity implements FetchDataListener{
UserFunctions userFunctions;
Button btnLogout;
TextView resultView;
private ProgressDialog dialog;
//private String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
initView();
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
TextView txtviewWard= (TextView) view.findViewById(R.id.ward_number);
String ward = txtviewWard.getText().toString();
TextView txtviewDate= (TextView) view.findViewById(R.id.date_time);
String dateTime = txtviewDate.getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("ward", ward);
i.putExtra("dateTime", dateTime);
startActivity(i);
}
});
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
Intent intent = getIntent();
String email = intent.getStringExtra(LoginActivity.EMAIL);
String url = "http://pubbapp.comze.com/pubapp1.php?email=" + email;
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
this is my SingleListItem.java file,
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtWard = (TextView) findViewById(R.id.ward_number);
TextView txtDate = (TextView) findViewById(R.id.date_time);
Intent i = getIntent();
// getting attached intent data
String wardNumber = i.getStringExtra("ward");
String dateTime = i.getStringExtra("dateTime");
// displaying selected product name
txtWard.setText(wardNumber);
txtDate.setText(dateTime);
}
this is my xml file,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ward_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="wardNumber"
android:textColor="#ffffff"
android:textSize="25dip"
android:textStyle="bold" />
<TextView
android:id="#+id/date_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Date"
android:padding="10dip"
android:textColor="#ffffff"
android:textSize="20dip"
android:textStyle="bold" />
</LinearLayout>
and this is the error in the LogCat,
12-02 19:10:01.100: E/AndroidRuntime(22705): FATAL EXCEPTION: main
12-02 19:10:01.100: E/AndroidRuntime(22705): java.lang.NullPointerException
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.example.androidhive.DashboardActivity$1.onItemClick(DashboardActivity.java:59)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.ListView.performItemClick(ListView.java:3745)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1980)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Handler.handleCallback(Handler.java:587)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Handler.dispatchMessage(Handler.java:92)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Looper.loop(Looper.java:130)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.app.ActivityThread.main(ActivityThread.java:3691)
12-02 19:10:01.100: E/AndroidRuntime(22705): at java.lang.reflect.Method.invokeNative(Native Method)
12-02 19:10:01.100: E/AndroidRuntime(22705): at java.lang.reflect.Method.invoke(Method.java:507)
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
12-02 19:10:01.100: E/AndroidRuntime(22705): at dalvik.system.NativeStart.main(Native Method)
please help me to fix this error.
thank you.
In first activity, pass the data as a bundle using putExtras:
// sending data to new activity
Bundle b = new Bundle();
b.putString("ward", ward);
b.putString("dateTime", dateTime);
i.putExtras(b);
In second activity, retrieve the bundle and parse the data as follows:
Bundle b = getIntent().getExtras();
if (b != null)
{
String wardNumber = b.getString("ward");
String dateTime = b.getString("dateTime");
}
try this....
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//your code
}
});
get data like this in ur second activity:
Bundle b = savedInstanceState.getExtras();
if(b!=null)
{
String ward =b.getString("ward");
String dateTime =b.getString("datetime");
}
bundle is responsible to getexras(),so use this.it worked for me and my other friends.

How to use Bottom tabActivity in my Activity itself

I want to use bottom tab in my activity,in my old activity itself having some function,without using seperate activity for tab,can i use tab functions in my activity itself,I tried like this.
public class GinfyActivity extends Activity {
/** Called when the activity is first created. */
public GridviewAdapter mAdapter;
private Spinner spinner1;
public String selectprayer;
ArrayList<GridviewAdapter> results = new ArrayList<GridviewAdapter>();
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_ginfy);
TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(GinfyActivity.this,Audioprayer.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(GinfyActivity.this,TTSMeditation.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(GinfyActivity.this,TTSList.class)));
mTabHost.setCurrentTab(0);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listginfy, listimage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (selectprayer.equals("www.ginfy.com"))
{
switch(position)
{
case 0:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Coming Soon", Toast.LENGTH_LONG).show();
}
}
else
{
switch(position)
{
case 0:
Intent new2Activity = new Intent(GinfyActivity.this,YourPrayerActivity.class);
startActivity(new2Activity);
break;
case 1:
Intent new3Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity1.class);
startActivity(new3Activity);
break;
case 3:
Intent new4Activity = new Intent(GinfyActivity.this,ExperiencesActivity.class);
startActivity(new4Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Coming Soon", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void addListenerOnSpinnerItemSelection() {
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinner1.setSelection(position);
//spinnerCapital.setSelection(position);
selectprayer = (String) spinner1.getSelectedItem();
//Toast.makeText(getBaseContext(), selectprayer, Toast.LENGTH_SHORT).show();
//String myStatesCapital = (String) spinnerCapital.getSelectedItem();
//tvCapital.setText("My State is " + myState + ".And its Capital is "
//+ myStatesCapital);
}
public void onNothingSelected(AdapterView<?> parent) {
}});
}
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
}
public void prepareList()
{
listginfy = new ArrayList<String>();
listginfy.add("Prayers");
listginfy.add("Prayer room");
listginfy.add("God gallery");
listginfy.add("Experiences");
listimage = new ArrayList<Integer>();
listimage.add(R.drawable.ginfyprayer);
listimage.add(R.drawable.poojaroom1);
listimage.add(R.drawable.godsgallery);
listimage.add(R.drawable.temp1);
}
}
I declared that tab functions in mylayout also but my activity is not opening,it display my activity has stopped
is showing somelogcat error.
09-12 08:43:45.615: E/AndroidRuntime(2630): FATAL EXCEPTION: main
09-12 08:43:45.615: E/AndroidRuntime(2630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonandroid/com.example.jsonandroid.GinfyActivity}: java.lang.NullPointerException
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.os.Handler.dispatchMessage(Handler.java:99)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.os.Looper.loop(Looper.java:137)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.main(ActivityThread.java:5039)
09-12 08:43:45.615: E/AndroidRuntime(2630): at java.lang.reflect.Method.invokeNative(Native Method)
09-12 08:43:45.615: E/AndroidRuntime(2630): at java.lang.reflect.Method.invoke(Method.java:511)
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-12 08:43:45.615: E/AndroidRuntime(2630): at dalvik.system.NativeStart.main(Native Method)
09-12 08:43:45.615: E/AndroidRuntime(2630): Caused by: java.lang.NullPointerException
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.example.jsonandroid.GinfyActivity.onCreate(GinfyActivity.java:44)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.Activity.performCreate(Activity.java:5104)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-12 08:43:45.615: E/AndroidRuntime(2630): ... 11 more
replace these two lines
public class GinfyActivity extends Activity
TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
with following
public class GinfyActivity extends TabActivity
TabHost mTabHost = getTabHost();
EDIT
change activity which you want to display in following line.
Intent intentAndroid = new Intent().setClass(this, Your_Activity.class);
And if you want only Tab then it's better to use ActionBar as TabHost is deprecated.
Full Example of TabHost
To use ActionBar here is sample code (use Sherlock or appcompat Library for < API 11)
public class MainActivity extends Activity implements TabListener {
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("TAB 1").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 2").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 3").setTabListener(this));
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start First Activity", Toast.LENGTH_SHORT).show();
break;
case 1:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start Second Activity", Toast.LENGTH_SHORT).show();
break;
case 2:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start Third Activity", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
For your your complete requirement https://github.com/AdilSoomro/Iphone-Tab-in-Android

Categories