android video playback - android

I'm new to android.
Can anyone help me how to display images from the Sd Card or play videos from Sd Card..
I tried it many ways but none of it is working..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<VideoView
android:id="#+id/videoView1"
android:layout_width="243dp"
android:layout_height="234dp" />
</LinearLayout>

here is complete reference example about VideoView.
You just need to set path of your video file here.

This is binding all songs from sdcard into listview....
public class VideoListActivity extends ListActivity {
private MediaCursorAdapter mediaAdapter = null;
private String currentFile = "";
VideoView video;
MediaController mediaController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
video = (VideoView) findViewById(R.id.videoView1);
mediaController = new MediaController(this);
mediaController.setAnchorView(video);
video.setMediaController(mediaController);
video.setKeepScreenOn(true);
Cursor cursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null,
null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem,
cursor);
setListAdapter(mediaAdapter);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position,
long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
video.setVideoPath(currentFile);
video.start();
video.requestFocus();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c, new String[] {
MediaStore.Video.VideoColumns.DISPLAY_NAME,
MediaStore.Video.VideoColumns.ARTIST,
MediaStore.Video.VideoColumns.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.Video.VideoColumns.DISPLAY_NAME)));
String str=cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.ARTIST));
if(str.equals("<unknown>"))
title.setText(" ");
else
title.setText(""
+ cursor.getString(cursor
.getColumnIndex(MediaStore.Video.VideoColumns.ARTIST)));
long durationInMs = Long.parseLong(cursor.getString(cursor
.getColumnIndex(MediaStore.Video.VideoColumns.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.Video.VideoColumns.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;
}
}
}
listitem.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="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/displayname"
android:textSize="18dip"
android:textStyle="bold"
android:singleLine="true"
android:ellipsize="end"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textSize="15dip"
android:singleLine="true"
android:ellipsize="end"
android:layout_weight="1.0"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/duration"
android:gravity="right"
android:textSize="15dip"
android:singleLine="true"
android:ellipsize="end"/>
</LinearLayout>
</LinearLayout>

Related

RecyclerView is not displaying (Showing)

there is lot of RecyclerViewin my project mostly i don't why that is same code that i privous used bu that not showing my RecyclerView. i can't find problem what is it. so
anybody can help
thanks in advance
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.activity_artists, container, false);
Artist_reclyerview = v.findViewById(R.id.artist_reclyerview);
artistPojos = new ArrayList<>();
getartist();
artistAdapter = new ArtistAdapter(context, artistPojos);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(context, 2);
Artist_reclyerview.setLayoutManager(mLayoutManager);
Artist_reclyerview.setAdapter(artistAdapter);
return v;
}
public void getartist() {
musicResolver = getActivity().getContentResolver();
musicUri = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;
//content Url Meida(LIke media,ALbum )
String sortOrder = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER + " ASC";
musicCursor = musicResolver.query(musicUri, null, null, null, sortOrder);
if (musicCursor != null && musicCursor.moveToFirst()) {
int media_id = musicCursor.getColumnIndex
(MediaStore.Audio.Media._ID);
int artistid = musicCursor.getColumnIndex(
MediaStore.Audio.Artists._ID);
int artistname = musicCursor.getColumnIndex
(MediaStore.Audio.Artists.ARTIST);
do {
String Media_id = musicCursor.getString(media_id);
String artistId = musicCursor.getString(artistid);
String artistName = musicCursor.getString(artistname);
Log.d("mediaid", "" + Media_id);
Log.d("artistid", "" + artistId);
Log.d("artistname", "" + artistName);
} while (musicCursor.moveToNext());
}
}
that is RecyclerView xml.
<?xml version="1.0" encoding="utf-8"?>
<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"
android:layout_marginTop="10dp"
android:background="#color/viewBg"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/artist_reclyerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:scrollbars="vertical" />
</RelativeLayout>
That is RecyclerView adpater class file
public class ArtistAdapter extends RecyclerView.Adapter<ArtistAdapter.Holder> {
ArrayList<ArtistPojo> artistPojos;
Context context;
LayoutInflater inflater;
View v;
public ArtistAdapter(Context c, ArrayList<ArtistPojo> pojos) {
context = c;
artistPojos = pojos;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflate layout
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.activity_artist_adapter, null);
return new ArtistAdapter.Holder(v);
}
#Override
public int getItemCount() {
return artistPojos.size();
}
#Override
public void onBindViewHolder(Holder holder, int position) {
final ArtistPojo artistPojo = artistPojos.get(position);
holder.artist.setText(artistPojo.getArtist());
holder.artist_img.setImageResource(R.drawable.splash);
}
public static class Holder extends RecyclerView.ViewHolder {
TextView artist;
ImageView artist_img, dot;
CardView Artist;
public Holder(View itemView) {
super(itemView);
//find by id to adpater file
artist = itemView.findViewById(R.id.artist_txttitile);
artist_img = itemView.findViewById(R.id.artist_img);
Artist = itemView.findViewById(R.id.card_view);
dot = itemView.findViewById(R.id.overflow);
}
}
}
And There is RecyclerView xml adpater file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/reclerview_adpater"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="20dp">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="#dimen/card_margin"
android:elevation="3dp"
card_view:cardCornerRadius="#dimen/card_album_radius">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/artist_img"
android:layout_width="match_parent"
android:layout_height="#dimen/album_cover_height"
android:background="?attr/selectableItemBackgroundBorderless"
android:scaleType="fitXY" />
<TextView
android:id="#+id/artist_txttitile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/thumbnail"
android:paddingLeft="#dimen/album_title_padding"
android:paddingRight="#dimen/album_title_padding"
android:paddingTop="#dimen/album_title_padding"
android:textColor="#color/album_title"
android:textSize="#dimen/album_title" />
<TextView
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:paddingBottom="#dimen/songs_count_padding_bottom"
android:paddingLeft="#dimen/album_title_padding"
android:paddingRight="#dimen/album_title_padding"
android:textSize="#dimen/songs_count" />
<ImageView
android:id="#+id/overflow"
android:layout_width="#dimen/ic_album_overflow_width"
android:layout_height="#dimen/ic_album_overflow_height"
android:layout_alignParentRight="true"
android:layout_below="#id/thumbnail"
android:layout_marginTop="#dimen/ic_album_overflow_margin_top"
android:scaleType="centerCrop"
android:src="#drawable/ic_dots" />
</RelativeLayout>
</android.support.v7.widget.CardView>
That is my ArtistPojo class
public class ArtistPojo {
Long Media_Id;
String Artist, ArtistId, Song;
public ArtistPojo(Long media_Id, String artist, String artistId, String song) {
Media_Id = media_Id;
Artist = artist;
ArtistId = artistId;
Song = song;
}
public Long getMedia_Id() {
return Media_Id;
}
public void setMedia_Id(Long media_Id) {
Media_Id = media_Id;
}
public String getArtist() {
return Artist;
}
public void setArtist(String artist) {
Artist = artist;
}
public String getArtistId() {
return ArtistId;
}
public void setArtistId(String artistId) {
ArtistId = artistId;
}
public String getSong() {
return Song;
}
public void setSong(String song) {
Song = song;
}
}
You are not adding any item in artistPojos ArrayList check it
add data in your arraylist like this
do {
String Media_id = musicCursor.getString(media_id);
String artistId = musicCursor.getString(artistid);
String artistName = musicCursor.getString(artistname);
ArtistPojo pojo= new ArtistPojo();
pojo.setData("");// as per your getter and setter method here
artistPojos.add(pojo)
Log.d("mediaid", "" + Media_id);
Log.d("artistid", "" + artistId);
Log.d("artistname", "" + artistName);
} while (musicCursor.moveToNext());
And also change this make your activity_artist_adapter hight android:layout_height="wrap_content"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/reclerview_adpater"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp">

how to call another activity on clicking a listview

Listing all the songs read form external storage. On clicking a song it should go to SecondActivity.java
MainActivity.java
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.example.shubham.hymnattune";
private List peers = new ArrayList();
private MainActivity.MediaCursorAdapter mediaAdapter = null;
private String currentFile = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra(EXTRA_MESSAGE,currentFile);
startActivity(intent);
}
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.TITLE)));
long duratioInMs = Long.parseLong(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) duratioInMs / 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 inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
};
Receive the song selected in MainActivity.java and play it.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
//private MainActivity.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 boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
// private final IntentFilter intentFilter = new IntentFilter();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
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));
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();
playButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
}
Intent intent=getIntent();
currentFile=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
startPlay(currentFile);
}
This is my main layout file. containing a list of songs from external storage.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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"
tools:context="com.example.shubham.hymnattune.MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"/>
</LinearLayout>
This is my xml file of second activity which is used for playing a song.
second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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"
tools:context="com.example.shubham.hymnattune.SecondActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:background="#android:drawable/screen_background_light"
android:id="#+id/linear2"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/selectedfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="middle"
android:gravity="center_horizontal"
android:singleLine="true"
android:text="No File Selected"
android:textColor="#android:color/black" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
try this
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.onItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Intent intent=new Intent(this,SecondActivity.class);
startActivity(intent);
}
});
I have used a code inside my adaptor class to implement on item click.. Check this code
public class LazyAdapter extends BaseAdapter {
private VideoActivity mainactivity;
private String[] result,imageId,title;
private static LayoutInflater inflater=null;
Context context;
public LazyAdapter(VideoActivity mainactivity, String[] videourls, String[] imgurls, String [] explist) {
context = mainactivity;
result = videourls;
imageId=imgurls;
title = explist;
inflater = (LayoutInflater)mainactivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(mainactivity.getApplicationContext());
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.listview, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
Glide.with(context)
.load(imageId[position])
.into(holder.img);
holder.tv.setText(title[position]);
// imageLoader.DisplayImage(result[position], holder.img);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+title[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, VideoActivity2.class);
intent.putExtra("imgid",title[position]);
intent.putExtra("videourl",result[position]);
context.startActivity(intent);
}
});
return rowView;
}
}
In this code I also have added a code to pass data on clicking each item in the list view.. Hope this one helps you

Button inside ListView unable to Receive OnClick? [duplicate]

This question already has answers here:
ListView and Buttons inside ListView
(5 answers)
Closed 8 years ago.
Currently, my listView is sitting inside a fragment. However, the buttons inside my view are not able to receive the on click event whenever I tap on them.
I am not sure what to do.
Here is my code:
public class ViewInvitationsCursorAdapter extends CursorAdapter {
private Activity activity;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;
private Fragment f;
private boolean displayAcceptDeny;
public ViewInvitationsCursorAdapter(Activity activity, Fragment f,
int layout, Cursor c, boolean displayAcceptDeny) {
super(activity, c);
this.layout = layout;
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
this.cr = c;
this.f = f;
this.displayAcceptDeny = displayAcceptDeny;
}
public static class ViewHolder {
public TextView sender;
public TextView sender_email;
public TextView author_role;
public Button deny;
public Button accept;
public Button cancel;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View view = inflater.inflate(layout, parent, false);
holder.sender = (TextView) view.findViewById(R.id.connection_sender);
holder.sender_email = (TextView) view
.findViewById(R.id.connection_sender_email);
holder.author_role = (TextView) view.findViewById(R.id.connection_role);
holder.accept = (Button) view.findViewById(R.id.connection_allow);
holder.deny = (Button) view.findViewById(R.id.connection_deny);
holder.cancel = (Button) view.findViewById(R.id.connection_cancel);
view.setTag(holder);
return view;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// .bindView(view, context, cursor);
final ViewHolder holder = (ViewHolder) view.getTag();
int sender_index = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_SENDER_BY_NAME);
int sender_email_index = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_SENDER_BY_EMAIL);
String senderString = cursor.getString(sender_email_index);
int author_role_name = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_RELATIONTYPE_NAME);
int message_index = cursor
.getColumnIndexOrThrow(FamilyDBHelper.COLUMN_MESSAGE);
holder.sender.setText(cursor.getString(sender_index));
holder.author_role.setText(cursor.getString(author_role_name));
holder.sender_email.setText(cursor.getString(sender_email_index));
holder.cancel.setVisibility(View.VISIBLE);
// setUpCancel(view, cursor);
holder.cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("cancel", "cancel clicked!");
}
});
}
protected void setUpAcceptDeny(View view, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("accept", "accept clicked!");
}
});
holder.deny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("deny", "deny clicked!");
}
});
}
}
Here is the xml for each of the items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/connection_item_row_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp" >
<LinearLayout
android:id="#+id/connection_item_info_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/connection_sender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold"
tools:text="ANDROID: PREFERENCEFRAGMENTCOMPAT" >
</TextView>
<TextView
android:id="#+id/connection_sender_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_sender"
android:textColor="#000000"
android:textSize="14sp"
tools:text="ANDROID: PREFERENCEFRAGMENTCOMPAT" >
</TextView>
<TextView
android:id="#+id/connection_role"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_sender_email"
android:textColor="#000000"
android:textSize="14sp"
>
</TextView>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_item_info_layout"
android:orientation="horizontal"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip" >
<Button
android:id="#+id/connection_allow"
android:layout_width="0.0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="Allow"
android:background="#color/green"
android:textColor="#color/white"
android:visibility="gone" />
<Button
android:id="#+id/connection_deny"
android:layout_width="0.0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:background="#color/red"
android:textColor="#color/white"
android:text="Deny"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/connection_item_info_layout_request"
android:orientation="horizontal"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip" >
<Button
android:id="#+id/connection_cancel"
android:layout_width="0.0dip"
android:background="#color/red"
android:textColor="#color/white"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="Cancel Request"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
Add this line to your list item xml file.
android:descendantFocusability="blocksDescendants"
if you set clicklistener inside newView method like this it should work. I generally user getView() for this method and there has never been a problem..
#Override
public View getView(Context context, View View, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View = inflater.inflate(R.layout.your_layout_file_id, parent,
false);
holder.sender = (TextView) view.findViewById(R.id.connection_sender);
holder.sender_email = (TextView) view
.findViewById(R.id.connection_sender_email);
holder.author_role = (TextView) view.findViewById(R.id.connection_role);
holder.accept = (Button) view.findViewById(R.id.connection_allow);
holder.deny = (Button) view.findViewById(R.id.connection_deny);
holder.cancel = (Button) view.findViewById(R.id.connection_cancel);
view.setTag(holder);
holder.cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("cancel", "cancel clicked!");
}
});
return view;
}

How to get selected item from custom ListView?

I have a custom ListView where each row consists of a number of TextViews inside it. When I click on the ListItem, the OnListItemClick() doesn't get called. So how do you get the selected of a custom list view?
Thanks for your help!
XML for Row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/priorityView"
android:layout_width="20dip"
android:layout_height="match_parent"
android:background="#cccccc"
android:layout_marginTop="2dip"
android:layout_marginBottom="2dip" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="1.0"
>
<TextView
android:id="#+id/dateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="2dip"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:paddingTop="2dip"
android:text="#string/empty"
android:textSize="20dip"
android:textStyle="bold" />
<TextView
android:id="#+id/monthText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dip"
android:text="#string/empty"
android:textSize="10dip" >
</TextView>
</LinearLayout>
<TextView
android:id="#+id/timeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="5dip"
android:text="#string/empty" >
</TextView>
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="5dip"
android:text="#string/empty"
android:textStyle="bold"
android:layout_weight="1.0" >
</TextView>
<CheckBox
android:id="#+id/selectedCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dip" >
</CheckBox>
</LinearLayout>
XML for ListView:
<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" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
Java
public class MainActivity extends ListActivity {
private AppointmentsDB dbHelper;
private Cursor cursor;
private AppointmentsCursorAdapter cursorAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new AppointmentsDB(this);
StringBuilder selectQuery = new StringBuilder();
selectQuery.append("SELECT "+AppointmentsDB.KEY_ID+",");
selectQuery.append(AppointmentsDB.KEY_TITLE + ", ");
selectQuery.append(AppointmentsDB.KEY_DESCRIPTION + ", ");
selectQuery.append(AppointmentsDB.KEY_PRIORITY + ", ");
selectQuery.append(AppointmentsDB.KEY_DATE_TIME + ", ");
selectQuery.append(AppointmentsDB.KEY_DURATION + ", ");
selectQuery.append(AppointmentsDB.KEY_ALARM_TIME + " FROM "
+ AppointmentsDB.DATABASE_TABLE + " ");
selectQuery.append("ORDER BY " + AppointmentsDB.KEY_DATE_TIME + " ASC");
cursor = dbHelper.openReadableDatabase().rawQuery(
selectQuery.toString(), null);
String[] columnNames = new String[] { };
int[] ids = new int[] { };
cursorAdapter = new AppointmentsCursorAdapter(this,
R.layout.row, cursor, columnNames, ids);
this.setListAdapter(cursorAdapter);
}
// This class sets our customised layout for the ListView
class AppointmentsCursorAdapter extends SimpleCursorAdapter {
private int layout;
private int[] colours;
#SuppressWarnings("deprecation")
public AppointmentsCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.layout = layout;
colours = new int[] {
context.getResources().getColor(R.color.light_gray),
context.getResources().getColor(R.color.green),
context.getResources().getColor(R.color.orange),
context.getResources().getColor(R.color.brick_red) };
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layout, parent, false);
TextView titleText = (TextView) view.findViewById(R.id.titleText);
TextView priorityView = (TextView) view
.findViewById(R.id.priorityView);
TextView dateText = (TextView) view.findViewById(R.id.dateText);
TextView monthText = (TextView) view.findViewById(R.id.monthText);
TextView timeText = (TextView) view.findViewById(R.id.timeText);
String title = cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_TITLE));
int priority = 0;
String _priority = cursor.getString(cursor.getColumnIndex(AppointmentsDB.KEY_PRIORITY));
if(_priority != null)
priority = Integer.parseInt(_priority);
long dateTime = Long.parseLong(cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_DATE_TIME)));
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(dateTime);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"dd,MMM,HH:mm aaa");
String[] tokens = timeFormat.format(calendar.getTime()).split(",");
dateText.setText(tokens[0]);
monthText.setText(tokens[1]);
timeText.setText(tokens[2]);
titleText.setText(title);
priorityView.setBackgroundColor(colours[priority]);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
TextView titleText = (TextView) view.findViewById(R.id.titleText);
TextView priorityView = (TextView) view
.findViewById(R.id.priorityView);
TextView dateText = (TextView) view.findViewById(R.id.dateText);
TextView monthText = (TextView) view.findViewById(R.id.monthText);
TextView timeText = (TextView) view.findViewById(R.id.timeText);
String title = cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_TITLE));
int priority =0;
String _priority = cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_PRIORITY));
if(_priority != null)
priority = Integer.parseInt(_priority);
long dateTime = Long.parseLong(cursor.getString(cursor
.getColumnIndex(AppointmentsDB.KEY_DATE_TIME)));
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(dateTime);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"dd,MMM,HH:mm aaa");
String[] tokens = timeFormat.format(calendar.getTime()).split(",");
dateText.setText(tokens[0]);
monthText.setText(tokens[1]);
timeText.setText(tokens[2]);
titleText.setText(title);
priorityView.setBackgroundColor(colours[priority]);
}
}
}
I find the solution.
You have to set the android:focusable attribute to false for each widget inside the custom ListView, including the Layout widgets.
Try usingOnItemClick() instead of OnListItemClick(),
This is the Custom listview created by SimpleCursorAdapter by sending cursor
SimpleCursorAdapter yearadapter =
new SimpleCursorAdapter(this, R.layout.listview, yearcursor, yearfrom, yearto);
setListAdapter(yearadapter);
amount.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Your code when item get clicked
}
});
It should work.
Below code will give you the list view item:
private ListView listView = (ListView) findviewbyid(.........);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
View v = v.getChildAt(arg2);//This will give the listview item
}
});

android list view getItemAtPosition() is returning raw data

i have implemented a list view its working fine but when i click on the list it gives me raw data that getItemAtPosition(position) returns me.
following is the code that i am using
public class FirstTab extends Activity{
private TabHostProvider tabProvider;
private TabView tabView;
private static String[] country1;
private ListView speakerList;
final Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
tabProvider = new TabbarView(this);
tabView = tabProvider.getTabHost("main");
tabView.setCurrentView(R.layout.firsttab);
setContentView(tabView.render(0));
String temp[] = new String[]{"furqan","furqan1","furqan2"};
Weather weather_data[] = new Weather[temp.length];
for(int i = 0;i<temp.length;i++)
{
weather_data[i] = new Weather(R.drawable.ic_launcher, temp[i]);
}
WeatherAdapter adapter = new WeatherAdapter(this,R.layout.listview_item_row, weather_data);
speakerList = (ListView)findViewById(R.id.speakerList);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
speakerList.addHeaderView(header);
speakerList.setAdapter(adapter);
final ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper);
speakerList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> arg0, View arg1, final int arg2,long arg3) {
// TODO Auto-generated method stub
String item = speakerList.getItemAtPosition(arg2).toString();
Log.d("the value is", item);
/*View item = (View) (speakerList.getItemAtPosition(arg2));
String item = arg0.getItemAtPosition(arg2).toString();
Log.d("the value is", item);*/
//Toast.makeText(getApplicationContext(), arg2, 1).show();
}
});
}
}
The above is the main activity.Following is the adapter
public class weatheradapter {
public static class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
}
}
this is the 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="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" android:gravity="center" android:background="#00FFcc">
<ViewFlipper android:id="#+id/viewflipper" android:layout_width="fill_parent" android:layout_height="fill_parent" >
<ListView android:id="#+id/speakerList" android:layout_width="fill_parent" android:layout_height="fill_parent" />
<ListView android:id="#+id/categoryList" android:layout_width="fill_parent" android:layout_height="wrap_content" />
</ViewFlipper>
</LinearLayout>
The following is the layout for the list view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="#+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView android:id="#+id/txtTitle"
android:text="#+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
need help thanks
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Cursor c = (Cursor) parent.getAdapter().getItem(position);
c.getString(c.getColumnIndex("col_name")));
}

Categories

Resources