Null pointer exception when onOptionsItemSelected is called - java

The java code is as follows: The layout seems fine. The only problem seems to occur when i click the navigation bar icon on the top left corner.
package com.example.chirag.carparlour;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button book = (Button)findViewById(R.id.book);
Button sub = (Button)findViewById(R.id.sub);
Button offers = (Button)findViewById(R.id.offers);
Button support = (Button)findViewById(R.id.support);
Button comp = (Button)findViewById(R.id.comp);
DrawerLayout dl = (DrawerLayout)findViewById(R.id.drawerlayout);
ActionBarDrawerToggle abdt = new ActionBarDrawerToggle(this, dl , R.string.Open, R.string.Close);
dl.addDrawerListener(abdt);
abdt.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, bookawash.class);
startActivity(intent);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, subscriptions.class);
startActivity(intent);
}
});
offers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
support.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
comp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(abdt.onOptionsItemSelected(item))
{return true;}
return super.onOptionsItemSelected(item);
}}
and the error in the log is as follows:
FATAL EXCEPTION: main
Process: com.example.chirag.carparlour, PID: 4879
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.app.ActionBarDrawerToggle.onOptionsItemSelected(android.view.MenuItem)' on a null object reference
at com.example.chirag.carparlour.MainActivity.onOptionsItemSelected(MainActivity.java:86)
at android.app.Activity.onMenuItemSelected(Activity.java:2914)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:408)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:198)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:113)
at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:187)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21166)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Whenever I click the navigation icon on the top left corner, the app crashes and it shows this error. It works fine if you just slide the screen. And when I do not have this method, the app doesn't crash but the navigation bar doesn't show either. This hasn't happened before.
Please help!

I think the problem is this: (in the onCreate):
ActionBarDrawerToggle abdt = new ActionBarDrawerToggle(this, dl , R.string.Open, R.string.Close);
Switch to:
abdt = new ActionBarDrawerToggle(this, dl , R.string.Open, R.string.Close);

Related

Android app crashes after RatingBar DialogFragment closes

The purpose of my app is to retrieve a value out of 5 from a rating bar through a custom dialog and display it in a TextView in the main activity. When I tap the button I've outlined in red in the image below, the app crashes and shuts down.
The app consists of 2 classes/activities. The main activity and the custom dialog activity.
The code for both files can be found below:
MainActivity.java:
package com.example.mealrater;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements MealRaterDialog.SaveRating {
public EditText restaurant, dish;
public TextView ratingDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
restaurant = findViewById(R.id.etRestaurant);
dish = findViewById(R.id.etDish);
RateMealButton();
}
#Override
public void finishMealRaterDialog(String rating) {
ratingDisplay = findViewById(R.id.tvRatingDisplay);
ratingDisplay.setText(rating);
}
private void RateMealButton() {
Button rate = findViewById(R.id.btnRate);
rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
MealRaterDialog mealRaterDialog = new MealRaterDialog();
mealRaterDialog.show(fm, "RateMeal");
}
});
}
}
MealRaterDialog.java:
package com.example.mealrater;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import androidx.fragment.app.DialogFragment;
public class MealRaterDialog extends DialogFragment {
String rating;
public interface SaveRating {
void finishMealRaterDialog(String rating);
}
public MealRaterDialog() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.meal_rater, container);
getDialog().setTitle("Rate your meal");
Button save = view.findViewById(R.id.btnSaveRating);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RatingBar ratingBar = view.findViewById(R.id.rbMeal);
rating = String.valueOf(ratingBar.getRating());
SaveItem(String.valueOf(rating));
}
});
return view;
}
private void SaveItem(String rating) {
MealRaterDialog.SaveRating activity = (MealRaterDialog.SaveRating) getActivity();
activity.finishMealRaterDialog(rating);
getDialog().dismiss();
}
}
I'm new to Android Studio and would also like to receive tips on how to improve this question. Thank you.
Logcat error:
2021-04-28 16:04:35.240 18144-18144/com.example.mealrater E/libc: Access denied finding property "ro.serialno"
2021-04-28 16:04:42.709 18144-18144/com.example.mealrater E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mealrater, PID: 18144
java.lang.NullPointerException: Attempt to invoke virtual method 'float android.widget.RatingBar.getRating()' on a null object reference
at com.example.mealrater.MealRaterDialog$1.onClick(MealRaterDialog.java:35)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
There are severall fixes for this.
First of all, You should define the ratingBar widget before the onClick. Right now it is creating the variable each time you click on the button. Define it after Button save = view.findViewById(R.id.btnSaveRating); line.
Second of all, As you are using a Dialog fragment, all the logic of the click should be called on the override funtion called onViewCreated(). Not in the OnCreateView() as you are doing right now. Let me know if it works for you.
I've tried to reproduce this error and I find a solution that works for me.
You have to create the rating bar with the view (outside of the listener).
This should be your onCreateView in your MealRaterDialog.java class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.meal_rater, container);
getDialog().setTitle("Rate your meal");
Button save = view.findViewById(R.id.btnSaveRating);
RatingBar ratingBar = view.findViewById(R.id.rbMeal);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rating = String.valueOf(ratingBar.getRating());
SaveItem(String.valueOf(rating));
}
});
return view;
}
Hope it works!

the Android Studio OnClickListener doesn't work

Nothing happens when I click the "start" button, the app suddenly closes. I think the View.OnClickListener doesn't work, but I can't find how to fix it.
package com.example.myquiz;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView title;
private Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.main_title);
start = findViewById(R.id.ma_startB);
Typeface typeface = ResourcesCompat.getFont(this,R.font.blacklist);
title.setTypeface(typeface);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,CategoryActivity.class);
startActivity(intent);
}
});
}
}
I got this error in Logcat:
error screenshot
This is the code for the CategoryActivity class, this is where I get the error from, but I really don't see where the problem is.
package com.example.myquiz;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class CategoryActivity extends AppCompatActivity {
private GridView catGrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Categories");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
catGrid = findViewById(R.id.catGridView);
List<String> catList = new ArrayList<>();
catList.add("Cat 1");
catList.add("Cat 2");
catList.add("Cat 3");
catList.add("Cat 4");
catList.add("Cat 5");
catList.add("Cat 6");
CatGridAdapter adapter = new CatGridAdapter(catList);
catGrid.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
{ CategoryActivity.this.finish();}
return super.onOptionsItemSelected(item);
}
}
The click listener is working correct, looking at the error log the launching of the CategoryActivity class is causing the app crash:
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor...
This tells the ActionBar / ToolBar inside the CategoryActivity is setup twice. Probably (if not, please share the class code) you can either remove setSupportActionBar() or change the theme of the CategoryActivity to something like: Theme.MaterialComponents.Light.NoActionBar to see if you get the Activity running after the button click.

Crashing app while using search bar in action bar in android. MainActivity is not able decide which one has to be executed first?

`Error in text
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.flavourbasket.flavourbasket/com.flavourbasket.flavourbasket.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at com.flavourbasket.flavourbasket.MainActivity.navigationDrawer(MainActivity.java:50)
at com.flavourbasket.flavourbasket.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
`https://github.com/nippynic93/FlavourBaske
This link refers to my project which has the issue.
This is the Code Which has the error at 50th line. I am unable to find it please help me.
It contains Search Bar at the mainActivity. If I am going to comment the 50th line so my action bar got to disappear. And project runs fine.
package com.flavourbasket.flavourbasket;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mdrawerlayout;
private ActionBarDrawerToggle mtoggle;
NavigationView navigationview;
BottomNavigationView mBottomNav;
private VideoView videoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onInitialize();
navigationDrawer();
sideView();
videoView = findViewById(R.id.videoView);
videoView.setVideoPath("android.resource://"+getPackageName()+"/"+R.raw.video);
videoView.start();
}
public void onInitialize() {
mdrawerlayout = (DrawerLayout) findViewById(R.id.drawer);
navigationview = (NavigationView) findViewById(R.id.navigation);
mBottomNav = (BottomNavigationView) findViewById(R.id.bottom_navigation);
}
public void navigationDrawer() {
mtoggle = new ActionBarDrawerToggle(this, mdrawerlayout, R.string.open, R.string.close);
mdrawerlayout.addDrawerListener(mtoggle);
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationview.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.youtube_videos:
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/user/flavourbasket"));
startActivity(i);
mdrawerlayout.closeDrawers();
break;
}
return true;
}
});
}
public void sideView() {
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// handle desired action here
// One possibility of action is to replace the contents above the nav bar
// return true if you want the item to be displayed as the selected item
switch (item.getItemId()) {
case R.id.extra_id:
Intent i = new Intent(MainActivity.this, Extras.class);
startActivity(i);
break;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mtoggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The ActionBar can be null. The code below will work:
toolbar = findViewById(R.id.tools);
setSupportActionBar(toolbar);
ActionBar ab = ((AppCompatActivity)getActivity()).getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}

Onclick button Event in fragment

I've tried two types of code to get this to work and it keeps giving me force closes when I press the button to go into another Activity. I'm using a Fragment and there's a button in that Fragments code but I can't seem to get it to work.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.androidbelieve.activity.LoginActivity;
import com.androidbelieve.helper.SQLiteHandler;
import com.androidbelieve.helper.SessionManager;
import java.util.HashMap;
public class PrimaryFragment extends Fragment {
private TextView txtName;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout rootView = (RelativeLayout) inflater.inflate(R.layout.primary_layout, container, false);
txtName = (TextView) rootView.findViewById(R.id.username);
btnLogout = (Button) rootView.findViewById(R.id.logout);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// session manager
session = new SessionManager(getActivity().getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
// Displaying the user details on the screen
txtName.setText(name);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
Button button = (Button) rootView.findViewById(R.id.saleentry);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDetail();
}
});
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), SentFragment.class);
startActivity(intent);
}
I was trying to go to another page using button, but it always fail.
Here is my stacktrace..this is the result when i used onclicklistener
04-07 22:42:37.285 27777-27777/com.androidbelieve.drawerwithswipetabs >E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidbelieve.drawerwithswipetabs, PID: 27777
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, >com.android.systemui=overlay:system}
android.content.ActivityNotFoundException: Unable to find explicit >activity class >{com.androidbelieve.drawerwithswipetabs/com.androidbelieve.drawerwithswipet>abs.SentFragment}; have you declared this activity in your >AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1801)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1514)
at android.app.Activity.startActivityForResult(Activity.java:3930)
at android.app.Activity.startActivityForResult(Activity.java:3890)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:907)
at android.support.v4.app.Fragment.startActivity(Fragment.java:916)
at com.androidbelieve.drawerwithswipetabs.PrimaryFragment.updateDetail(PrimaryFragment.java:75)
at com.androidbelieve.drawerwithswipetabs.PrimaryFragment$2.onClick(PrimaryFragment.java:67)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21156)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5456)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
firstly you have to add frame layout in your xml layout.
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
then use this code on click
Button button = (Button) rootView.findViewById(R.id.saleentry);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new SentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.remove(new PrimaryFragment ());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});

Problems while switching activity using intent

I am trying to create a student management application. So far I have made a login page. I am a beginner to android so I have downloaded another sample activity to understand how to link to activites using intent. So far as soon as I click on login, the app crashes. Could anyone help me understand what is going wrong?
This is my Login Page (MainActivity.java).
package zade.example.com.zade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText username = null;
private EditText password = null;
private Button login;
int counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.eno);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login_button);
}
public void login(View view) {
if (username.getText().toString().equals("1") &&
password.getText().toString().equals("a")) {
Toast.makeText(getApplicationContext(), "Login Successful",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Home.class);
this.startActivity ( intent );
}
else {
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
counter--;
if (counter == 0) {
login.setEnabled(false);
}
}
}
}
This is the Home.java (Home activity)
package zade.example.com.zade;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Locale;
public class Home extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Intent intent = getIntent();
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
Logcat
--------- beginning of crash
01-19 14:35:25.458 2116-2116/zade.example.com.zade E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: zade.example.com.zade, PID: 2116
java.lang.RuntimeException: Unable to start activity ComponentInfo{zade.example.com.zade/zade.example.com.zade.Home}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at zade.example.com.zade.Home.onCreate(Home.java:55)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="zade.example.com.zade" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Home"
android:label="#string/title_activity_home"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="zade.example.com.zade.MainActivity" />
</activity>
</application>
</manifest>
Instead of using
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
use
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Also make sure that you use getSupportActionBar() in place of getActionBar() in all occurrences.
This is because you are getting null when you are using getActionBar() as in LogCat it say
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
Use getSupportActionBar(), hope it helps.
If you are still getting the crash after doing this please tell me.
Check whether you added the second activity class in your AndroidManifest.XML file as a child of tag.
the following code might help:
login = (Button) findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//change the page and other stuffs you wish to when
//user will hit logIn button
}
});
It should not be so hard
1)Create 2 java files Activity1.java and activity2.java create suitables xml files if you want.
2)declare the second activity in the manifest.xml file within the
<Application> </Application tags.
in this activities onCreate write the following code
Intent intent = new Intent(this,Activity2.class);
startActivity(intent);

Categories