Android protected void onCreate(Bundle savedInstanceState) { error - android

I am making a Soudboard with a navigation drawer I am getting an error on two things here is the code
package com.example.user.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Button;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
case 2:
objFragment = new menu3_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer intromp = MediaPlayer.create(this, R.raw.intro);
Button intro = (Button) this.findViewById(R.id.intro);
intro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (intromp.isPlaying()) {
intromp.seekTo(0);
} else {
intromp.start();
}
}
});
final MediaPlayer holyshitmp = MediaPlayer.create(this, R.raw.holyshit);
final Button holyshit = (Button) this.findViewById(R.id.holyshit);
holyshit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holyshitmp.isPlaying()) {
holyshitmp.seekTo(0);
} else {
holyshitmp.start();
}
}
});
final MediaPlayer limberthanwatermp = MediaPlayer.create(this, R.raw.limberthanwater);
Button limberthanwater = (Button) this.findViewById(R.id.limberthanwater);
limberthanwater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (limberthanwatermp.isPlaying()) {
limberthanwatermp.seekTo(0);
} else {
limberthanwatermp.start();
}
}
});
final MediaPlayer sandpapernipplwsmp = MediaPlayer.create(this, R.raw.sandpapernipples);
Button sandpapernipples = (Button) this.findViewById(R.id.sandpapernipples);
sandpapernipples.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (sandpapernipplwsmp.isPlaying()) {
sandpapernipplwsmp.seekTo(0);
} else {
sandpapernipplwsmp.start();
}
}
});
final MediaPlayer raisemyweinermp = MediaPlayer.create(this, R.raw.raisingmyweiner);
Button raisemyweiner = (Button) this.findViewById(R.id.raisemyweiner);
raisemyweiner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (raisemyweinermp.isPlaying()) {
raisemyweinermp.seekTo(0);
} else {
raisemyweinermp.start();
}
}
});
final MediaPlayer alientacklesatreemp = MediaPlayer.create(this, R.raw.alientacklesatree);
final Button alientacklesatree = (Button) this.findViewById(R.id.alientacklesatree);
alientacklesatree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (alientacklesatreemp.isPlaying()) {
alientacklesatreemp.seekTo(0);
} else {
alientacklesatreemp.start();
}
}
});
final MediaPlayer nipplerubbermp = MediaPlayer.create(this, R.raw.nipplerubber);
Button nipplerubber = (Button) this.findViewById(R.id.nipplerubber);
nipplerubber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (nipplerubbermp.isPlaying()) {
nipplerubbermp.seekTo(0);
} else {
nipplerubbermp.start();
}
}
});
final MediaPlayer shittalkmp = MediaPlayer.create(this, R.raw.shittalk);
Button shittalk = (Button) this.findViewById(R.id.shittalk);
shittalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (shittalkmp.isPlaying()) {
shittalkmp.seekTo(0);
} else {
shittalkmp.start();
}
}
});
}
}
There is an error on both of the
protected void onCreate(Bundle savedInstanceState) {
statements that says onCreate(Bundle) is already defined in MainActivity
Also sorry for the names of the sound file names, they're from a Youtuber which doesn't particularly censor his videos.

try to add this in MainActivity.java
import android.os.Bundle;

Related

How to write the User name in the Navigation Drawer of a navigational activity From One of its Fragments?

HomeActivity.java (Navigational Activity)
import android.app.Fragment;
import android.app.FragmentManager;
mport android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
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.view.View;
import android.widget.TextView;
import com.example.dellpc.reuz_app.DTO.User;
import com.example.dellpc.reuz_app.Fragments.BrowseAdFragment;
import com.example.dellpc.reuz_app.Fragments.LoginFragment;
import com.example.dellpc.reuz_app.Fragments.NetworkErrorFragment;
import com.example.dellpc.reuz_app.Fragments.TopMainFragment;
import com.example.dellpc.reuz_app.R;
import com.example.dellpc.reuz_app.utils.CheckNetworkConnection;
import com.example.dellpc.reuz_app.utils.NetworkErrorFragmentSetter;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Fragment fragment;
private String title;
private DrawerLayout drawer;
private NavigationView navigationView;
private View layout;
private User user=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("REUZ");
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
System.out.println(getSupportActionBar().getHeight());
View headerLayout = navigationView.getHeaderView(0);
layout=headerLayout.findViewById(R.id.navigationHeader);
getSupportActionBar().setTitle("REUZ");
this.setInitialFragment();
this.listeners();
/*this.getUserObject();*/
}
public void listeners(){
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(CheckNetworkConnection.isConnectionAvailable(HomeActivity.this))
{
getLoginFragment();
}
else{
fragment= NetworkErrorFragmentSetter.getNetworkErrorFragment(HomeActivity.this);
replaceFragment();
}
}
});
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
if (currentFragment instanceof TopMainFragment) {
getSupportActionBar().setTitle("REUZ");
}
else if (currentFragment instanceof BrowseAdFragment) {
getSupportActionBar().setTitle("All Categories");
}
else if (currentFragment instanceof LoginFragment) {
getSupportActionBar().setTitle("LOGIN");
}
else if(currentFragment instanceof NetworkErrorFragment){
getSupportActionBar().setTitle("NETWORK ERROR");
}
}
});
}
#Override
public void onBackPressed() {
//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.home, 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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the home action
setInitialFragment();
} else if (id == R.id.nav_browse) {
fragment=new BrowseAdFragment();
} else if (id == R.id.nav_submitAd) {
Intent intent=new Intent(getApplicationContext(),SubmitAdActivity.class);
startActivity(intent);
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_my_ads) {
} else if (id == R.id.nav_wishList) {
}
replaceFragment();
//drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setTitleOnActionBar(String title) {
getSupportActionBar().setTitle(title);
}
public void setInitialFragment(){
fragment=new TopMainFragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
// ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
public void getLoginFragment(){
fragment=new LoginFragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
public void replaceFragment(){
FragmentTransaction ft=getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onResume() {
super.onResume();
// Set the title
}
public void getUserObject(User user){
this.user=user;
if(user!=null){
changeLayoutName();
}
}
public void changeLayoutName(){
TextView name= (TextView)layout.findViewById(R.id.textView8);
name.setText(user.getName());
}
}
LoginFragment.java(Fragment)
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.dellpc.reuz_app.Activities.HomeActivity;
import com.example.dellpc.reuz_app.Activities.RegisterActivity;
import com.example.dellpc.reuz_app.Activities.UnableToLoginActivity;
import com.example.dellpc.reuz_app.DTO.User;
import com.example.dellpc.reuz_app.R;
import com.example.dellpc.reuz_app.Validator.IValidation;
import com.example.dellpc.reuz_app.Validator.Validation;
import com.example.dellpc.reuz_app.dao.IUserDAO;
import com.example.dellpc.reuz_app.dao.UserDAO;
public class LoginFragment extends Fragment {
private EditText emailET, passwordET;
private Button loginBTN;
private TextView utlTV, registerTV, invalidEmailTV, invalidPasswordTV;
private View view;
private NavigationView navigationView;
private User user;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_login, container, false);
Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);
((HomeActivity)getActivity()).getSupportActionBar().setTitle("LOGIN");
this.mapping();
this.listeners(view);
return view;
}
public void mapping(){
emailET = (EditText)view.findViewById(R.id.emailET);
passwordET = (EditText)view.findViewById(R.id.passwordET);
loginBTN = (Button)view.findViewById(R.id.loginBTN);
utlTV = (TextView)view.findViewById(R.id.utlTV);
invalidEmailTV = (TextView)view.findViewById(R.id.invalidEmailTV);
invalidPasswordTV = (TextView)view.findViewById(R.id.invalidPasswordTV);
registerTV = (TextView)view.findViewById(R.id.registerTV);
}
public void listeners(View view){
loginBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
validateAndMoveToActivity(email, password);
}
});
utlTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent utlIntent = new Intent(getActivity(), UnableToLoginActivity.class);
startActivity(utlIntent);
}
});
registerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(getActivity(), RegisterActivity.class);
startActivity(registerIntent);
}
});
emailET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
invalidEmailTV.setText("");
invalidPasswordTV.setText("");
}
});
passwordET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s)
{
invalidEmailTV.setText("");
invalidPasswordTV.setText("");
}
});
}
public void validateAndMoveToActivity(String email, String password){
IValidation iValidation = new Validation();
if(!iValidation.isFilled(email) && iValidation.isFilled(password)){
invalidEmailTV.setText("This field is required");
}
else if(iValidation.isFilled(email) && !iValidation.isFilled(password)) {
invalidPasswordTV.setText("This field is required");
}
else if(!iValidation.isFilled(email) && !iValidation.isFilled(password)){
invalidEmailTV.setText("This field is required");
invalidPasswordTV.setText("This field is required");
}
else
{
IUserDAO iUserDAO = new UserDAO(getActivity().getApplicationContext());
/*
if(iUserDAO.isEmailPasswordExist(email, password))*/
if(iUserDAO.isEmailExist(email)){
user=iUserDAO.isEmailPasswordExist(email,password);
if(user!=null)
{
Toast.makeText(view.getContext(), "Successful Login", Toast.LENGTH_SHORT).show();
HomeActivity home=new HomeActivity();
home.getUserObject(user);
/* Intent homeACIntent = new Intent(view.getContext(), HomeActivity.class);
homeACIntent.putExtra("user",user);
startActivity(homeACIntent);*/
// Remove this fragment.
getActivity().getFragmentManager().popBackStack();
}
else {
invalidPasswordTV.setText("Invalid email or password");
}
}
else {
// After successful login where do you want to move your activity.
invalidEmailTV.setText("Invalid phone number or email");
}
}
}
#Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putSerializable("user",user);
}
}
HomeActivity contains Two Fragments- Login And Top
Initially it shows top fragment
Login Fragment has a option for registration
After successful registration the user is navigated to login fragment
Now after Login the control must reach to the "Top" and the name of the user has to written in the Navigation Drawer
How to do it?
this is my Drawer .t want to write name of User instead of welcome to Reuz
HomeActivity
I see that you're saving the user details in your local database, and then trying to load the data after the user has successfully logged in. The issue that you're facing is that the TextView is not being updated. One possible solution that you can call the changeLayoutName() method from the onViewCreated() method of the TopMainFragment itself.

Trouble switching fragment view to main view

I am stuck trying to put the content from my fragment into the main view in android studio.
The app compiles and runs. But when I choose an item in the navigation drawer (sliding menu) to the item in the list with the fragment: it is blank.
My fragment contains an embedded YouTube player.
The logCat does not show an error...
From my code - what am I over looking that is wrong??
here is the main Activity:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
//displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
/* #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
} */
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Here is the fragment class:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MasjidAlHaramFragment extends Fragment implements YouTubePlayer.OnInitializedListener {
public String API_KEY = "xxxxxxxxxxxxxxxxxxxxx";
//http://youtu.be/<VIDEO_ID>
//final String VIDEO_ID = "4OoKpZWJASY";
public String VIDEO_ID_2 = "VopbGPJVkzM";
public MasjidAlHaramFragment () {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_masjidharam, container, false);
//http://youtu.be/<VIDEO_ID>
//final String VIDEO_ID = "4OoKpZWJASY";
//final String VIDEO_ID_2 = "VopbGPJVkzM";
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = null;
if (youTubePlayerView != null)
youTubePlayerView = (YouTubePlayerView) getView().findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
//setContentView(R.layout.activity_main);
}
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
//Toast.makeText(this,"Failured to Initialize!", Toast.LENGTH_LONG).show();
}
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(VIDEO_ID_2);
}
}
YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(YouTubePlayer.ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
};
}
and here is the XML view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp" />
</RelativeLayout>
Thanks.
ironmantis7x
You need to call super.onCreateView(...) in the fragment's onCreateView method for the fragment to be drawn correctly.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Also, I'd recommend doing the following, since there are a few logical errors:
View rootView = inflater.inflate(R.layout.fragment_masjidharam, container, false);
YouTubePlayerView youTubePlayerView = null;
// THIS IS ALWAYS FALSE. Comment it out or else it'll never get set.
// if (youTubePlayerView != null)
youTubePlayerView = (YouTubePlayerView) rootView.findViewById(R.id.youtube_player);
// Check for not-null here.
if(youTubePlayerView != null) {
youTubePlayerView.initialize(API_KEY, this);
}

Button linked to sounds onStart

I'm working on an app there are no errors with this app however whenever i test it on my phone there are supposed to be sounds when I touch the button however no sounds.
MainActivity
package com.example.user.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Button;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
case 2:
objFragment = new menu3_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
protected void onStart(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{
setContentView(R.layout.activity_main);
final MediaPlayer intromp = MediaPlayer.create(this, R.raw.intro);
Button intro = (Button) this.findViewById(R.id.intro);
intro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (intromp.isPlaying()) {
intromp.seekTo(0);
} else {
intromp.start();
}
}
});
final MediaPlayer holyshitmp = MediaPlayer.create(this, R.raw.holyshit);
final Button holyshit = (Button) this.findViewById(R.id.holyshit);
holyshit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holyshitmp.isPlaying()) {
holyshitmp.seekTo(0);
} else {
holyshitmp.start();
}
}
});
final MediaPlayer limberthanwatermp = MediaPlayer.create(this, R.raw.limberthanwater);
Button limberthanwater = (Button) this.findViewById(R.id.limberthanwater);
limberthanwater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (limberthanwatermp.isPlaying()) {
limberthanwatermp.seekTo(0);
} else {
limberthanwatermp.start();
}
}
});
final MediaPlayer sandpapernipplwsmp = MediaPlayer.create(this, R.raw.sandpapernipples);
Button sandpapernipples = (Button) this.findViewById(R.id.sandpapernipples);
sandpapernipples.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (sandpapernipplwsmp.isPlaying()) {
sandpapernipplwsmp.seekTo(0);
} else {
sandpapernipplwsmp.start();
}
}
});
final MediaPlayer raisemyweinermp = MediaPlayer.create(this, R.raw.raisingmyweiner);
Button raisemyweiner = (Button) this.findViewById(R.id.raisemyweiner);
raisemyweiner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (raisemyweinermp.isPlaying()) {
raisemyweinermp.seekTo(0);
} else {
raisemyweinermp.start();
}
}
});
final MediaPlayer alientacklesatreemp = MediaPlayer.create(this, R.raw.alientacklesatree);
final Button alientacklesatree = (Button) this.findViewById(R.id.alientacklesatree);
alientacklesatree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (alientacklesatreemp.isPlaying()) {
alientacklesatreemp.seekTo(0);
} else {
alientacklesatreemp.start();
}
}
});
final MediaPlayer nipplerubbermp = MediaPlayer.create(this, R.raw.nipplerubber);
Button nipplerubber = (Button) this.findViewById(R.id.nipplerubber);
nipplerubber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (nipplerubbermp.isPlaying()) {
nipplerubbermp.seekTo(0);
} else {
nipplerubbermp.start();
}
}
});
final MediaPlayer shittalkmp = MediaPlayer.create(this, R.raw.shittalk);
Button shittalk = (Button) this.findViewById(R.id.shittalk);
shittalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (shittalkmp.isPlaying()) {
shittalkmp.seekTo(0);
} else {
shittalkmp.start();
}
}
});
}
}
}
ActivityMain
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id = "#+id/container">
<!--Note for Ryan, id Container is needed because it will not display the navigation menu aka the container-->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/intro"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:text="Intro"
android:singleLine="true"/>
<Button
android:id="#+id/holyshit"
android:layout_width="193dp"
android:layout_height="wrap_content"
android:text="Holy shit"
android:singleLine="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/limberthanwater"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:text="Limber Than Water"
android:singleLine="true"/>
<Button
android:id="#+id/sandpapernipples"
android:layout_width="193dp"
android:layout_height="wrap_content"
android:text="Sandpaper Nipples"
android:singleLine="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/raisemyweiner"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:text="Raise My Weiner"
android:singleLine="true"/>
<Button
android:id="#+id/alientacklesatree"
android:layout_width="193dp"
android:layout_height="wrap_content"
android:text="Alien tacking a tree"
android:singleLine="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/nipplerubber"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:text="Nipple Rubber"
android:singleLine="true"/>
<Button
android:id="#+id/shittalk"
android:layout_width="193dp"
android:layout_height="wrap_content"
android:text="Shit Talk"
android:singleLine="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.user.myapplication.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
There is also a very basic Navigation drawer. It has nothing on it only text so I am not posting that here because it's pointless
Everything works fine however the only issue is the buttons. I am really new to android. I initially had an onCreate instead of the onStart where the buttons' actions were because it had errors and I was told that It onCreate can only be called once per activity.
If you can give an answer and also provide explanation that would greatly be appreciated to improve my learning.
remove the onStart
and transfer the value to onCreate
it should be like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer intromp = MediaPlayer.create(this, R.raw.intro);
Button intro = (Button) this.findViewById(R.id.intro);
intro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (intromp.isPlaying()) {
intromp.seekTo(0);
} else {
intromp.start();
}
}
});
final MediaPlayer holyshitmp = MediaPlayer.create(this, R.raw.holyshit);
final Button holyshit = (Button) this.findViewById(R.id.holyshit);
holyshit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holyshitmp.isPlaying()) {
holyshitmp.seekTo(0);
} else {
holyshitmp.start();
}
}
});
final MediaPlayer limberthanwatermp = MediaPlayer.create(this, R.raw.limberthanwater);
Button limberthanwater = (Button) this.findViewById(R.id.limberthanwater);
limberthanwater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (limberthanwatermp.isPlaying()) {
limberthanwatermp.seekTo(0);
} else {
limberthanwatermp.start();
}
}
});
final MediaPlayer sandpapernipplwsmp = MediaPlayer.create(this, R.raw.sandpapernipples);
Button sandpapernipples = (Button) this.findViewById(R.id.sandpapernipples);
sandpapernipples.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (sandpapernipplwsmp.isPlaying()) {
sandpapernipplwsmp.seekTo(0);
} else {
sandpapernipplwsmp.start();
}
}
});
final MediaPlayer raisemyweinermp = MediaPlayer.create(this, R.raw.raisingmyweiner);
Button raisemyweiner = (Button) this.findViewById(R.id.raisemyweiner);
raisemyweiner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (raisemyweinermp.isPlaying()) {
raisemyweinermp.seekTo(0);
} else {
raisemyweinermp.start();
}
}
});
final MediaPlayer alientacklesatreemp = MediaPlayer.create(this, R.raw.alientacklesatree);
final Button alientacklesatree = (Button) this.findViewById(R.id.alientacklesatree);
alientacklesatree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (alientacklesatreemp.isPlaying()) {
alientacklesatreemp.seekTo(0);
} else {
alientacklesatreemp.start();
}
}
});
final MediaPlayer nipplerubbermp = MediaPlayer.create(this, R.raw.nipplerubber);
Button nipplerubber = (Button) this.findViewById(R.id.nipplerubber);
nipplerubber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (nipplerubbermp.isPlaying()) {
nipplerubbermp.seekTo(0);
} else {
nipplerubbermp.start();
}
}
});
final MediaPlayer shittalkmp = MediaPlayer.create(this, R.raw.shittalk);
Button shittalk = (Button) this.findViewById(R.id.shittalk);
shittalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (shittalkmp.isPlaying()) {
shittalkmp.seekTo(0);
} else {
shittalkmp.start();
}
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}

Navigation drawer won't close when item selected

I have a navigation drawer that when an Item is selected, it loads the new fragment but never closes the drawer. My navigation drawer code looks like this:
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends ActionBarActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
//getActionBar().setDisplayHomeAsUpEnabled(true);
//enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu_white, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
//getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
//getActionBar().setTitle(mTitle);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
//setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
//setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
I also have an enum that I use for my drawer which looks like this:
import android.support.v4.app.Fragment;
public enum MainNavItem
{
// Displayed in NavDrawerListAdapter
STATISTICS("Your Statistics", R.layout.statistics_pagelayout, StatisticsPage.class),
DISCOVER ("Discover", R.layout.activity_discover, BPTopBeers.class),
PORTFOLIO ("Portfolio", R.layout.activity_portfolio, Portfolio.class),
DRINKLOCAL ("Drink Local", R.layout.beer_location_list, DrinkLocal.class),
Map ("Brewery Map", R.layout.activity_brewmap, MapTabs.class),
LISTS ("Your Lists", R.layout.activity_search, AllLists.class),
NEWS ("News", R.layout.activity_news, NewsWeb.class),
Find ("Nearby Breweries", R.layout.beer_location_list, FindBrewery.class),
CONTACT ("Contact", R.layout.activity_contact, ContactPage.class),
// Items NOT displayed in NavDrawerListAdapter
SEARCH ("Search", R.layout.activity_search, Search.class),
;
private static MainNavItem LAST_NAV_ITEM = CONTACT;
private String mTitleResId;
private int mLayoutResId;
private Class<? extends Fragment> mFragClass;
private MainNavItem(String titleResId, int layoutResId, Class<? extends Fragment> fragClass)
{
mTitleResId = titleResId;
mLayoutResId = layoutResId;
mFragClass = fragClass;
}
public int getLayoutResId()
{
return mLayoutResId;
}
public String getTitleResId()
{
return mTitleResId;
}
public Class<? extends Fragment> getFragClass()
{
return mFragClass;
}
public static MainNavItem[] getNavAdapterItems()
{
int count = LAST_NAV_ITEM.ordinal() + 1;
MainNavItem[] adapterItems = new MainNavItem[count];
for(int i = 0; i < count; i++){
adapterItems[i] = values()[i];
}
return adapterItems;
}
}
Add this to your onItemClick method of the mDrawerList
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
I can't find where are you loading fragment in your code but you are probably missing mDrawerToggle.onDrawerClosed(mDrawerLayout); before you replace your fragments.

Android - ActionBarSherlock Navigation Drawer and Fragments with Activities

I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}

Categories

Resources