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));
}
Related
MainActivity.java
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.intel.dualboot, PID: 23319
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}:
java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2330)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:469)
at android.app.BackStackRecord.add(BackStackRecord.java:464)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
replace
com.exmaple.intel.dualboot.InSwipeRefreshLayout
with
android.support.v4.widget.SwipeRefreshLayout
in your xml file,
as the com.exmaple.intel.dualboot.InSwipeRefreshLayout class is not defined
com.exmaple.intel.dualboot.InSwipeRefreshLayout
Check this path if it is correct in your xml.It seems the path of "InSwipeRefreshLayout" is not corect
in your xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.exmaple.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.exmaple.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
the com.exmaple.intel.dualboot.InSwipeRefreshLayout has that spelling of "exmaple", it should be example.
The posted layout working fine for me.Please check the package name properly com.example.intel.dualboot.InSwipeRefreshLayout whether exist or not and clean and build the project.
i have this code onBackPressed in my MainActivity.java
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
and I have HomeFragment.java
what I want is when im in the HomeFragment.java..
I want to add a double tap back to exit my application..
How can I do that?
here is my MainActivity.java
package com.example.administrator.mosbeau;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
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.ImageView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.pm.Signature;
import com.facebook.appevents.AppEventsLogger;
#SuppressWarnings("deprecation")
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;
UserLocalStore userLocalStore;
String customersid, countrycode, carttotal, stateid;
SearchView searchView;
RelativeLayout notifCount;
TextView tv;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://shop.mosbeau.com.ph/android/";
String myJSONcarttotal;
JSONArray jsonarraycarttotal;
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connectivity connectivity=new Connectivity();
if(connectivity.isConnected(MainActivity.this)) {
// Add code to print out the key hash
/*try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.administrator.mosbeau",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}*/
}else{
nointernet();
}
userLocalStore = new UserLocalStore(this);
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));
}
public void onStart() {
super.onStart();
if(authenticate() == true){
displayUserDetails();
}else{
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
}
}
private boolean authenticate() {
if (userLocalStore.getLoggedInUser() == null) {
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
return false;
}
return true;
}
private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
customersid = user.customers_id;
countrycode = user.customers_countryid;
stateid = user.customers_stateid;
if(customersid==""){
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
}
}
#Override
public void onNavigationDrawerItemSelected(int position,String id,String name,String image2) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment.newInstance())
.commit();
}
else if (position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance(id,name,countrycode,image2,customersid,stateid))
.commit();
}
else if (position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, AccountFragment.newInstance(customersid))
.commit();
}
else if (position == 3){
fragmentManager.beginTransaction()
.replace(R.id.container, ReferFragment.newInstance(customersid))
.commit();
}
else if (position == 4){
fragmentManager.beginTransaction()
.replace(R.id.container, AboutFragment.newInstance(customersid))
.commit();
}
else if (position == 5){
fragmentManager.beginTransaction()
.replace(R.id.container, PolicyFragment.newInstance(customersid))
.commit();
}
else if (position == 6){
fragmentManager.beginTransaction()
.replace(R.id.container, TermsFragment.newInstance(customersid))
.commit();
}
else if (position == 7){
fragmentManager.beginTransaction()
.replace(R.id.container, ContactusFragment.newInstance(customersid))
.commit();
}
else if (position == 8){
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Intent myIntent = new Intent(this, IndexActivity.class);
startActivity(myIntent);
}
else if (position == 101){
fragmentManager.beginTransaction()
.replace(R.id.container, CartFragment.newInstance(customersid,countrycode,stateid,"a"))
.commit();
}
}
#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();
// HERE RETURNS NULL
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
int searchImgId = getResources().getIdentifier("android:id/search_button", null, null);
ImageView v = (ImageView) searchView.findViewById(searchImgId);
v.setImageResource(R.drawable.action_searchm);
if (searchView != null) {
final Menu menu_block = menu;
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// collapse the view ?
//menu_block.findItem(R.id.action_search).collapseActionView();
SearchFragment searchFragment = SearchFragment.newInstance(query,countrycode,customersid,stateid);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, searchFragment)
.addToBackStack(null)
.commit();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// search goes here !!
// listAdapter.getFilter().filter(query);
return false;
}
});
//Log.i("sales module", "SearchView QWE");
}else{
//Log.i("sales module", "SearchView is null");
}
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 onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}*/
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
Fragment fragment = getFragmentManager().findFragmentById(R.id.textHomeBack);
if (fragment instanceof HomeFragment) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
else {
super.onBackPressed();
}
}
}
public void nointernet(){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("There seems to be a problem with your connection.");
dialogBuilder.setNegativeButton("Edit Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
dialogBuilder.setPositiveButton("Reload", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
AlertDialog dialog = dialogBuilder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
}
}
and here is my homelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:fillViewport="false"
android:background="#fffff1f1">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#fffff1f1"
android:padding="10dp"
android:orientation="horizontal"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textHomeBack"
android:visibility="invisible"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textCountryId"
android:visibility="invisible"/>
<FrameLayout
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="200dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:gravity="center"
android:layout_gravity="center"/>
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</FrameLayout>
<FrameLayout
android:id="#+id/framelayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/framelayout"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:minHeight="130dp">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="horizontal"
android:id="#+id/horizontalScrollView"
android:fillViewport="false">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"/>
</HorizontalScrollView>
<ProgressBar
android:id="#+id/loading2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</FrameLayout>
<FrameLayout
android:id="#+id/framelayout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/framelayout2"
android:minHeight="200dp">
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:gravity="center"
android:layout_gravity="center" />
<ProgressBar
android:id="#+id/loading3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</FrameLayout>
</RelativeLayout>
</ScrollView>
please help me.
Try it like this :
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof HomeFragment) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
else {
super.onBackPressed();
}
}
}
Try this code..
long back_pressed=0;
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis())
super.onBackPressed();
else
{
Snackbar snackbar=Snackbar.make(view, "Double Tap to Exit!", Snackbar.LENGTH_SHORT);
View view=snackbar.getView();
view.setBackgroundColor(getResources().getColor(R.color.white));
snackbar.show();
back_pressed = System.currentTimeMillis();
}
}
This code must help you to do things.
Define
private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
private long mBackPressed;
While adding fragments to your container, add them with backstack.
private void setFragment(Fragment fragment, int position) {
mTextViewAppTitle.setText(navTitles[position]);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.main_content, fragment)
.addToBackStack(navTitles[position])
.commit();
}
Then in onBackPressed event
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() != 0) {
super.onBackPressed();
return;
}
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Utils.showToast(this, "Tap back button in order to Exit");
}
mBackPressed = System.currentTimeMillis();
}
I have not get double tap to exit any way and I don't know this is right way or not but you can solve your problem following way
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (count == 0)
count = 1;
else
count = 2;
android.os.Handler h = new android.os.Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (count == 2) {
// Just Put Your Code for Exit
Log.d("DoubleTap", "Exit");
}
count= 0;
}
}, 500);//You can set double tap interval currently set half second
// super.onBackPressed();
}
Note : - Declare count as a global int variable;
ex. int count = 0;
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);
}
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;
Hello everyone and thank you in advance,
I looked all around stackoverflow, but couldn't find the answer to my problem.
I have a viewpager, and two different fragments. I can swipe no problem. I'm getting data from a mp3 stream (artist name and song title). I want to put this data in a TextView every 30secs. My problem is that I don't know, from the Main Activity, how to reach the textview in my fragments. I tried using bundle but ended up getting null on getArguments().
I managed, using interfaces to get my main to do something when I click on a button. This time i want my main to do something, and update text in a fragment.
Here is my code :
MainActivity
package com.radioGMT.radio;
import java.net.URL;
import android.app.ActionBar;
.
.
.
import com.radioGMT.tabsswipe.adapter.TabsPagerAdapter;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnButtonPlayListener, OnButtonPauseListener {
private Button button_play;
private Button button_pause;
private AudioManager audioManager;
private TextView textView_info;
private PhoneStateListener phoneStateListener;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
public String URL_GMT ="http://goodmorningtoulouse.bcast.infomaniak.ch:8000/radiogmt.mp3";
boolean finish = false;
public String data_metadata ="ini";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pour Swipe Tabs
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new TabsPagerAdapter(fragmentManager));
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Add 2 tabs, specifying the tab's text and TabListener
actionBar.addTab(actionBar.newTab().setText("Direct").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Programme").setTabListener(this));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//////
Here, I want to setText to a fragment
}
//Classes fonctions et interfaces
//Following three allow for extends FragmentActivity implements ActionBar.TabListener
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
TabsPagerAdapter :
package com.radioGMT.tabsswipe.adapter;
import android.support.v4.app.Fragment;
.
.
import com.radioGMT.radio.ProgrammeFragment;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
#Override
public Fragment getItem(int index) {
Fragment fragment = null;
if (index == 0){
fragment = new LecteurFragment();
}
if (index == 1){
fragment = new ProgrammeFragment();
}
return fragment;
}
}
LecteurFragment
package com.radioGMT.radio;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class LecteurFragment extends Fragment implements View.OnClickListener{
//Declaration des variables
private TextView textView;
private Button mButtonPlay;
private Button mButtonPause;
private OnButtonPlayListener _mClickListener;
private OnButtonPauseListener _mClickPause;
private TextView bottom_text;
//En cours
//Interfaces
public interface OnButtonPlayListener {
public void onButtonPlayInteraction(View view);
}
public interface OnButtonPauseListener {
public void onButtonPauseInteraction(View view);
}
//onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
//onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_lecteur, container, false);
mButtonPlay=(Button) view.findViewById(R.id.button_play);
mButtonPause = (Button) view.findViewById(R.id.button_pause);
// Le programme surveille le bouton play, au cas ou l'utilisateur appuie dessus
mButtonPlay.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
_mClickListener.onButtonPlayInteraction(view);
}
});
//Le programme surveille le bouton pause, au cas ou l'utilisateur appuie dessus
mButtonPause.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
_mClickPause.onButtonPauseInteraction(view);
}
});
return view;
}
//onAttach
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
_mClickListener = (OnButtonPlayListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonPlayListener");
}
try {
_mClickPause = (OnButtonPauseListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + "must implement OnButtonPauseListener");
}
}
//onDetach
#Override
public void onDetach() {
super.onDetach();
_mClickListener = null;
_mClickPause = null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
fragment_lecteur.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/Orange"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/Orange" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="#string/Header_image"
android:src="#drawable/logo_header_v2_4" />
</RelativeLayout>
<LinearLayout
android:id="#+id/Degrade_001"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#layout/gradient_noir_marron"
android:minHeight="10dp"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/Marron"
android:orientation="horizontal" >
<Button
android:id="#+id/button_play"
style="android:attr/buttonBarButtonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="#android:drawable/ic_media_play"
android:drawableStart="#android:drawable/ic_media_play"
android:text="#string/Lecture" />
<Button
android:id="#+id/button_pause"
style="android:attr/buttonBarButtonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="#android:drawable/ic_media_pause"
android:drawableStart="#android:drawable/ic_media_pause"
android:text="#string/Pause" />
</LinearLayout>
<RelativeLayout
android:id="#+id/RelativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/Marron" >
<TextView
android:id="#+id/textView_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<LinearLayout
android:id="#+id/Degrade_002"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#layout/gradient_marron_noir"
android:minHeight="10dp"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="#+id/bottom_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
To resume, I want to write something in bottom_text in LecteurFragment, from my mainactivity.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public LecteurFragment lecteur_fragment;
public ProgrammeFragment programme_fragment;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
lecteur_fragment = new LecteurFragment();
programme_fragment = new ProgrammeFragment();
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int index) {
if (index == 0) {
return lecteur_fragment;
}
else if (index == 1){
return programme_fragment;
}
else {
return null;
}
}
}
And in your activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
FragmentManager fragmentManager = getSupportFragmentManager();
mAdapter = new TabsPagerAdapter(fragmentManager);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Direct").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Programme").setTabListener(this));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override public void onPageScrollStateChanged(int arg0) { }
});
MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//call a function `updateTextView` in the fragment with the value, and the fragment will update its textview..
((LecteurFragment)mAdapter.getItem(0)).updateTextView("myValue");
}
Now in your LecteurFragment
public class LecteurFragment extends Fragment implements View.OnClickListener {
...
public void updateTextView(String value_to_set) {
((TextView) getView().findViewById(R.id.id_of_textview)).setText(value_to_set);
}
...
}
Probably the official approach would be creating an Interface with a method that returns an String.
This interface would be must implemented in the MainActiviy and past as parameter on the TabsPagerAdapter constructor. After that, it could be assigned to the LecteurFragment and use it.
But it isn't really the approach that i would take it. I would just create an static String on MainActivity:
//MainActivity
public static String artistName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//before call setAdapter
artistName = getArtistName()
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new TabsPagerAdapter(fragmentManager));
//etc
}
And use it in the LectureFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_lecteur, container, false);
TextView tv_artist_name = (TextView) view.findViewById(R.id.tv_artist_name);
tv_artist_name.setText(MainActivity.artistName);
}