Search code examples
javaandroidmedia-player

Using play button in Bindview,That play function is not working


I am storing text and audio in db,i am fetching the data and showing using Bindview. But i didnt show my audio recorder filename in the listview,Instead of i am using play button to play that audio.But while clicking the play button its not doing any functions.

My mp is getting null,its not going the else part.But i am sure i am saving the audio file name also i checked that one also.its again and again showing mp is null

private void fillData() {
mDbHelper.open();      
Cursor projectsCursor = mDbHelper.fetchAllProjects3();

int count = projectsCursor.getCount();
Log.i(".................",""+count);
if (projectsCursor.moveToFirst()) {
      do {

          int col1 = projectsCursor.getColumnIndex("expname");
          String expname = projectsCursor.getString(col1);         
          bb.add(expname);                

              int col2 = projectsCursor.getColumnIndex("expcontent");
                        String expcontent = projectsCursor.getString(col2);         
                    aa.add(expcontent);
      } while (projectsCursor.moveToNext());

}
//startManagingCursor(projectsCursor);


// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_EXPNAME,GinfyDbAdapter.CATEGORY_COLUMN_EXPERIENCE,GinfyDbAdapter.CATEGORY_COLUMN_EXPDATE};

int[] to = new int[]{R.id.text2,R.id.text1,R.id.date};
dataAdapter = new CustomAdapter (ExperiencesActivity .this, R.layout.activity_row3, projectsCursor, from, to);
setListAdapter(dataAdapter);



EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {
    }

    public void beforeTextChanged(CharSequence s, int start,
            int count, int after) {
    }

    public void onTextChanged(CharSequence s, int start,
            int before, int count) {
        dataAdapter.getFilter().filter(s.toString());
    }
});

dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
    public Cursor runQuery(CharSequence constraint) {
        return mDbHelper.fetchProjectByName3(constraint.toString());
    }
});



tts = new TextToSpeech(this, this);
final ListView lv = getListView();
txtText = (TextView) findViewById(R.id.text1);
lv.setTextFilterEnabled(true);  
   }

@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
    tts.stop();
    tts.shutdown();
}
super.onDestroy();
 }

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

    int result = tts.setLanguage(Locale.US);

    if (result == TextToSpeech.LANG_MISSING_DATA
            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
        Log.e("TTS", "This Language is not supported");
    } else {
        //btnaudioprayer.setEnabled(true);
        speakOut();
    }

} else {
    Log.e("TTS", "Initilization Failed!");
}
}


private void createProject3() {
Intent i = new Intent(this, AddyourexpActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);  
}



 public void  playSong(String expfilename){
  // Play song
     try
     {          
      mp.reset();
      mp.setDataSource(expfilename);
      mp.prepare();
      mp.start();        

      // Changing Button Image to pause image
      //btnpause.setImageResource(R.drawable.pause);


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


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}


private void speakOut() {

    tts.speak(typed, TextToSpeech.QUEUE_FLUSH, null);
}

private static class ViewHolder {
    static TextView textview1;
    static TextView textview2;
     static Button button23;
}


class CustomAdapter extends SimpleCursorAdapter implements CompoundButton.OnCheckedChangeListener {

    private LayoutInflater mInflater;
    private ListView lv;




    @SuppressWarnings("deprecation")
    public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
             {
        super(context, layout, c, from, to);
        mInflater= LayoutInflater.from(context);
        mCheckStates = new SparseBooleanArray(c.getCount());



        // TODO Auto-generated constructor stub
    }


     @Override
        public void bindView( View view, Context context, final Cursor cursor){
            int row_id = cursor.getColumnIndex("_id");  //Your row id (might need to replace)
            TextView tv = (TextView) view.findViewById(R.id.text2);
            final TextView tv1 = (TextView) view.findViewById(R.id.text1);
            TextView tv2 = (TextView) view.findViewById(R.id.date);
            CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);

            int col1 = cursor.getColumnIndex("expname");
            final String expname = cursor.getString(col1 );
            int col2 = cursor.getColumnIndex("expcontent");
            final String expcontent = cursor.getString(col2 );
            int col3 = cursor.getColumnIndex("expdate");

            final String expdate = cursor.getString(col3);
            int col4 = cursor.getColumnIndex("expfilename");
            final String expfilename = cursor.getString(col4);
            cb.setTag(cursor.getPosition());
            cb.setChecked(mCheckStates.get(cursor.getPosition(), false));
            cb.setOnCheckedChangeListener(this);
          //  TextView tv2 = (TextView) view.findViewById(R.id.text3);
            //cursor.getColumnName(1)
            tv.setText( expname);
            tv1.setText( expcontent);
           tv2.setText(expdate);
            //tv2.setText( ""+cursor.getColumnIndex(GinfyDbAdapter.CATEGORY_COLUMN_COUNT));
         //   String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT}
            ImageButton button = (ImageButton) view.findViewById(R.id.sms);
            button.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v){
                    StringBuffer sb2 = new StringBuffer();
                sb2.append("Title:");
                    sb2.append(Html.fromHtml(expname));
                    sb2.append(",Content:");
                    sb2.append(Html.fromHtml(expcontent));
                    sb2.append("\n");
                    String strContactList1 = (sb2.toString().trim());
                    sendsmsdata(strContactList1);
                }
            });

            ImageButton button1 = (ImageButton) view.findViewById(R.id.mail);
            button1.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v){
                    StringBuffer sb3 = new StringBuffer();
                sb3.append("Title:");
                    sb3.append(Html.fromHtml(expname));
                    sb3.append(",Content:");
                    sb3.append(Html.fromHtml(expcontent));
                    sb3.append("\n");
                    String strContactList2 = (sb3.toString().trim());
                    sendmaildata(strContactList2);
                }
            });

            ImageButton button2 = (ImageButton) view.findViewById(R.id.btnaudioprayer);
            button2.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v){
                    //ADD STUFF HERE you know which row is clicked. and which button
                    typed = expcontent;
                    speakOut();
                }
            });

         ImageButton play = (ImageButton) view.findViewById(R.id.eplay);

             play.setOnClickListener(new OnClickListener(){
                  @Override
                   public void onClick(View v) 
                   {
                      song(); 

                   }
                });

            ImageButton button3 = (ImageButton) view.findViewById(R.id.bBlame);
            button3.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v){
                    //Toast.makeText(ExperiencesActivity.this, expname, Toast.LENGTH_SHORT).show();
                    //dialog.show();
                    showMyDialog();

                }


                    public void showMyDialog(){

                        dialog=new Dialog(ExperiencesActivity.this);
                        ViewHolder viewholder;
                                        dialog.setContentView(R.layout.exp1);
                                        dialog.setCancelable(true);
                                        dialog.setTitle("My Experiences");

                                        ViewHolder.textview1 = (TextView)dialog.findViewById(R.id.tv11);
                                        ViewHolder.textview1.setText("Title:" + expname);
                                        ViewHolder.textview2 = (TextView)dialog.findViewById(R.id.tv22);
                                        ViewHolder.textview2.setText("Content:" + expcontent);
                                        ViewHolder.button23=(Button)dialog.findViewById(R.id.btnSubmit);
                                       ViewHolder.button23.setOnClickListener(new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                                dialog.dismiss();

                                            }
                                        });
                         dialog.show();
                        }




            });

        /*    dialog=new Dialog(ExperiencesActivity.this);
            dialog.setContentView(R.layout.exp1);
            dialog.setCancelable(true);
            dialog.setTitle("My Experiences");

            textview1 = (TextView)dialog.findViewById(R.id.tv11);
            textview1.setText("Title:" + expname);
            textview2 = (TextView)dialog.findViewById(R.id.tv22);
            textview2.setText("Content:" + expcontent);
            Button button23=(Button)dialog.findViewById(R.id.btnSubmit);
            button23.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    dialog.dismiss();

                }
            });*/




        }


     public void song(){
         // check for already playing
         mp = new MediaPlayer();
         if(mp!=null){
             Log.d("Testing","checking mp status.");
              if(mp.isPlaying()){
                  Log.d("Testing","pausing song.");
                 mp.pause();
                 // Changing button image to play button
                 play.setImageResource(R.drawable.ep1);
              }

         }else{
             // Resume song
             Log.d("Testing","playing song.");
                 mp.start();
                 // Changing button image to pause button
                 play.setImageResource(R.drawable.epause);
                 // play selected song
                 Cursor filename = mDbHelper.fetchProject3FileName(mRowId);
                 startManagingCursor(filename);

                expfilename =filename.getString(filename.getColumnIndexOrThrow(GinfyDbAdapter.CATEGORY_COLUMN_EXPFILENAME));
                    playSong(expfilename);  
             }






     }



        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent){
            LayoutInflater inflater = LayoutInflater.from(context);
            View v = inflater.inflate(R.layout.activity_row3, parent, false);

            bindView(v,context,cursor);
            return v;
        }

Solution

  • You need to get the path form the data base parse it to uri and use the mediaplayer to play.

    Make the following changes

    ImageButton play = (ImageButton) view.findViewById(R.id.eplay);
    play.setTag(cursor.getPosition());
    play.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) 
    {
        int pos = (Integer) v.getTag();
        song(pos+1); 
    
    }
    });
    

    song method

    public void song(int pos){
                 try
                 {
                 if(mp==null)
                 {
                 mp = new MediaPlayer();
                 }
                 mp.reset();
                 Cursor filename = mDbHelper.fetchProject3FileName(pos);
                 expfilename =filename.getString(filename.getColumnIndexOrThrow(GinfyDbAdapter.CATEGORY_COLUMN_EXPFILENAME)); 
                 mp.setDataSource(ExperiencesActivity.this, Uri.parse(expfilename));
                 Toast.makeText(getApplicationContext(),expfilename, 1000).show();
                 mp.prepare();
                 mp.start();     
                 }catch(Exception e)
                 {
                     e.printStackTrace();
                 }               
             }