Multiple MediaPlayer background instead of 1 - android-activity

I'm trying to run an App that has only one background song that runs on all activities. But some how when I open another activity, (all the activities are extends of the main activity), the application opens another session of the song. I tried to fix it but with no success.
I don't understand why the "Music:IsPlaying" is always false despite that the song is playing, this is my code:
public class MainActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Music = MediaPlayer.create(MainActivity.this, R.raw.ad_matai);
if (!Music.isPlaying())
{
Music.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void OpenMyProfile(View view)
{
Intent open_my_profile = new Intent(this,MyProfile.class);
startActivity(open_my_profile);
}
public void OpenPeople(View view)
{
Intent open_people = new Intent(this,PazamPeople.class);
startActivity(open_pazam_people);
}

Why don't You use service for that? If You have task which should be active for longer than single activity lifecycle it should be service for that. Hit Google with 'music service android'

Related

Android - Top Back Button not working

I have this button on the topmost left part. And for some reason it is not going back to it's previous page when I click it. I've checked the other links already but it is not working.
The activity code on that one
public class CardListActivity extends Activity {
private static final String LOG_TAG = CardListActivity.class.getSimpleName();
private EventBus eventBus;
private Activity activity;
private CardListRequest cardListRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
public void init() {
Log.e(LOG_TAG, "XXXX Start : init XXXX");
setUpActionBar();
activity = this;
setContentView(R.layout.activity_card_list);
Log.e(LOG_TAG, "XXXX Finish : init XXXX");
}
private void setUpActionBar() {
getActionBar().setTitle(CardListActivity.class.getSimpleName());
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
AndroidManifest.xml
...
<activity
android:name=".CardListActivity"
android:label="#string/title_activity_card_list"
android:parentActivityName=".HomeActivity2">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.pw.mccdealsapp.HomeActivity2" />
</activity>
...
This page contains all the information to create an Up button that works correctly.
You need to add, in your activity, something like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
first on your onCreate method put this
//action bar back icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
then override this method and make back opetion go to its parent
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}

My Android App is crashed when I register SensorManager.registerListener

Below is my code. I am having a problem when I call SensorManager.registerListener, my app will crash. Can someone tell me what's going on?
I just follw the web guide to setup SensorManger, Sensor(Accelerometer) and then register the action lintener to detect the montion of accelerometer.
I used API 21 to develop this app.
public class MainActivity extends ActionBarActivity implements SensorEventListener{
private TextView tip;
private SensorManager mSensorManager;
private Sensor mSensor;
private float axisX = 0;
private float axisY = 0 ;
private float axisZ = 0;
#Override
protected void onResume() {
super.onResume();
setUpAcceleratorSensor();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpAcceleratorSensor();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpAcceleratorSensor(){
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if((mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null);
else
Toast.makeText(this, "No Sensor Device Exist", Toast.LENGTH_LONG).show();
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] != 0 || event.values[1] != 0 || event.values[2] != 0){
axisX = event.values[0];
axisY = event.values[1];
axisZ = event.values[2];
tip.setText("Detect your montion");
}
}
else
Toast.makeText(this, "Cannot Get Sensor Device", Toast.LENGTH_LONG).show();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Thanks.
First that I always check when something like this goes wrong, is to check that you have all the correct permissions in the Android Manifest; however, I don't believe that there are any permissions associated with using the position sensors. I would check on this first. That is what comes to mind first, after you post logcat, we will be able to give a more detailed answer.
Try getting the sensor this way
mSensor = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0); instead in your setUpAccelerometer() method.

Android ImageButton Onclick not working

I'm trying to change images when an image button is clicked. Even without the code for changing image my application is crashing whenever I use an onClickListener or try to set an onClick listener. How do i fix this I'm running app on kitkat api 19
package com.example.t11;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Scene extends ActionBarActivity {
ImageView scene=(ImageView) findViewById(R.id.images);
int i=0;
int[] imgarray = {R.drawable.i1,R.drawable.i2,R.drawable.i4,R.drawable.i6,R.drawable.i7,R.drawable.i8,R.drawable.i9,R.drawable.i10,R.drawable.i12};
//Just set one Click listener for the image
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scene);
Intent sceneint = getIntent();
ImageButton left = (ImageButton) findViewById(R.id.left);
ImageButton right= (ImageButton) findViewById(R.id.right);
// Left and right button listener creation
left.setOnClickListener(leftlistener);
right.setOnClickListener(rightlistener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.scene, menu);
return true;
}
View.OnClickListener rightlistener = new OnClickListener() {
public void onClick(View v1) {
//Increase Counter to move to next Image
i++;
scene.setImageResource(imgarray[i]);
}
};
View.OnClickListener leftlistener = new OnClickListener() {
public void onClick(View v) {
//Increase Counter to move to Previous Image
i--;
scene.setImageResource(imgarray[i]);
}
};
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instantiate the listener as an anonymous function :
left.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Increase Counter to move to Previous Image
i--;
scene.setImageResource(imgarray[i]);
}
});
if you want the reference of the listener as well for some reason then try instantiating and assigning the listener before registering it with the button.

Unable to load tab in PagerSlidingTabStrip when fragment is replaced

I'm trying to implement a viewpager with a PagerSlidingTabStrip instead of a TabView. The viewpager has three tabs in which each listview displays a list of events. The three tabs are called Past, Tonight and Future.
I've set up the slider as the github page suggests:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
// Set Present tab as default
pager.setCurrentItem(1);
return v;
}
When the app starts the Main Activity adds for the first time this fragment and everything works great. 3 swipeable tabs with 3 listviews. (c.f. code section)
Here is the problem:
I've noticed that when I press the back button and replace the fragment again, in order to reopen the viewpager, the tab in the middle doesn't show any listview. If I swype left or right the content in the other tabs is loaded and displayed but the Present Tab remains empty.
When I debug the ToNightEvents ListFragment isn't called at all.
Do you guys have any suggestions to solve the problem?
The code:
The code is structured as follows: After the onCreateView I've added an OnDestroyView method to remove the fragment but it didn't work... Then in the fragmentPagerAdapter each page is called as a fragment in the getItem method. Finally at the end of the code you can see the three ListFragment classes in which a listview is populated through an AsyncTask
public class FragmentAllEvents extends Fragment
{
private static final String TAG_UID = "uid";
private static final String TAG_LOGO = "logo";
private static final String TAG_POKUID = "pokuid";
static ArrayList<HashMap<String, String>> userList;
ArrayList<HashMap<String, String>> userListTotal;
private final Handler handler = new Handler();
HashMap<String, String> userSelected;
EventsFunctions eventsFunctions;
UserFunctions userFunctions;
static ListView lv;
ActionBar actionBar;
MyPagerAdapter adapter;
ViewPager pager;
PagerSlidingTabStrip tabs;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
//Context context = this;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set up the action bar.
actionBar = getActivity().getActionBar();
actionBar.setHomeButtonEnabled(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setCurrentItem(1);
return v;
}
#Override
public void onDestroyView()
{
super.onDestroyView();
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
switch (i)
{
case 0:
return new PastEvents();
case 1:
return new ToNightEvents();
case 2:
return new FutureEvents();
/*default:
// The other sections of the app are dummy placeholders.
return new ToNightEvents();
*/
}
return null;
}
/**
* A fragment that launches past events list.
*/
public static class PastEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView pastList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View pastView = inflater.inflate(R.layout.pastlist, container, false);
progress = (ProgressBar) pastView.findViewById(R.id.loading_spinner_past);
tabTime="past";
pastList = (ListView) pastView.findViewById(android.R.id.list);
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(pastList, this);
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
return pastView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
//Log.e("AttendList Report", "Clicked list item: " + position +" Content: \n" + map.get(TAG_ID).toString());
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class FutureEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView futureList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View futureView = inflater.inflate(R.layout.futurelist, container, false);
progress = (ProgressBar) futureView.findViewById(R.id.loading_spinner_future);
tabTime = "future";
futureList = (ListView) futureView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(futureList, this);
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
return futureView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class ToNightEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView tonightList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View tonightView = inflater.inflate(R.layout.tonightlist, container, false);
progress = (ProgressBar) tonightView.findViewById(R.id.loading_spinner_tonight);
tabTime = "tonight";
tonightList = (ListView) tonightView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(tonightList, this);
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
return tonightView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
}
}
public String[] titles=
{
"Past",
"Tonight",
"Future"
};
#Override
public int getCount()
{
return titles.length;
}
#Override
public CharSequence getPageTitle(int position)
{
return titles[position];
}
}
}
This would normally work if you were in an Activity, however I guess you are in a Fragment since the code you posted is the method onCreateView(). The problem is that you are trying to use the FragmentManager of the Activity and you should be using the Fragment's FragmentManager. This FragmentManager is not what you need. Try this instead:
adapter = new MyPagerAdapter(getChildFragmentManager());
I think I'm a little bit late but if anyone happens to have the same error here is the solution =)
Q.
The following fixed it for me:
Add an OnBackStackChangedListener to the fragment manager.
In the onBackStackChanged method, get references to both the ViewPager and the PagerSlidingTabStrip (pager and tabs in your example). If the appropriate fragment is currently active, do the following:
pager.invalidate();
tabs.invalidate();
pager.setAdapter(new MyPagerAdapter(getFragmentManager()));
tabs.setViewPager(pager);

Eclipse DisplayMessageActivity error

I have a question about an error I get in Eclipse.
Eclipse says "The nested type DisplayMessageActivity cannot hide an enclosing type"
This is my script:
package com.example.warzonegaming;
public class DisplayMessageActivity {
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Does someone knows an fix for this, because I can't go further now.
Regards
Try learn basics of javapackage com.example.warzonegaming;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}