Convert gdata feed to xml - Youtube Playlist to ANdroid Listview - android

I am following this code to create a custom list view.
It uses an XML file to parse objects and show them in Listview
I was wondering can I use the same example to show Videos Titles and Duration of a Youtube Playlist.
I have gone though Youtube API and GDATA but I can't find out how to get raw xml link which I can use with above example code
Any help guys?

Heres a class I've used in one of my previous projects. This puts the first video as the "main" one, displays the time and title, and then adds all the rest of the videos to a layout.
public class Videos extends Activity {
ImageView mainThumb;
TextView mainTitle;
TextView mainTime;
LinearLayout videos;
ArrayList<String> links;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videos);
new ParseVideoDataTask().execute();
mainThumb = (ImageView) findViewById(R.id.mainThumb);
mainTitle = (TextView) findViewById(R.id.mainTitle);
mainTime = (TextView) findViewById(R.id.mainTime);
videos = (LinearLayout) findViewById(R.id.videos);
}
private class ParseVideoDataTask extends AsyncTask<String, String, String> {
int count = 0;
#Override
protected String doInBackground(String... params) {
URL jsonURL;
URLConnection jc;
links = new ArrayList<String>();
try {
jsonURL = new URL("http://gdata.youtube.com/feeds/api/playlists/" +
YOUR PLAYLIST ID +
"?v=2&alt=jsonc");
jc = jsonURL.openConnection();
InputStream is = jc.getInputStream();
String jsonTxt = IOUtils.toString(is);
JSONObject jj = new JSONObject(jsonTxt);
JSONObject jdata = jj.getJSONObject("data");
JSONArray aitems = jdata.getJSONArray("items");
for (int i=0;i<aitems.length();i++) {
JSONObject item = aitems.getJSONObject(i);
JSONObject video = item.getJSONObject("video");
String title = video.getString("title");
JSONObject player = video.getJSONObject("player");
String link = player.getString("default");
String length = video.getString("duration");
JSONObject thumbnail = video.getJSONObject("thumbnail");
String thumbnailUrl = thumbnail.getString("hqDefault")
String[] deets = new String[4];
deets[0] = title;
deets[1] = thumbnailUrl;
deets[2] = length;
links.add(link);
publishProgress(deets);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(final String... deets) {
count++;
if (count == 1) {
MainActivity.setImageFromUrl(deets[1], mainThumb, Videos.this);
mainTitle.setText(deets[0]);
mainTime.setText(formatLength(deets[2]));
mainThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(1)));
startActivity(i);
}
});
} else {
LayoutInflater layoutInflater = (LayoutInflater)Videos.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View video = layoutInflater.inflate(R.layout.video, null);
ImageView thumb = (ImageView) video.findViewById(R.id.thumb);
TextView title = (TextView) video.findViewById(R.id.title);
TextView time = (TextView) video.findViewById(R.id.time);
MainActivity.setImageFromUrl(deets[1], thumb, Videos.this);
title.setText(deets[0]);
time.setText(formatLength(deets[2]));
video.setPadding(20, 20, 20, 20);
videos.addView(video);
video.setId(count-1);
video.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(v.getId())));
startActivity(i);
}
});
}
}
}
private CharSequence formatLength(String secs) {
int secsIn = Integer.parseInt(secs);
int hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ((minutes < 10 ? "0" : "") + minutes
+ ":" + (seconds< 10 ? "0" : "") + seconds );
}
#Override
public void onDestroy() {
super.onDestroy();
for (int i=0;i<videos.getChildCount();i++) {
View v = videos.getChildAt(i);
if (v instanceof ImageView) {
ImageView iv = (ImageView) v;
((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
}
}
}
}
video.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/thumb"
android:layout_width="240dp"
android:layout_height="180dp"
android:layout_centerHorizontal="true"
android:scaleType="fitStart" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/thumb"
android:layout_below="#+id/thumb"
android:layout_toLeftOf="#+id/time"
android:maxLines="1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/thumb"
android:layout_below="#+id/thumb"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
</RelativeLayout>
videos.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/mainThumb"
android:layout_width="240dp"
android:layout_height="180dp"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/mainTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mainThumb"
android:layout_below="#+id/mainThumb"
android:layout_toLeftOf="#+id/mainTime"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/mainTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/mainThumb"
android:layout_below="#+id/mainThumb"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
</RelativeLayout>
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="none"
android:layout_alignParentBottom="true" >
<LinearLayout
android:id="#+id/videos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal" />
</HorizontalScrollView>
</RelativeLayout>

Related

Playing videos using textureview inside recyclerview with cardview in android

I done video playing inside recyclerview with cardview using sdcard path location. Also check sdcard not available then fetch recorded videos from internal memory. Its perfectly working in Lava iris x8 device, but in Samsung J5 and Samsung Note 2 only odd numbers(1,3,5,7) videos are playing not even(2,4,6,8) videos are playing and getting dialog like "Can't play this video" when scrolling and getting position of even(2,4,6,8) numbers of video. I am not able to know what is the problem? Below is my whole code about display and play video inside recyclerview and cardview in android.
display_video.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/mRelative_background"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="#6FC298">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp">
<RelativeLayout
android:id="#+id/mRelativeClick"
android:layout_width="50dp"
android:layout_height="30dp"
android:gravity="left">
<ImageView
android:id="#+id/mImage_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#mipmap/icon_back"></ImageView>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My Challenge"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="italic" />
<ImageView
android:id="#+id/mImageView_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#mipmap/icon_setting"></ImageView>
</RelativeLayout>
<RelativeLayout
android:id="#+id/mRelative_circular_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="65dp">
<ImageView
android:id="#+id/mImageView_color1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:visibility="invisible"
android:layout_marginLeft="10dp"
android:src="#mipmap/color1"/>
<ImageView
android:id="#+id/mImageView_color2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color1"
android:src="#mipmap/color2"/>
<ImageView
android:id="#+id/mImageView_color3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color2"
android:src="#mipmap/color3"/>
<app.stakes.CircularImageView
android:id="#+id/mcircularImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_centerInParent="true"
android:background="#mipmap/camera_icon" />
<ImageView
android:id="#+id/mImageView_color4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mcircularImage"
android:src="#mipmap/color4"/>
<ImageView
android:id="#+id/mImageView_color5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color4"
android:src="#mipmap/color5"/>
<ImageView
android:id="#+id/mImageView_color6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color5"
android:src="#mipmap/color6"/>
</RelativeLayout>
<TextView
android:id="#+id/mTextViewUsername_VideoList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mRelative_circular_image"
android:layout_centerInParent="true"
android:layout_marginTop="25dp"
android:text="Text"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="italic" />
<ImageView
android:id="#+id/mImageView_color_table"
android:src="#mipmap/color_table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mRelative_circular_image"
android:layout_marginTop="25dp"
android:layout_marginRight="15dp"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/mRelativeTab"
android:layout_below="#+id/mRelative_background"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/mImageViewtab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/list"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/mImageViewtab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/view"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="40dp"
android:layout_marginStart="40dp" />
<ImageView
android:id="#+id/mImageViewtab3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/showbook"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="40dp"
/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#+id/mRelativeTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:scrollbars="vertical" />
</RelativeLayout>
</RelativeLayout>
cardview1.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:background="#FFFFFF"
android:id="#+id/mRelativeMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--<ImageView
android:id="#+id/iconId"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_centerHorizontal="true"/>-->
<app.stakes.CircularImageView
android:id="#+id/circleImageview"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#mipmap/camera_icon" />
<TextView
android:id="#+id/tvVersionName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_toRightOf="#+id/circleImageview"
android:layout_marginLeft="5dp"
android:text="Auther"
android:textColor="#android:color/black"
android:textSize="7sp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_toRightOf="#+id/circleImageview"
android:layout_marginLeft="70dp"
android:textColor="#android:color/black"
android:textSize="10sp" />
<ImageView
android:id="#+id/mImageview_clock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_toLeftOf="#+id/tvSec"
android:src="#mipmap/timing"/>
<TextView
android:id="#+id/tvSec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="35dp"
android:text="Lollipop"
android:textColor="#android:color/black"
android:textSize="5sp" />
<FrameLayout
android:id="#+id/video_frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/circleImageview">
<com.sprylab.android.widget.TextureVideoView
android:id="#+id/mvideoView"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal|center_vertical"
/>
<ImageView
android:id="#+id/mImageview_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:src="#mipmap/play" />
<ImageView
android:id="#+id/mImageView_fav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mImageview_play"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="40dp"
android:layout_marginTop="130dp"
android:src="#mipmap/bookmark_video" />
<ImageView
android:id="#+id/mImageView_share"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#+id/mImageview_play"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="40dp"
android:layout_marginTop="130dp"
android:src="#mipmap/sharevideo" />
<!--</RelativeLayout>-->
</FrameLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Display_Video1.java
public class Display_Video1 extends ActionBarActivity {
public RecyclerView recyclerView;
private ArrayList<FeddProperties> os_versions;
private Adapter mAdapter;
private Adapter fav_video_adapter;
CircularImageView mcircularImage;
static DisplayMetrics dm;
static MediaController media_Controller;
RelativeLayout mRelativeClick;
static boolean isViewWithCatalog;
RelativeLayout mRelative_background;
static File OldFile;
static String[] fileList = null;
static String[] fileListOld = null;
/*static String FILE_PATH = newFile.getAbsolutePath();*/
static String FILEPATH_OLD;
static String videoOldFilePath;
static String replaceOldString;
String MiME_TYPE = "video/mp4";
static String videoFilePath;
static String replaceStr;
static String[] fav_video_list = null;
CallbackManager callbackManager;
public static String facebook_user_id;
public static String username;
Boolean isSDPresent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.display_video);
isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent) {
OldFile = new File(Environment.getExternalStorageDirectory(), "/Stakes_Download");
MEDIA_PATHOLD = new String(OldFile.getAbsolutePath());
FILEPATH_OLD = OldFile.getAbsolutePath();
}
else{
OldFile = new File(this.getFilesDir(), "Stakes_Download");
MEDIA_PATHOLD = new String(OldFile.getAbsolutePath());
FILEPATH_OLD = OldFile.getAbsolutePath();
}
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
os_versions = new ArrayList<FeddProperties>();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileList.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileList), Toast.LENGTH_LONG).show();
}
}
}
if (fileListOld != null) {
for (int i = 0; i < fileListOld.length; i++) {
if (fileListOld[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileListOld.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileListOld), Toast.LENGTH_LONG).show();
}
}
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(Display_Video1.this));
// create an Object for Adapter
if (fileList != null) {
mAdapter = new CardViewDataAdapter(Display_Video1.this, fileList);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
} else {
/*Toast.makeText(getApplicationContext(),"No File Exist",Toast.LENGTH_LONG).show();*/
}
updateSongList();
updateSongListOld();
initContrls();
}
public void updateSongList() {
File videoFiles = new File(MEDIA_PATHOLD);
Log.d("**Value of videoFiles**", videoFiles.toString());
if (videoFiles.isDirectory()) {
fileList = videoFiles.list();
}
if (fileList == null) {
System.out.println("File doesnot exit");
Toast.makeText(this, "There is no file", Toast.LENGTH_SHORT).show();
} else {
System.out.println("fileList****************" + fileList);
for (int i = 0; i < fileList.length; i++) {
Log.e("Video:" + i + " File name", fileList[i]);
}
}
}
public void updateSongListOld() {
File videoFiles = new File(MEDIA_PATHOLD);
Log.d("**Value of videoFiles**", videoFiles.toString());
if (videoFiles.isDirectory()) {
fileListOld = videoFiles.list();
}
if (fileListOld == null) {
System.out.println("File doesnot exit");
Toast.makeText(this, "There is no file", Toast.LENGTH_SHORT).show();
} else {
System.out.println("fileList****************" + fileListOld);
for (int i = 0; i < fileListOld.length; i++) {
Log.e("Video:" + i + " File name", fileListOld[i]);
}
}
}
private void initContrls() {
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
os_versions = new ArrayList<FeddProperties>();
if (fileList != null) {
/*gridView.setAdapter(new ImageAdapter(this, fileList));*/
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileList.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileList), Toast.LENGTH_LONG).show();
/* FeddProperties feed = new FeddProperties();
feed.setTitle(fileList[i]);
*//*feed.setThumbnail(icons[i]);*//*
os_versions.add(feed);*/
}
}
}
if (fileListOld != null) {
/*gridView.setAdapter(new ImageAdapter(this, fileList));*/
for (int i = 0; i < fileListOld.length; i++) {
if (fileListOld[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileListOld.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileListOld), Toast.LENGTH_LONG).show();
/* FeddProperties feed = new FeddProperties();
feed.setTitle(fileList[i]);
*//*feed.setThumbnail(icons[i]);*//*
os_versions.add(feed);*/
}
}
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Grid View
/* recyclerView.setLayoutManager(new GridLayoutManager(this,2,1,false));*/
//StaggeredGridView
/*recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,1));*/
// create an Object for Adapter
if (fileList != null) {
mAdapter = new CardViewDataAdapter(Display_Video1.this, fileList);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
} else {
/*Toast.makeText(getApplicationContext(),"No File Exist",Toast.LENGTH_LONG).show();*/
}
recyclerView.addOnItemTouchListener(new CardViewDataAdapter(Display_Video1.this, new CardViewDataAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
}));
}
Recyclerview Adapter
public static class CardViewDataAdapter extends Adapter<CardViewDataAdapter.ViewHolder> implements OnItemTouchListener {
private ArrayList<FeddProperties> dataSet;
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
private Context context;
private String[] VideoValues;
private int position = 0;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public CardViewDataAdapter(Context context, String[] VideoValues) {
/*dataSet = os_versions;*/
this.context = context;
this.VideoValues = VideoValues;
}
public CardViewDataAdapter(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// create a new view
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view1, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
videoFilePath = FILEPATH_OLD + "/" + fileList[i];
Toast.makeText(context,"Path: "+videoFilePath,Toast.LENGTH_LONG).show();
viewHolder.tvVersionName.setText(fileList[i]);
System.out
.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>> file path>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
+ fileList[i]);
viewHolder.mvideoView.setVideoPath(videoFilePath);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, Uri.parse(videoFilePath));
final String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInMillisec = Long.parseLong(time);
final long duration = timeInMillisec / 1000;
long hours = duration / 3600;
long minutes = (duration - hours * 3600) / 60;
final long seconds = duration - (hours * 3600 + minutes * 60);
viewHolder.tvSec.setText(String.valueOf(seconds) + "s");
viewHolder.mImageview_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.mvideoView!= null) {
if (viewHolder.mvideoView.isPlaying()) {
viewHolder.mvideoView.pause();
viewHolder.mImageview_play.setImageResource(R.mipmap.play);
} else {
viewHolder.mvideoView.start();
viewHolder.mImageview_play.setImageResource(R.mipmap.play_click);
}
}
viewHolder.mvideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
viewHolder.mImageview_play.setImageResource(R.mipmap.play);
}
});
}
});
viewHolder.str = fileList;
}
#Override
public int getItemCount() {
return VideoValues.length;
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
// inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvVersionName;
public TextView tvTitle;
public TextView tvSec;
/*public ImageView iconView;*/
/*public RelativeLayout mvideoView;*/
public TextureVideoView mvideoView;
public ImageView mImageview_play;
public CircularImageView circleImageview;
public ImageView mImageView_fav;
public ImageView mImageView_share;
public FeddProperties feed;
public String[] str;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvVersionName = (TextView) itemLayoutView
.findViewById(R.id.tvVersionName);
/*iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);*/
tvSec = (TextView) itemLayoutView.findViewById(R.id.tvSec);
tvTitle = (TextView) itemLayoutView.findViewById(R.id.tvTitle);
mvideoView = (TextureVideoView) itemLayoutView.findViewById(R.id.mvideoView);
mImageview_play = (ImageView) itemLayoutView.findViewById(R.id.mImageview_play);
}
}
}

Circular imageview dissappears in listview after fling

Im generating a feed full of images (similar to instagram post) using Glide for loading images and user's profile picture. After i get the data from server, i load the Url's of images inside the listitem. Initally All items are being loaded properly.
The issue is that when i fast scroll the listview, user profile picture dissappears and that view doesnt respond to onClick Events. Please explain why this happens and how can i resolve this?
XML layout of each list Item.
<?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:layout_marginBottom="20dp"
android:orientation="vertical" >
<RelativeLayout android:id="#+id/userheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/realdp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/nodp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/realdp"
android:text="handle"
android:layout_marginLeft="3dp"
android:gravity="center_vertical"
android:layout_alignTop="#+id/realdp"
android:layout_alignBottom="#+id/realdp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/uploadtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/handle"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:text="time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RelativeLayout android:id="#+id/rlimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/handle">
<ImageView
android:id="#+id/imgpost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:background="#ffffff"/>
</RelativeLayout>
<RelativeLayout android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rlimg"
android:layout_marginTop="5dp">
<com.sivaram.fishograph.FlipImageView
android:id="#+id/like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_marginLeft="20dp"
android:src="#drawable/hook_unlike"/>
<ImageButton
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_toRightOf="#+id/likesnum"
android:layout_marginLeft="20dp"
android:src="#drawable/comment" />
<ImageButton
android:id="#+id/more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_alignParentRight="true"
android:background="#00000000"
android:src="#drawable/more" />
<TextView
android:id="#+id/likesnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/like"
android:layout_alignTop="#+id/like"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/like"
android:text="likes"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
<TextView
android:id="#+id/comnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/comment"
android:layout_alignTop="#+id/comment"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/comment"
android:gravity="center_vertical"
android:text="comments"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/caption"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/userheader"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text="Caption"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/caption"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Java Code for generating feed:
public class Feed extends Fragment implements OnScrollListener
{
String handle;
ListView lvposts;
Jsparser jp;
int width,height;
int maxMemory;
int currentFirstVisibleItem ;
int currentVisibleItemCount;
PostAdapter pa;
ArrayList<eachpost> posts;
int value = 1;
boolean isLoading = false;
int photoid;
private List<String> myData;
Boolean tapped = false, Loading= false;
SharedPreferences spf;
ArrayList<String> likes;
public Feed()
{
super();
}
Feed(String handle)
{
super();
photoid = 99999999;
this.handle = handle;
}
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
spf = getActivity().getSharedPreferences("prefs",Context.MODE_PRIVATE);
likes = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup vg, Bundle b)
{
View v = inflater.inflate(R.layout.allposts, vg, false);
ActionBar ab = ((ActionBarActivity) getActivity()).getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.RED));
ab.hide();
lvposts = (ListView) v.findViewById(R.id.lvposts);
jp = new Jsparser();
Display d = getActivity().getWindowManager().getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
lvposts.setOnScrollListener(this);
posts = new ArrayList<eachpost>();
pa = new PostAdapter(getActivity(),R.layout.postcontent,posts,inflater);
Loading = true;
lvposts.setAdapter(pa);
new GetData(photoid).execute();
return v;
}
class GetData extends AsyncTask<String,String,String>
{
String msg;
Integer limit,success=0;
ProgressDialog pd;
Bitmap dpbm;
GetData(int l)
{
limit = l;
}
#Override
public void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> lp = new ArrayList<NameValuePair>();
lp.add(new BasicNameValuePair("handle",handle));
lp.add(new BasicNameValuePair("photoid",limit.toString()));
JSONObject job = jp.makeHttpRequest("server/getfeed.php", "POST", lp);
try
{
Log.d("json", job.toString());
success = job.getInt("success");
msg = job.getString("message");
if(success==1)
{
JSONArray ja = job.getJSONArray("posts");
for(int c = 0; c<ja.length(); c++)
{
JSONObject jb = ja.getJSONObject(c);
posts.add(new eachpost(jb.getString("handle"),jb.getString("url"), jb.getString("caption"),
jb.getString("uldatetime"), jb.getInt("likescount"), jb.getInt("comcount"), jb.getString("dpurl"), jb.getInt("isliked"),jb.getInt("photoid") ));
}
}
else
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
#Override
public void onPostExecute(String url)
{
Loading = false;
if(success==1)
{
photoid = posts.get(posts.size()-1).getPhotoid();
Log.d("last id",photoid+"");
Log.d("Length of posts",""+posts.size());
pa.notifyDataSetChanged();
}
}
}
class PostAdapter extends ArrayAdapter<eachpost>
{
ViewHolder vholder;
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File (root + ".feed");
Map<Integer,View> myViews;
public PostAdapter(Context context, int resource, ArrayList<eachpost> list, LayoutInflater li) {
super(context, R.layout.postcontent, list);
myViews = new HashMap<Integer,View>();
}
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
row.setTag(vholder);
myViews.put(pos, row);
}
return row;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
} //end of adapter class
static class ViewHolder {
TextView handle;
TextView caption;
TextView likesnum;
TextView comnum;
TextView uploadtime;
ImageView photo;
CircularImageView feeddp;
FlipImageView like;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.currentVisibleItemCount > 0 && scrollState == SCROLL_STATE_FLING) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(currentFirstVisibleItem > (currentVisibleItemCount - 2) && Loading!=true)
{
new GetData(photoid).execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
}
}
When loading multiple images there is always caching problem when using Async Tasks. I recommend an open source library Picasso. It will load the images and cache it. After that most probably, your fast scroll problem will solve.
The cause can also be the size of the images being received. Picasso has methods by which you can resize the image before putting it onto the image view
try with this modified getView
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
row.setTag(vholder); //changed here setTag()
}else{
vholder=(ViewHolder)row.getTag(); //changed here getTag()
}
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
myViews.put(pos, row);
}
return row;
}

How to loop execution of AsyncTask with an array of params

I'm new in Android programming.
I created classes of web objects each class has 3 RSS URLs to be parsed. I loop an array of this objects to operate on each one the AsyncTask Executer. Every time I do that different errors appear and the UI freezes. I can't find what's wrong. Then I use custom adapter to display the UI but program don't even reach to that code. Please help me finding what's wrong with my code. I tried everything I had in mind.
I loop it in the main thread like this:
public class MainActivity extends Activity
{
ArrayList <WebPage> wpObjects;
ListView lv;
int threadIsFinishedcounter=0;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.listView1);
WebPage ynet= new WebPage(R.drawable.ynet, "http://www.ynet.co.il/Integration/StoryRss2.xml","http://www.ynet.co.il/Integration/StoryRss6.xml","http://www.ynet.co.il/Integration/StoryRss3.xml");
WebPage walla=new WebPage(R.drawable.walla, "http://rss.walla.co.il/?w=/1/0/12/#rss.e","http://rss.walla.co.il/?w=/2/0/12/#rss.e","http://rss.walla.co.il/?w=/3/0/12/#rss.e");
WebPage nrg= new WebPage(R.drawable.nrg, "http://rss.nrg.co.il/news/","http://rss.nrg.co.il/finance","http://rss.nrg.co.il/sport");
wpObjects=new ArrayList<WebPage>();
wpObjects.add(ynet);
wpObjects.add(walla);
wpObjects.add(nrg);
for(WebPage item:wpObjects)
{
//new getParseData(wpObjects.indexOf(item)).execute(item.getUrls());
new getParseData(wpObjects.indexOf(item)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, item.getUrls());
}
if(threadIsFinishedcounter==wpObjects.size())
{
MyCostumedAdapter adapter=new MyCostumedAdapter(MainActivity.this, wpObjects);
lv.setAdapter(adapter);
if(threadIsFinishedcounter==wpObjects.size())
}
}
The AsyncTask class:
class getParseData extends AsyncTask<String,Void, Collecter>
{
int indexofwp;
public getParseData(int indexofwp) {
super();
this.indexofwp = indexofwp;
}
protected Collecter doInBackground(String... params) {
Collecter col = new Collecter() ;
ArrayList<String> allResult = new ArrayList<String>();
ArrayList<String> Titles = new ArrayList<String>();
for (int y = 0; y < params.length; y++) {
Titles.clear();
allResult.clear();
col.yIndex = y;
String urlString = params[y];
try {
URL url = new URL(urlString);
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
XmlPullParser parser = factory.newPullParser();
InputStream is = url.openStream();
parser.setInput(is, null);
boolean inItemTag = false;
boolean inTitleTag = false;
String TagName;
int EventType = parser.getEventType();
while (EventType != XmlPullParser.END_DOCUMENT) {
Log.i("im in while loop of parser", "");
if (EventType == XmlPullParser.START_TAG) {
TagName = parser.getName();
if (inItemTag) {
if (TagName.equals("title"))
inTitleTag = true;
} else// !item
{
if (TagName.equals("item"))
inItemTag = true;
}
}
if (EventType == XmlPullParser.TEXT) {
if (inTitleTag) {
Titles.add(parser.getText());// AD THE TITLE
inTitleTag = false;
}
}
if (EventType == XmlPullParser.END_TAG) {
TagName = parser.getName();
if (TagName.equals("item"))
inItemTag = false;
}
EventType = parser.next();
Log.i("im after parser.next", "");
}// end while of parsing loop
} catch (MalformedURLException e) {
e.printStackTrace();
Log.i("EXEPTION******************",
"MalformedURLException*********");
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("EXEPTION******************",
"XmlPullParserException*********");
} catch (IOException s) {
s.printStackTrace();
Log.i("IOException***************************", "");
}
synchronized (col) {
if (col.yIndex == 0) {
col.news.addAll(Titles);
col.rssRsult.add(col.news);
}
if (col.yIndex == 1) {
col.economy.addAll(Titles);
col.economy.size()+"");
col.rssRsult.add(col.economy);
}
if (col.yIndex == 2) {
col.sports.addAll(Titles);
col.sports.size()+"");
col.rssRsult.add(col.sports);
}
}
}// end of y loop
return col;
}
#Override
protected void onPreExecute()
{
if(threadIsFinishedcounter==wpObjects.size())
threadIsFinishedcounter=0;
}
#Override
protected void onPostExecute(Collecter coll)
{
if(indexofwp<wpObjects.size())
{
wpObjects.get(indexofwp).NewsTitles.addAll(coll.rssRsult.get(0));
wpObjects.get(indexofwp).EconomicsTitles.addAll(coll.rssRsult.get(1))
wpObjects.get(indexofwp).SportssTitles.addAll(coll.rssRsult.get(2));
threadIsFinishedcounter++;
}
I thought maybe my custom adapter is wrong but didn't find anything wrong:
public class MyCostumedAdapter extends BaseAdapter
{
Context context;
ArrayList<WebPage> wp;
public MyCostumedAdapter(Context context , ArrayList<WebPage> wp)
{
super();
this.context = context;
this.wp=wp;
}
#Override
public int getCount()
{
return wp.size();
}
#Override
public Object getItem(int position)
{
return wp.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View rowView;
if(convertView==null)
{
LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView= inflater.inflate(R.layout.lvlayout, null);
}
else
{
final WebPage currentwp=wp.get(position);
rowView=convertView;
ImageView imag=(ImageView)rowView.findViewById(R.id.imageView1);
imag.setImageResource(currentwp.getIcon());
Button newsButton=(Button)rowView.findViewById(R.id.AllnewsButton);
newsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent=new Intent(context,NewHeadlines.class);
intent.putExtra("newsbutton",currentwp.getNewsTitles());//to pass information to next activity
context.startActivity(intent);
}
});
Button economicsButton=(Button)rowView.findViewById(R.id.AllEconomicsButton);
economicsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent=new Intent(context,NewHeadlines.class);
intent.putExtra("economicbutton",currentwp.getEconomicsTitles());//to pass information to next activity
context.startActivity(intent);
}
});
Button sportsButton=(Button)rowView.findViewById(R.id.AllSportsButton);
sportsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent=new Intent(context,NewHeadlines.class);
intent.putExtra("sportsbutton",currentwp.getSportssTitles());//to pass information to next activity
context.startActivity(intent);
}
});
TextView firstNewsTitle=(TextView)rowView.findViewById(R.id.firstnewsTitle);
firstNewsTitle.setText(currentwp.getNewsTitles().get(0));
TextView firstEconomicsTitle=(TextView)rowView.findViewById(R.id.firsteconomicsTitle);
firstEconomicsTitle.setText(currentwp.getEconomicsTitles().get(0));
TextView firstSportsTitle=(TextView)rowView.findViewById(R.id.firstSportsTitle);
firstSportsTitle.setText(currentwp.getSportssTitles().get(0));
}
return rowView;
}
}
main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="326dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllnewsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/News" />
<TextView
android:id="#+id/firstnewsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllEconomicsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Economic" />
<TextView
android:id="#+id/firsteconomicsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllSportsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Sports" />
<TextView
android:id="#+id/firstSportsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout >
</LinearLayout >
each ListView row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="326dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllnewsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/News" />
<TextView
android:id="#+id/firstnewsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllEconomicsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Economic" />
<TextView
android:id="#+id/firsteconomicsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
< Button
android:id="#+id/AllSportsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Sports" />
< TextView
android:id="#+id/firstSportsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
You should pass your array inyo the constructor and then operate and handle that there. I am sure that you can send your array into your params, but you should make your Asynktask diferent fr string values, as currently you have. So the easy and best way is :
int indexofwp;
List<String> allResult = new ArrayList<String>()
public getParseData(int indexofwp, List<String> allResult)
{
super();
this.indexofwp = indexofwp;
This.allResult=allResult;
}
And thats all.
Regards.

How to move the position of Progress bar when the image loads in List View

I am loading the images one by one in Listview by running the task in back ground.I am running a progress bar until it loads fully.The position of progress is not changing when the image starts loading.I want the postion of the progressbar also to be changed when the images loads.How to do it? what am i doing wrong?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relaGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include
android:id="#+id/Master"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/activity_master_page" />
<ListView
android:id="#+id/ItemView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/Master" >
</ListView>
<ProgressBar
android:id="#+id/ItemsProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Master"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Added the code for loading image
private class testAynscTask extends AsyncTask {
#Override
protected void onPreExecute() {
TheProgressBarG = (ProgressBar) findViewById(R.id.ItemsProgressBar);
TheProgressBarG.setVisibility(View.VISIBLE);
}
protected Void doInBackground(Void... ParamsP) {
try {
POSManager aPOSManagerL = new POSManager();
ListCriteria aListCriteriaL = new ListCriteria();
ObjectInformation zItemInfoL = new ObjectInformation();
CategoryItemListG = new ObjectList();
//Get CategoryId
String zCategoryIdL = GetCategoryId();
aListCriteriaL.SearchConditionsM.AddSearchConditionWithValue("Item_Category.Id", zCategoryIdL);
Gson gsonBuilderL = new GsonBuilder().serializeNulls().create();
String zListCriteriaL = gsonBuilderL.toJson(aListCriteriaL);
//Get Category Items List
aPOSManagerL.GetCategoryItems(HttpUtil.SessionKeyM,zListCriteriaL);
DisplayMetrics zDisplayMetricsL = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(zDisplayMetricsL);
int nPreviewSizeL = zDisplayMetricsL.widthPixels / 3;
ObjectList zItemListL = HttpUtil.CategoryItemListM;
for (int countL = 0; countL < zItemListL.GetLength(); countL++) {
zItemInfoL = (ObjectInformation) zItemListL.GetObject(countL);
String zItemIdL = (String) zItemInfoL.GetValue("ID");
//Get Item Image
aPOSManagerL.GetCategoryItemImage(HttpUtil.SessionKeyM,zItemIdL, nPreviewSizeL);
zItemInfoL.SetValue("aPictureByteArrayP",HttpUtil.CategoryItemImageBytesM);
CategoryItemListG.Add(zItemInfoL);
publishProgress(countL);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... PositionP) {
ListView TheItemListViewL=(ListView) findViewById(R.id.ItemView);
TheItemListViewL.setAdapter(anImageAdapterG);
super.onProgressUpdate(PositionP);
}
#Override
protected void onPostExecute(Void ResultP) {
super.onPostExecute(ResultP);
TheProgressBarG.setVisibility(View.INVISIBLE);
anImageAdapterG.notifyDataSetChanged();
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return CategoryItemListG.GetLength();
// return mImageIds.length;
}
public Object getItem(int PositionP) {
return PositionP;
}
public long getItemId(int PositionP) {
return PositionP;
}
public View getView(int PositionP, View ConvertViewP, ViewGroup ParentP) {
ObjectInformation zItemInfoL = (ObjectInformation)CategoryItemListG.GetObject(PositionP);
String zItemNameL = (String)zItemInfoL.GetValue("ITEMNAME");
String zItemPriceL = (String)zItemInfoL.GetValue("SalesPrice");
String zItemImageBytesL = (String)zItemInfoL.GetValue("aPictureByteArrayP");
Bitmap ItemImageBitMapL =GetItemImageBitMap(zItemImageBytesL);
RelativeLayout TheRelativelayoutL = new RelativeLayout(getApplicationContext());
ImageView TheItemImageL = new ImageView(mContextL);
TheItemImageL.setImageBitmap(ItemImageBitMapL);
TheItemImageL.setScaleType(ImageView.ScaleType.FIT_XY);
TheItemImageL.setLayoutParams(new ListView.LayoutParams(100,100));
TheItemImageL.setPadding(1, 0, 0, 0);
TheItemImageL.setId(1);
TextView tvItemNameL = new TextView(mContextL);
tvItemNameL.setText(zItemNameL);
tvItemNameL.setGravity(Gravity.CENTER);
tvItemNameL.setTextSize(10);
tvItemNameL.setTextColor(Color.parseColor("#000000"));
tvItemNameL.setPadding(15, 0, 0, 0);
tvItemNameL.setId(2);
TextView tvItemPriceL = new TextView(mContextL);
tvItemPriceL.setText("Rs. "+zItemPriceL);
tvItemPriceL.setGravity(Gravity.CENTER);
tvItemPriceL.setTextSize(10);
tvItemPriceL.setTextColor(Color.parseColor("#A30000"));
tvItemPriceL.setId(3);
tvItemPriceL.setPadding(15, 0, 0, 20);
TheRelativelayoutL.addView(TheItemImageL);
RelativeLayout.LayoutParams zRelativeLayoutParamsL = new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams.WRAP_CONTENT),(RelativeLayout.LayoutParams.WRAP_CONTENT));
zRelativeLayoutParamsL.addRule(RelativeLayout.RIGHT_OF,1);
zRelativeLayoutParamsL.addRule(RelativeLayout.CENTER_IN_PARENT);
TheRelativelayoutL.addView(tvItemNameL, zRelativeLayoutParamsL);
zRelativeLayoutParamsL = new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams.WRAP_CONTENT),(RelativeLayout.LayoutParams.WRAP_CONTENT));
zRelativeLayoutParamsL.addRule(RelativeLayout.RIGHT_OF,1);
zRelativeLayoutParamsL.addRule(RelativeLayout.BELOW,2);
zRelativeLayoutParamsL.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
TheRelativelayoutL.addView(tvItemPriceL, zRelativeLayoutParamsL);
return TheRelativelayoutL;
}
I made the below changes to the UI and it works fine for me
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relaGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include
android:id="#+id/Master"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/activity_master_page" />
<ListView
android:id="#+id/ItemView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/Master" >
</ListView>
<ProgressBar
android:id="#+id/ItemsProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ItemView"
android:layout_centerHorizontal="true" />
</RelativeLayout>

how to show text above list ,i use ListActivity to show a custom list

dear
how to show text above customise list when i extends listactivity in my class file..the code is given below..
public class ServerResponce extends ListActivity {
private ArrayList<listobj> tobj = new ArrayList<listobj>();
static String str1;
PickUpLocation pickup=new PickUpLocation();
String pickuplocid= pickup.locationid;
String des=planner.description;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**//here not work force close**
// ****setContentView(R.layout.list_item);
**// TextView tv = (TextView)findViewById(R.id.text1);
// tv.setText("i want to book a cab for 4 hr/40km from sushant lok to delhi air port at" +
// "4 pm today"
// +"the cab should be 4 seater compact cab with carriage");
// tv.setBackgroundColor(R.color.black);**
//
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ServerResponce.this,
"", "Loading. Please wait...", true);
}
protected void onProgressUpdate(Integer... integer){
TextView tv = null;
tv.setText("gjh");
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL("http://qrrency.com/mobile/j2me/cab/CabBookingStatus.php?requestid=666");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
int l=0;
int k=0;
StringBuffer buffer=new StringBuffer();
String str=" ";
while ((l=in.read())!=-1)
{
buffer.append((char)l);
str=str+(char)l;
}
in.close();
//
try {
JSONObject json = new JSONObject(str);
JSONArray nameArray=json.getJSONArray("bookings");
JSONObject[] cabListing=new JSONObject[nameArray.length()];
for (int i = 0; i < cabListing.length; i++) {
//JSONObject jSONObject = cabListing[i];
JSONObject jSONObject = nameArray.getJSONObject(i);
listobj tweet = new listobj();
JSONObject temp=jSONObject.getJSONObject("booking");
tweet.cabid = temp.getString("cabbookingid");
tweet.author =temp.getString("CabDriverName");
tweet.content =temp.getString("price");
tweet.cabrat=temp.getString("cabrating");
tobj.add(tweet);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e)
{
} catch (IOException e)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new tListAdaptor(
ServerResponce.this, R.layout.list_item, tobj));
}
}
private class tListAdaptor extends ArrayAdapter<listobj> {
private ArrayList<listobj> tobj;
public tListAdaptor(Context context,int textViewResourceId,ArrayList<listobj> items)
{
super(context, textViewResourceId, items);
this.tobj = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
listobj o = tobj.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView bt1 = (TextView) v.findViewById(R.id.bottomtext1);
TextView bt2 = (TextView) v.findViewById(R.id.bottomtext2);
bt.setText("CAB NAME: " +o.author);
bt1.setText("CAB ID: " +o.cabid);
tt.setText("PRICE: " +o.content);
bt2.setText("CAB RATING: " +o.cabrat);
return v;
}
}
public String getItem(int position) {
// TODO Auto-generated method stub
return null;
}
}
xml file is...
<?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"
>
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip">
<TextView android:id="#+id/text" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text=" "
android:textStyle="italic"
/>
<Button
android:text="auto book"
android:id="#+id/autobook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"/>
<Button
android:text="cancel"
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/autobook"/>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView android:id="#+id/toptext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
<TextView android:id="#+id/bottomtext1" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext2" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
You can set the header to by a textview. It will still be in the same format as a list view but the top item in the list view will be your text view
Your code is looking for R.id.text1
TextView tv = (TextView)findViewById(R.id.text1);
But your xml does not have any such id.
So you will get a null for tv.

Categories

Resources