0

well i think my question describes itself , anyways here is the code

public class  NowPlaying extends Activity implements Serializable  {
    static MediaPlayer mp =new MediaPlayer();

    String artist;ProgressDialog pd;
    int position; String key=null ;
    /*int z=0;
    SeekBar songProgressBar ;
    TextView songCurrentDurationLabel;
    TextView songTotalDurationLabel ;
    private Handler mHandler = new Handler();
    private Utilities utils=new Utilities();
    */

    @SuppressLint("NewApi")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.now_playing);
        Intent i = getIntent();
         position=i.getIntExtra("Data2", 0);
         /* songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
          songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
          songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
            */

        final ArrayList<SongDetails> songs = getIntent().getParcelableArrayListExtra("Data1"); 

         pd = new ProgressDialog(this);
         pd.setMessage("Loading...");


            Playservice(songs,position  );


        Button bfake=(Button) findViewById(R.id.bFake);
        LinearLayout LL=(LinearLayout) findViewById(R.id.LL);
        Button Pause=(Button)findViewById(R.id.bPlayPause);
        // songProgressBar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this); // Important

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer player) {

                position=position+1;



                 Playservice(songs,position);





            }});
         bfake.setOnTouchListener(new OnSwipeTouchListener()
         {           public void onSwipeRight() {
                 position=position-1;   
                 Playservice(songs,position  );
             }
                public void onSwipeLeft() {
                 position=position+1;   
                 Playservice(songs,position );
                }
                public void onSwipeBottom() {
                    mp.stop();
                }
               });
            LL.setOnTouchListener(new OnSwipeTouchListener() {
               public void onSwipeBottom() {
                    mp.stop();
                }
               });  
            Pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
            {if(mp.isPlaying())
                mp.pause();
            else
                mp.start();
            }
            });
    }

     private void Playservice( ArrayList<SongDetails> songs, int position    )

         {



         int currentPosition= 0;
            int total = mp.getDuration();
           /* while (mp!=null && currentPosition<total) {
                try {
                    Thread.sleep(1000);
                    currentPosition= mp.getCurrentPosition();
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    break;
                }            
          //      songProgressBar.setProgress(currentPosition);
            */





          try {
                 String ab=songs.get(position).getPath2().toString();
                 artist=songs.get(position).getArtist();
                 new Xmlparse().execute(); 
                if(mp.isPlaying())
                    {   mp.stop();
                        }
                    mp.reset();
                    mp.setDataSource(ab) ;
                    mp.prepare();
                    mp.start();
            //      songProgressBar.setProgress(0);
                //  songProgressBar.setMax(mp.getDuration());
                    new Thread().start();
                } catch (IllegalArgumentException e) {

                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e)
                {
                    e.printStackTrace();
                } 


         }
     /*public void onStartTrackingTouch(SeekBar seekBar) {
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
        }

        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            if(fromUser) mp.seekTo(progress);

        }


*/
class Xmlparse extends AsyncTask<Void,Drawable,Drawable>
 {
    protected void onPostExecute(Drawable result) {
       // super.onPostExecute(result);
        pd.dismiss();
        LinearLayout LL=(LinearLayout) findViewById(R.id.LL);
         LL.setBackgroundDrawable(result);


        // Toast.makeText(getApplicationContext(),result, 1000).show();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd.show();
    }
    @Override
    protected Drawable doInBackground(Void... params) {
        Drawable s =getData();
        return s;
    }  

    public Drawable getData()
    {  Drawable drawable = null;//=new BitmapDrawable(bmp); 

        artist=artist.trim();
        artist=artist.replace(" ", "%20");

        try{

          URL url = new URL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" +artist+              "&api_key=1732077d6772048ccc671c754061cb18");
        URLConnection connection = url.openConnection();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        final Document document = db.parse(connection.getInputStream());
        document.getDocumentElement().normalize();
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xPathEvaluator = xPathfactory.newXPath();
        XPathExpression nameExpr = xPathEvaluator.compile("//lfm/artist/image");
        // XPathExpression nameExpr = xPathEvaluator.compile("//lfm/tracks/track/image");
        NodeList nl = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);


        for (int zzz = 0; zzz < nl.getLength(); zzz++)
        {
            Node currentItem = nl.item(zzz);
            key = currentItem.getTextContent();


            // key = currentItem.getAttributes().getNamedItem("uri").getNodeValue();
        }URL ulrn = new URL(key);
        HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
        InputStream is = con.getInputStream();
        Bitmap bmp = BitmapFactory.decodeStream(is);
        drawable=new BitmapDrawable(bmp); 
        }
        catch(Exception e)
        {}
        return drawable;}   
  }}
Ankit Srivastava
  • 280
  • 2
  • 7
  • 24

2 Answers2

3

it restarts because your activity was recreated... each time the user change the orientation of the device the oncreate method is called again. to fix this try add this to your activity in the manifest file:

   android:configChanges="orientation|keyboardHidden">
Tobiel
  • 1,543
  • 12
  • 19
  • thank you,but how will this help( i can't test it right now,because my friend took away the phone i was testing upon,and my emulator doesn't work as well) – Ankit Srivastava Sep 03 '13 at 16:44
  • this will help because your are telling to the system that, you don't want to recreate your activity each time the orientation changes. – Tobiel Sep 03 '13 at 16:46
  • ok thanx,but what if its a fragment??should i put this code in the holder activity of the fragment??or is there another way to do it?(fragments are not declared in the manifest) – Ankit Srivastava Sep 03 '13 at 16:47
  • see this: http://stackoverflow.com/questions/10634854/android-fragments-recreated-on-orientation-change – Tobiel Sep 03 '13 at 16:48
3

Try this in your manifest...

 <activity android:name="Your Activity Name"
             android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="adjustPan"/>  
Hariharan
  • 24,741
  • 6
  • 50
  • 54