this is my java code
whenever i run the code, no error is shown, only the seekbar and buttons are displayed when run not the list view with any items. i am running the code on my phone not emulator. please help
public class songs extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private ListView list = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekbar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
#Override
public void run() {
updatePosition();
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
prevButton = (ImageButton) findViewById(R.id.prev);
nextButton = (ImageButton) findViewById(R.id.next);
list = (ListView) findViewById(android.R.id.list);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String[] selectionArgsMp3 = new String[]{mimeType};
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selectionMimeType, selectionArgsMp3, sortOrder);
if (null != cursor && cursor.moveToFirst()) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
}
cursor.close();
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected:", file);
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c, new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durataionInMin = ((double) durationInMs / 1000.0) / 60.0;
durataionInMin = new BigDecimal(Double.toString(durataionInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durataionInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekbar = false;
}
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekbar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekbar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
}
}
};
#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, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Toast.makeText(getApplicationContext(), "Playing All Songs", Toast.LENGTH_LONG).show();
return true;
case R.id.two:
Toast.makeText(getApplicationContext(), "Rename The Song", Toast.LENGTH_LONG).show();
return true;
case R.id.three:
Toast.makeText(getApplicationContext(), "Adding Ringtone", Toast.LENGTH_LONG).show();
return true;
case R.id.four:
Toast.makeText(getApplicationContext(), "Choose Playlist", Toast.LENGTH_LONG).show();
return true;
case R.id.five:
Toast.makeText(getApplicationContext(), "Song deleted", Toast.LENGTH_LONG).show();
return true;
case R.id.six:
Toast.makeText(getApplicationContext(), "Songs Deleted", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is my song.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.0" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/selectedfile"
android:ellipsize="middle"
android:gravity="center_horizontal"
android:singleLine="true"
android:text="No file selcted"
android:textColor="#android:color/black"
/>
<SeekBar
android:id="#+id/seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:padding="10dip"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prev"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/play"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
this is my listenitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/displayname"
android:ellipsize="end"
android:singleLine="true"
android:textSize="18dip"
android:textStyle="bold"
android:layout_weight="0.75" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="303dp"
android:layout_height="104dp"
android:id="#+id/title"
android:ellipsize="end"
android:singleLine="true"
android:textSize="15dip"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/duration"
android:ellipsize="end"
android:singleLine="true"
android:textSize="15dip"
/>
</LinearLayout>
</LinearLayout>
I tried your code and it works for me. Only thing is, that the list appears in the upper right corner of the screen:
Related
I have set onclick event on a button(Submit). If the radio buttons of a radio group is not selected then I try to Toast message and focus/listview scroll the first unchecked radio group with error image beside or text(please select answer) as well as show error beside all unchecked radiogroup. I was able to achieve Toast message but not able to achieve focus and error beside on radiogroup which is unchecked.
**CustomAdapter**
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
resetAnswers();
inflter = (LayoutInflater.from(applicationContext));
}
public void resetAnswers(){
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
}
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return questionsList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (convertView == null) {
if (inflter != null) {
view = inflter.inflate(R.layout.list_items, null);
}
}
TextView question = (TextView) view.findViewById(R.id.question);
question.setText(questionsList[i]);
final RadioGroup rg = (RadioGroup)view.findViewById(R.id.radio_group);
final RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
final RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
if(selectedAnswers.get(i).equals("1")){
rg.check(R.id.yes);
}else if(selectedAnswers.get(i).equals("2")){
rg.check(R.id.no);
}else{
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
switch (checkedId){
case R.id.yes:
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.BLACK);
selectedAnswers.set(i, "1");
break;
case R.id.no:
rb_yes.setBackgroundColor(Color.BLACK);
rb_no.setBackgroundColor(Color.rgb(255,165,0));
selectedAnswers.set(i, "2");
break;
}
if (checkedId !=-1){
Log.d("USB", "oniew "+checkedId);
rg.clearCheck();
}
else
{
Log.d("USB", "towie "+checkedId);
}
}
});
if (rb_yes.isChecked()||rb_no.isChecked()){
Log.d("USB", "checked");
}
else
{
Log.d("USB", "null ");
}
Log.d("USB", "I value "+i);
return view;
}
public List<String> getSelectedAnswers(){
return selectedAnswers;
}
**Main Activity**
public class MainActivity extends AppCompatActivity {
private ListView simpleListView;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit, clear;
private RadioGroup radioGroup;
FileOutputStream fstream;
private boolean forceClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
questions = getResources().getStringArray(R.array.questions);
simpleListView = (ListView) findViewById(R.id.simpleListView);
View Listview = getLayoutInflater().inflate(R.layout.list_items,null);
RadioButton rb_yes = Listview.findViewById(R.id.yes);
RadioButton rb_no = Listview.findViewById(R.id.no);
final RadioGroup radioGroup= Listview.findViewById(R.id.radio_group);
View footerView = getLayoutInflater().inflate(R.layout.footer,null);
clear= (Button) footerView.findViewById(R.id.clear);
submit = (Button) footerView.findViewById(R.id.submit1);
simpleListView.addFooterView(footerView);
View headerView = getLayoutInflater().inflate(R.layout.header, null);
simpleListView.addHeaderView(headerView);
customAdapter = new CustomAdapter(getApplicationContext(),questions);
simpleListView.setAdapter(customAdapter);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customAdapter.resetAnswers();
customAdapter.notifyDataSetChanged();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {LayoutInflater inflater=getLayoutInflater();
View customToastroot=inflater.inflate(R.layout.mycustom_toast, null);
String message = "";
boolean found_unanswered = false;
if(customAdapter != null){
for(int i = 0 ;i<customAdapter.getSelectedAnswers().size() ; i++){ if(customAdapter.getSelectedAnswers().get(i).equals("3")){
String p = customAdapter.getSelectedAnswers().get(i);
Log.d("USB", "ID check main "+customAdapter.getSelectedAnswers().get(i));
radioGroup.requestFocus();
radioGroup.requestFocusFromTouch();
Context context=getApplicationContext();
Toast customtoast= new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,0, 0);
customtoast.setDuration(Toast.LENGTH_LONG);
customtoast.show();
found_unanswered = true;
break;
}
message = message + "\n" + (i + 1) + " " + customAdapter.getSelectedAnswers().get(i);
}
}
if(!found_unanswered){
try {
fstream = openFileOutput("user_answer", Context.MODE_PRIVATE);
fstream.write(message.getBytes());
fstream.close();
Toast.makeText(getApplicationContext() ,message , Toast.LENGTH_LONG).show();
Intent inent = new Intent(view.getContext(), DetailsActivity.class);
startActivity(inent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
#SuppressLint("RestrictedApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
if(menu instanceof MenuBuilder){
MenuBuilder m = (MenuBuilder) menu;
m.setOptionalIconsVisible(true);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.about) {
Intent inent = new Intent(MainActivity.this, devicedetailsActivity.class);
startActivity(inent);
return true;
}
if (id == R.id.admin) {
Intent inent = new Intent(MainActivity.this, adminactivity.class);
startActivity(inent);
return true;
}
if (id == R.id.SerialPort) {
Intent inent = new Intent(MainActivity.this, DeviceListActivity.class);
startActivity(inent);
return true;
}
if (id == R.id.customservice) {
Intent inent = new Intent(MainActivity.this, testactivity_main.class);
startActivity(inent);
return true;
}
if (id == R.id.exit) {
ActivityCompat.finishAffinity(MainActivity.this);
return true;
}
return super.onOptionsItemSelected(item);
}
Thanks
Try the following:
1) MainActivity_.class:-----------------
public class MainActivity_ extends AppCompatActivity {
private ListView lv;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit;
private Button clear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout8);
questions = new String[10];
for(int i = 0 ; i<10 ; i++){
questions[i] = "Q " + i;
}
lv = (ListView) findViewById(R.id.lv);
customAdapter = new CustomAdapter(getApplicationContext() , questions);
lv.setAdapter(customAdapter);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean found_unanswered = false;
int index_first_unanswered = 0;
List<Integer> backgroundColor = new ArrayList<Integer>(); // new
if(customAdapter != null){
for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
if(customAdapter.getSelectedAnswers().get(i).equals("3")){
if(!found_unanswered) { // new
found_unanswered = true;
index_first_unanswered = i; // new
}
backgroundColor.add(Color.RED); // new
}else{ // new
backgroundColor.add(Color.WHITE);
}
}
}
if(!found_unanswered) {
Toast.makeText(getApplicationContext(), "All Answered", Toast.LENGTH_LONG).show();
customAdapter.setBackgroundColor(backgroundColor); // new
//Go to other activity
}else{ // new
Toast.makeText(getApplicationContext(), "Found Unanswered", Toast.LENGTH_LONG).show();
if(customAdapter != null && lv != null){
customAdapter.setBackgroundColor(backgroundColor);
lv.smoothScrollToPosition(index_first_unanswered);
}
}
}
});
clear = (Button) findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (customAdapter != null) {
customAdapter.clearSelectedAnswers();
}
}
});
}
}
2) CustomAdapter.class:----------------
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
private List<String> selectedAnswers;
private List<Integer> backgroundColor; // new
public CustomAdapter(Context context, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<String>();
backgroundColor = new ArrayList<Integer>(); // new
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
backgroundColor.add(Color.WHITE); // new
}
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return questionsList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (convertView == null) {
if (inflter != null) {
view = inflter.inflate(R.layout.list_items, null);
}
}
TextView question = (TextView) view.findViewById(R.id.question);
question.setText(questionsList[i]);
question.setBackgroundColor(backgroundColor.get(i)); // new
// initialize/re-restore UI Radio Button State
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
if(selectedAnswers.get(i).equals("1")){
rg.check(R.id.yes);
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
}else if(selectedAnswers.get(i).equals("2")){
rg.check(R.id.no);
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
}else {
// no answer.
rg.clearCheck(); // new
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
//Toast.makeText(context , (checkedId == R.id.yes)?"yes":"no" , Toast.LENGTH_LONG).show();
switch (checkedId){
case R.id.yes:
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
selectedAnswers.set(i, "1");
break;
case R.id.no:
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
selectedAnswers.set(i, "2");
break;
default: // new
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
selectedAnswers.set(i, "3");
break;
}
}
});
return view;
}
public List<String> getSelectedAnswers(){
return selectedAnswers;
}
public void clearSelectedAnswers(){
selectedAnswers = new ArrayList<String>();
backgroundColor = new ArrayList<Integer>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
backgroundColor.add(Color.WHITE); // new
}
this.notifyDataSetChanged();
}
public void setBackgroundColor(List<Integer> backgroundColor_){ // new
this.backgroundColor = backgroundColor_;
this.notifyDataSetChanged();
}
}
3) layout_8.xml:---------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="90"
android:id="#+id/lv">
</ListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_weight="10"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Submit"
android:layout_toStartOf="#id/v"
android:textAllCaps="false"
android:id="#+id/submit"/>
<View
android:layout_width="1dp"
android:layout_height="0dp"
android:id="#+id/v"
android:layout_centerInParent="true">
</View>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Clear"
android:layout_toEndOf="#id/v"
android:textAllCaps="false"
android:id="#+id/clear"/>
</RelativeLayout>
</LinearLayout>
4) list_items.xml:--------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout 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"
tools:context=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
</LinearLayout>
I am developing an app with audio player.I want to add next song play button and previous song play button. Following is my code which is working but in this code i want to add next track play and previous track play button.Help me!!
//MainActivity.java
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private TextView selectedfile = null;
private SeekBar seekBar = null;
private MediaPlayer player = null;
private ImageButton prev = null;
private ImageButton play = null;
private ImageButton next = null;
private MediaCursorAdapter adapter = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositinRunnable = new Runnable() {
#Override
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedfile = (TextView) findViewById(R.id.selecteditem);
seekBar = (SeekBar) findViewById(R.id.seekBar);
prev = (ImageButton) findViewById(R.id.previous);
play = (ImageButton) findViewById(R.id.play);
next = (ImageButton) findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekBar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.
INTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
adapter = new MediaCursorAdapter(this, R.layout.item, cursor);
setListAdapter(adapter);
prev.setOnClickListener(OnButtonClick);
play.setOnClickListener(OnButtonClick);
next.setOnClickListener(OnButtonClick);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
currentFile = (String) v.getTag();
startPlay(currentFile);
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selectedfile.setText(file);
seekBar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekBar.setMax(player.getDuration());
play.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
play.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositinRunnable);
seekBar.setProgress(0);
isStarted = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositinRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void updatePosition() {
handler.removeCallbacks(updatePositinRunnable);
seekBar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositinRunnable, UPDATE_FREQUENCY);
}
private View.OnClickListener OnButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositinRunnable);
player.pause();
play.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
play.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.previous: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
;
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged =
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "OnProgressChanged");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
};
}
//MediaCursorAdapter.java
public class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c, new String[]{MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.TITLE,MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(cursor.getColumnIndex(
MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(cursor.getColumnIndex(
MediaStore.MediaColumns.TITLE)));
long durationInMS = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) durationInMS / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).
setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.item, parent, false);
bindView(v, context, cursor);
return v;
}
}
In MainActivity class:
public class MainActivity extends ActionBarActivity {
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
private ListView lvMainChat;
private EditText etMain;
private Button btnSend;
private String connectedDeviceName = null;
private List<Message1> listMessages;
private MessagesListAdapter chatArrayAdapter;
private StringBuffer outStringBuffer;
private BluetoothAdapter bluetoothAdapter = null;
private ChatService chatService = null;
private EditText result;
final Context context = this;
private Handler handler = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to,
connectedDeviceName));
chatArrayAdapter.isEmpty();
break;
case ChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case ChatService.STATE_LISTEN:
case ChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writemessage = new String(writeBuf);
boolean isSelf1 = true;
Message1 m1 = new Message1(writemessage, isSelf1);
// Appending the message to chat list
appendMessage(m1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
boolean isSelf = false;
Message1 m = new Message1(readMessage, isSelf);
// Appending the message to chat list
appendMessage(m);
break;
case MESSAGE_DEVICE_NAME:
connectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"Connected to " + connectedDeviceName,
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
.show();
break;
}
return false;
}
});
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
getWidgetReferences();
bindEventHandler();
Button Enskripsi = (Button) this.findViewById(R.id.btnEnskripsi);
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
return;
}
result = (EditText) findViewById(R.id.etMain);
Enskripsi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.enskripsi, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText ciperteks = (EditText) promptsView
.findViewById(R.id.cipertext);
final EditText plainteks = (EditText) promptsView
.findViewById(R.id.plaintext);
final EditText key1 = (EditText) promptsView
.findViewById(R.id.key1);
final Button enskripsi = (Button) promptsView
.findViewById(R.id.btEnskripsi1);
// set dialog message
alertDialogBuilder
.setTitle("Enskripsi Pesan")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
String plaintext = plainteks.getText().toString().trim();
String key=key1.getText().toString().trim();
String ciper=ciperteks.getText().toString().trim();
result.setText(ciperteks.getText());
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
enskripsi.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String plaintext = plainteks.getText().toString().trim();
String key=key1.getText().toString().trim();
String enKata = "";
if (plaintext.isEmpty()|| key.isEmpty()) {
Toast.makeText(getBaseContext(), "Silahkan Isi Textbox Yang Kosong", 1).show();
} else {
try {
enKata = CopyOfZIgZagCode1.RFEncryptionWork(key, plaintext);
} catch (Exception e) {}
ciperteks.setText(enKata);
}
}
});
}
});
}
private void getWidgetReferences() {
lvMainChat = (ListView) findViewById(R.id.lvMainChat);
etMain = (EditText) findViewById(R.id.etMain);
btnSend = (Button) findViewById(R.id.btnSend);
}
private void bindEventHandler() {
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String message = etMain.getText().toString();
sendMessage(message);
}
});
}
private void appendMessage(final Message1 m) {
runOnUiThread(new Runnable() {
#Override
public void run() {
listMessages.add(m);
chatArrayAdapter.notifyDataSetChanged();
// Playing device's notification
playBeep();
}
});
}
public void playBeep() {
try {
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
String address = data.getExtras().getString(
DeviceListActivity.DEVICE_ADDRESS);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
chatService.connect(device, secure);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan:
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent,
REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
}
return false;
}
private void ensureDiscoverable() {
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private void sendMessage(String message) {
if (message.length() > 0) {
byte[] send = message.getBytes();
chatService.write(send);
outStringBuffer.setLength(0);
etMain.setText(outStringBuffer);
}
}
private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
private final void setStatus(int resId) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle(resId);
}
private final void setStatus(CharSequence subTitle) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle(subTitle);
}
private void setupChat() {
listMessages = new ArrayList<Message1>();
chatArrayAdapter = new MessagesListAdapter(this, listMessages);
lvMainChat.setAdapter(chatArrayAdapter);
lvMainChat.setTextFilterEnabled(true);
lvMainChat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
chatService = new ChatService(this, handler);
outStringBuffer = new StringBuffer("");
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (chatService == null)
setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if (chatService != null) {
if (chatService.getState() == ChatService.STATE_NONE) {
chatService.start();
}
}
}
}
Source Code In AdapterList
public class MessagesListAdapter extends BaseAdapter {
private Context context;
private List<Message1> messagesItems = new ArrayList<Message1>();
public MessagesListAdapter(Context context, List<Message1> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
/**
* The following list not implemented reusable list items as list items
* are showing incorrect data Add the solution if you have one
* */
Message1 m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View rowView = mInflater.inflate(R.layout.main, parent, false);
// Identifying the message owner
if (m.isSelf()) {
// message belongs to you, so load the right aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_right1,
null);
} else {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_left1,
null);
}
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
ListView lvMainChat = (ListView) convertView.findViewById(R.id.lvMainChat);
txtMsg.setText(m.getMessage());
return convertView;
}
}
in list_item_message_left1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingLeft="10dp">
<TextView
android:id="#+id/lblMsgFrom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12dp"
android:textColor="#color/lblFromName"
android:textStyle="italic"
android:padding="5dp"/>
<TextView
android:id="#+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_marginRight="80dp"
android:textColor="#color/title_gray"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:background="#drawable/bg_msg_from"/>
</LinearLayout>
list_item_message_right1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingRight="10dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/lblMsgFrom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textColor="#color/lblFromName"
android:textSize="12dp"
android:textStyle="italic" />
<TextView
android:id="#+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:background="#drawable/bg_msg_you"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:textColor="#color/white"
android:textSize="16dp" />
</LinearLayout>
I guess you have an error here:
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
Do not cast your list items as (TextView) as they are not (you defined them as LinearLayout in your XML).
Get desired strings from your adapter or use subviews of list items views.
Try i.e.
Toast.makeText(getApplicationContext(), ((TextView) view.findViewbyId(R.id.txtMsg)).getText(), Toast.LENGTH_SHORT).show();
I am using videoView to play video but I am getting fatal signal 6 error so I got solution that use textureview instead of videoview but I have no idea how to use it .
This is my code.
public class MainActivity extends Activity {
ListView listview;
CustomListAdapter adapter;
private static ProgressDialog progressDialog;
public static int currentItem;
public static ArrayList<String> videoLIst;
public static MediaController mediaController ;
boolean pauseOnScroll = true;
boolean pauseOnFling = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
System.gc();
videoLIst = new ArrayList<String>();
mediaController = new MediaController(MainActivity.this);
videoLIst.add("http://journey.coderspreview.com/uploads/Home_Video/mov_bbb.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/165/video/father-and-young-daughter.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/185/video/couple-on-sail-boat.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/39/video/VID-20141231-WA0006.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/26/video/VID-20141216-WA0004.mp4");
listview = (ListView) findViewById(R.id.list);
listview.setAdapter(new CustomListAdapter(this, videoLIst));
listview.setRecyclerListener(new RecyclerListener() {
#Override
public void onMovedToScrapHeap(View view) {
VideoView videoView = (VideoView)view.findViewById(R.id.VideoView);
}
});
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
private int mFirstVisibleRow = -1;
private int mActiveItem = -1;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int firstVisibleRow = listview.getFirstVisiblePosition();
if( mFirstVisibleRow != firstVisibleRow )
{
mFirstVisibleRow = firstVisibleRow;
// Cancel the video of the previous active item
VideoView prevActiveVideoView = getVideoViewForRow(mActiveItem);
if( prevActiveVideoView != null )
{
prevActiveVideoView.pause();
}
// Start the video of the new active item
mActiveItem = mFirstVisibleRow + 1;
VideoView newActiveVideoView = getVideoViewForRow(mActiveItem);
if(newActiveVideoView != null)
{
newActiveVideoView.start();
}
}
}
private VideoView getVideoViewForRow(int row)
{
int firstVisibleRow = listview.getFirstVisiblePosition();
View rowView = listview.getChildAt(row-firstVisibleRow);
return (rowView == null) ? null : (VideoView)rowView.findViewById(R.id.VideoView);
}
});
}
static class ViewHolderItem {
TextView textViewItem;
VideoView video;
ProgressBar progressbar;
}
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<String> videoList;
public CustomListAdapter(Activity activity, ArrayList<String> videoList) {
this.activity = activity;
this.videoList = videoList;
}
#Override
public int getCount() {
return videoList.size();
}
#Override
public Object getItem(int location) {
return videoList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("NewApi")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolder;
if (convertView == null){
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.video_list_item, null);
viewHolder = new ViewHolderItem();
viewHolder.video = (VideoView)convertView.findViewById(R.id.VideoView);
viewHolder.progressbar = (ProgressBar)convertView.findViewById(R.id.progress);
viewHolder.textViewItem =(TextView)convertView.findViewById(R.id.txvposition);
int pos;
pos=viewHolder.video.getCurrentPosition();
Log.d("current item position:",""+pos);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
viewHolder.textViewItem.setText("Video"+position);
// mediaController.setAnchorView(viewHolder.video);
Log.d("video url inadapter:", ""+videoLIst.toString());
Uri uri = Uri.parse(videoList.get(position));
// viewHolder.video.setMediaController(mediaController);
// viewHolder.video.setVideoURI(uri);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewHolder.video.setVisibility(View.GONE);
viewHolder.video.setVisibility(View.VISIBLE);
viewHolder.video.setVideoURI(Uri.parse(videoList.get(position)));
}
}, 200);
//viewHolder.video.start();
viewHolder.video.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
viewHolder.progressbar.setVisibility(View.GONE);
viewHolder.video.start();
viewHolder.video.setBackgroundResource(0);
}
});
viewHolder.video.setOnInfoListener(new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.d("BUFFRRING START", "On_InFO");
if (MediaPlayer.MEDIA_INFO_BUFFERING_START == what) {
viewHolder.progressbar.setVisibility(View.VISIBLE);
Log.d("BUFFRRING START", "" + what);
}
if (MediaPlayer.MEDIA_INFO_BUFFERING_END == what) {
viewHolder.progressbar.setVisibility(View.GONE);
Log.d("BUFFRRING END", "" + what);
}
if (MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START == what) {
viewHolder.progressbar.setVisibility(View.GONE);
Log.d("RENDERING END", "" + what);
}
return false;
}
});
viewHolder.video.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.d("Error", "------>error" + what + "/" + extra);
if (extra != 0) {
Toast.makeText(MainActivity.this, "Can't Play Video",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
viewHolder.video.clearAnimation();
return convertView;
}
}
}
activity_view.xml
<RelativeLayout 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"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
video_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<VideoView
android:id="#+id/VideoView"
android:layout_width="match_parent"
android:layout_height="100dp" />
<ProgressBar
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
/>
<TextView
android:id="#+id/txvposition"
android:layout_width="match_parent"
android:layout_height="80dp" />
</LinearLayout>
I am facing this two proble.
1)On scroll videos/list items starts buffering again for the item that was already buffered.
2)On fast scroll list gets too laggy and get stuck and crashes.
please give me guidence how I used textureview insted of videoview.
i am new to android development. In my app ive implemented an audio player, it plays soounds from teh sd card. i want it to play and show the list of only those audio files that i provide in a folder the app workspace (like the images we give in drawable)
here is the code. Thank you in advance
Play.java
public class Play extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selelctedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
selelctedFile = (TextView)findViewById(R.id.selectedfile);
seekbar = (SeekBar)findViewById(R.id.seekbar);
playButton = (ImageButton)findViewById(R.id.play);
prevButton = (ImageButton)findViewById(R.id.prev);
nextButton = (ImageButton)findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if(null != cursor)
{
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.list, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selelctedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition(){
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter{
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[] { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[] { R.id.displayname, R.id.title, R.id.duration });
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView)view.findViewById(R.id.title);
TextView name = (TextView)view.findViewById(R.id.displayname);
TextView duration = (TextView)view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double)durationInMs/1000.0)/60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.play:
{
if(player.isPlaying())
{
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
}
else
{
if(isStarted)
{
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
}
else
{
startPlay(currentFile);
}
}
break;
}
case R.id.next:
{
int seekto = player.getCurrentPosition() + STEP_VALUE;
if(seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev:
{
int seekto = player.getCurrentPosition() - STEP_VALUE;
if(seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// returning false will call the OnCompletionListener
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
if(isMoveingSeekBar)
{
player.seekTo(progress);
Log.i("OnSeekBarChangeListener","onProgressChanged");
}
}
};
}
play.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_weight="1.0"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:padding="10dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/selectedfile"
android:text="Not file selected"
android:textColor="#android:color/black"
android:gravity="center_horizontal"
android:singleLine="true"
android:ellipsize="middle"/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekbar"
android:max="100"
android:paddingBottom="10dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#android:drawable/screen_background_light">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prev"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/play"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
You need to put your music to assets directory (ie. create subfolder titled 'sounds') and then list the contents of it by method:
myContext.getAssets().list(”sounds");
Then you have to attach the asset to MediaPlayer object:
mediaPlayer.setDataSource(myContext.getAssets().openFd(soundPathInAssets));
You should also see this thread (because the bit of code I presented to you would play whole directory): Play audio file from the assets directory
EDIT: Code from example project (in case of deleting file on my dropbox):
MainActivity.java
public class MainActivity extends Activity {
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView list = (ListView) findViewById(R.id.listView1);
mMediaPlayer = new MediaPlayer();
Button playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mControl.isPlaying()){
mControl.pause();
} else {
mControl.start();
}
}
});
try {
list.setAdapter(new MyAdapter(getAssets().list("music")));
} catch (IOException e) {
e.printStackTrace();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String path = (String) list.getAdapter().getItem(position);
try {
AssetFileDescriptor fd = getAssets().openFd("music/"+path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class MyAdapter extends BaseAdapter {
private String[] content;
public MyAdapter(String[] content){
this.content=content;
}
#Override
public int getCount() {
return content.length;
}
#Override
public Object getItem(int position) {
return content[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = new TextView(getApplicationContext());
TextView cv = (TextView) convertView;
cv.setTextSize(18);
cv.setPadding(8, 8, 8, 8);
}
TextView v = (TextView) convertView;
v.setText(content[position]);
return v;
}
}
MediaPlayerControl mControl = new MediaPlayerControl() {
public void start() {
mMediaPlayer.start();
}
public void pause() {
mMediaPlayer.pause();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
};
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/play"
android:background="#drawable/btn_transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="PlayPause" />
</LinearLayout>