How to loop execution of AsyncTask with an array of params - android

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.

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);
}
}
}

Viewpager not delete current page position

I am using ViewPager in side activity and add Fragment-State-Pager-Adapter and trying to remove current page position after add the some pages.but every time removed last page position.so please recommend me for use right approach for doing this.Thanks in advance.
This is my activity and adapter code.
public class Main-Activity extends Fragment-Activity implements AddItemFragment.OnFragmentInteractionListener {
PagerAdapter mAdapter;
ViewPager mPager;
Button button ,btn_add;
int pos,TOTAL_PAGES=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
//THIS IS THE MODEL CLASS WHERE I ADD THE PAGES.
MoveItems.items = new ArrayList<>();
MoveItems.items.clear();
Intialize();
}
public void Intialize() {
mPager = (ViewPager)findViewById(R.id.pager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
pos = position + 1;
}
#Override
public void onPageScrollStateChanged(int state) {
//Function.toast(MainActivity.this, "onPageScrollStateChanged");
}
});
Addpage();
button = (Button)findViewById(R.id.delete_current);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAdapter.deletePage(mPager.getCurrentItem());
Function.toast(MainActivity.this,"'Delete page");
}
});
btn_add=(Button)findViewById(R.id.goto_first);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Addpage();
}
});
}
public void Addpage() {
TOTAL_PAGES++;
ItemDescription item = new ItemDescription();
MoveItems.items.add(item);
if (mAdapter != null)
mAdapter.notifyDataSetChanged();
mPager.setCurrentItem((TOTAL_PAGES - 1));
}
#Override
public void onFragmentCreated(ItemDescription itemDescription, int position) {
if (mAdapter != null)
mAdapter.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentStatePagerAdapter
{
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ItemDescription description = new ItemDescription();
description.setItemNo(position);
description = MoveItems.items.get(position);
return AddItemFragment.newInstance(position, description);
}
#Override
public int getCount() {
return MoveItems.items.size();
}
public void deletePage(int position)
{
MoveItems.items.remove(position);;
notifyDataSetChanged();
}
}
}
This The XML PART
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center"
android:measureWithLargestChild="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0">
<!--go to the first page in the view pager-->
<Button android:id="#+id/goto_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First">
</Button>
<!--Delete the current page-->
<Button android:id="#+id/delete_current"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete">
</Button>
<!--go to the last page in the view pager-->
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last">
</Button>
</LinearLayout>
</LinearLayout>
THIS THE FRAGMENT CLASS WHERE I INFLATE THE LAYOUT WHICH HAVE CHECK-BOXES AND EDITEXT.
public class AddItemFragment extends Fragment {
// Store instance variables
private int page;
ItemDescription description;
CheckBox furniture, mattress, box, appliance;
EditText other, item_description;
private OnFragmentInteractionListener listener;
LinearLayout line1;
CheckBox checkboxes[];
View v;
// newInstance constructor for creating fragment with arguments
public static AddItemFragment newInstance(int page, ItemDescription item) {
AddItemFragment fragmentFirst = new AddItemFragment();
Bundle args = new Bundle();
args.putInt("pagecount", page);
args.putSerializable("item", item);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onAttach(Activity activity) {
try {
listener = (OnFragmentInteractionListener) getActivity();
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
super.onAttach(activity);
}
/**
* Interface for communicating data
*/
public interface OnFragmentInteractionListener {
public void onFragmentCreated(ItemDescription itemDescription, int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_add_item, container, false);
page = getArguments().getInt("pagecount", 0);
description = (ItemDescription) getArguments().getSerializable("item");
One = (CheckBox) v.findViewById(R.id.furniture);
Two = (CheckBox) v.findViewById(R.id.mattress);
Three = (CheckBox) v.findViewById(R.id.box);
Four = (CheckBox) v.findViewById(R.id.appliance);
other = (EditText) v.findViewById(R.id.other);
item_description = (EditText) v.findViewById(R.id.item_description);
checkboxes = new CheckBox[]{One, Two, Three, Four};
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
BitmapsForImage bitmapsForImage = null;
imagePath = "";
if (resultCode == Activity.RESULT_OK) {
if (requestCode == Constants.ImagePick) {
Uri imageUri = getPickImageResultUri(data);
imagePath = getPath(getActivity(), imageUri);
bitmapsForImage = Function.resizeBitmap(imagePath, getActivity());
} else if (Constants.CAMERA_REQUEST_CODE == requestCode) {
bitmapsForImage = Function.resizeBitmap(imagePath, getActivity());
} else if (Constants.GALLERY_IMAGE == requestCode && null != data) {
if (data != null) {
Uri contentURI = data.getData();
String imagePath = Function.getRealPathFromURI(getActivity(), contentURI);
bitmapsForImage = Function.resizeBitmap(imagePath, getActivity());
}
}
if (bitmapsForImage != null && imagePath != null && imagePath.length() > 0) {
MoveItems.itemsBitmapList.set(page, bitmapsForImage.getBitmapToShow());
line1.setVisibility(View.GONE);
description.setItemFilePath(imagePath);
description.setItemFile(new File(imagePath));
MoveItems.items.get(page).setItemFile(new File(imagePath));
MoveItems.items.get(page).setItemFilePath(imagePath);
try {
listener.onFragmentCreated(description, page);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Function.toast(getActivity(), "Some Error Occured");
return;
}
}
}
}
THIS IS THE Fragment_Add_Item WHICH HAVE CHECK BOX AND EDIT TEXT.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:layout_marginTop="20dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:orientation="horizontal">
<CheckBox
android:id="#+id/furniture"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Furniture"
android:textSize="15sp" />
<CheckBox
android:id="#+id/mattress"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Mattress"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="5dp"
android:orientation="horizontal">
<CheckBox
android:id="#+id/box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Box"
android:textSize="15sp" />
<CheckBox
android:id="#+id/appliance"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Appliance"
android:textSize="15sp" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/other_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<EditText
android:id="#+id/other"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Other"
android:singleLine="true"
android:textSize="15sp" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/notes_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/item_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Item Notes"
android:singleLine="true"
android:textSize="15sp" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="#+id/line1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="2dp"
android:text="Add a Photo"
android:textSize="15sp" />
<TextView android:id="#+id/Des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="2dp"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
This problem occurs when I get any input type inside Fragment_Add_Item layout please help me for find out this problem.This very-very important from me and i am using first time view-pager. In this code item of view-pager deleted but not exact.so i was doing this differnt ways. but not getting right output. thanks in advance.

Android ListView lags for every scroll, even with ViewHolder

I want to give a little context: The app I'm currently involved in helping develop is an app a company has already developed for IOS and Android but the Android developer didn't delivered the expected results (mostly performance wise) so the leader gave me the code to see if I could fix it. Given the code I tried to improve it, now, the app is a picture sharing app somewhat like Instagram and it uses and endless scrolling list, the problem with the app is that every time I scroll a little bit, the app lags or freezes for a second and then loads a new row.
The listview only has one row visible at any moment.
What have I tried?:
The adapter wasn't using the ViewHolder pattern so I tried to implement it.
The programmer was defining a lot of click listeners on the getView method so I removed them.
still, every time I scroll ( a new row appears as there's only one visible row at any time) it lags. Are there any other noticeable problems here that could be the cause?
On another note, on this view there's a lot of overdraw so, maybe it's affecting the performance on the ListView? if so, tell me and I'll post the XML part.
Here's the code I adapted:
public class SomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
// declaration and constructors.....
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//initialization......
//setting variables.......
//getting views.....
listview = (ListView)rootView.findViewById(R.id.listview);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
int position = listview.getLastVisiblePosition();
if (!loading) {
loading = true;
listview.addFooterView(footerView, null, false);
currentVal = position + 1;
LoadMoreStuffAsyncTask loadMoreStuffAsyncTask = new LoadMoreStuffAsyncTask();
loadMoreStuffAsyncTask.execute();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (listview == null || listview.getChildCount() == 0) ? 0 : listview.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
}
});
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity, container, false);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(SomeFragment.this);
return rootView;
}
private void LoadStuff () {
list=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
try {
list = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void LoadMoreStuff () {
List<ParseObject> moreList=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
query.setSkip(currentVal);
try {
moreList = query.find();
if(moreList!=null|| moreList.size()!=0){
for(int i =0;i<moreList.size();i++){
list.add(moreList.get(i));
}
}else{
loading=false;
}
} catch (ParseException e) {
e.printStackTrace();
loading=false;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
listAdapter.notifyDataSetChanged();
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
class LoadMoreStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected Void doInBackground(Void... params) {
LoadMoreStuff();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listAdapter.updateList(list);
listview.setAdapter(listAdapter);
loading=false;
listview.removeFooterView(footerView);
listview.setSelection(currentVal);
}
}
class LoadStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getString(R.string.loading));
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
LoadStuff();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
swipeRefreshLayout.setRefreshing(false);
listAdapter = new CustomAdapter(activity,momentosGeneral);
listview.setAdapter(listAdapter);
}
}
}
This is the adapter:
public class CustomAdapter extends BaseAdapter {
//declaration of variables.....
public CustomAdapter(ActionBarActivity activity, List<ParseObject> list) {
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder{
//holderfields......
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder holder;
if (v == null) {
v = View.inflate(activity.getApplicationContext(), R.layout.customview, null);
holder = new ViewHolder();
holder.profilepicture = (CircularImageView) v.findViewById(R.id.profilepic);
holder.username = (TextView) v.findViewById(R.id.username);
holder.picture = (ParseImageView) v.findViewById(R.id.picture);
holder.container =(LinearLayout)v.findViewById(R.id.container);
holder.share=(LinearLayout)v.findViewById(R.id.share);
holder.comment= (TextView) v.findViewById(R.id.comment);
holder.likes= (TextView) v.findViewById(R.id.likes);
holder.publishDate =(TextView)v.findViewById(R.id.publisdate);
holder.liked = (ImageView)v.findViewById(R.id.liked);
v.setTag(holder);
}
holder = (ViewHolder)v.getTag();
CustomTypography customTypo = new CustomTypography(activity.getApplicationContext());
holder.username.setTypeface(customTypo.OpenSansSemibold());
if(list.get(position).getParseUser("User")!=null){
holder.username.setText(list.get(position).getParseUser("User").getString("name"));
profilePic = list.get(position).getParseUser("User").getParseFile("profilePic");
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
else{
holder.username.setText("");
}
final ParseFile picture = list.get(position).getParseFile("picture");
if (picture != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(picture.getData(), 0, picture.getData().length));
holder.picture.setImageDrawable(drawable);
holder.picture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
else{
}
holder.container.setLayoutParams(customLayoutParams);
holder.comment.setText(capitalizarPrimeraLetra(list.get(postiion).getString("Comment")));
holder.comment.setTypeface(customTypo.OpenSansRegular());
final int likes= list.get(position).getInt("Likes");
if(likes==0|| likes<0){
holder.likes.setText("");
}else{
holder.likes.setText(String.valueOf(likes));
}
holder.likes.setTypeface(customTypo.OpenSansLight());
holder.publishDate.setText(timeBetween(list.get(position).getCreatedAt()));
ParseQuery<ParseObject> query = ParseQuery.getQuery("LikedPictures");
query.whereEqualTo("picture", list.get(position));
query.whereEqualTo("user", currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> likelist, ParseException e) {
if (e == null) {
if (likelist.size() != 0) {
hasLiked = true;
holder.liked.setBackground(activity.getApplicationContext().getResources().getDrawable(R.drawable.like));
holder.likes.setTextColor(activity.getApplicationContext().getResources().getColor(R.color.red));
} else {
hasLiked = false;
}
} else {
hasLiked = false;
}
}
});
return v;
}
private String timeBetween(Date date){
String result="";
Date parsedPictureDate = null;
Date parsedCurrentDate=null;
Date today = new Date();
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
try {
parsedPictureDate= dateFormatLocal.parse(dateFormatGmt.format(date));
parsedCurrentDate=dateFormatLocal.parse(dateFormatGmt.format(hoy));
} catch (java.text.ParseException e) {
result="";
}
long milis=parsedCurrentDate.getTime()-parsedPictureDate.getTime();
final long MILISECS_PER_MINUTE=milis/(60 * 1000);
final long MILISECS_PER_HOUR=milis/(60 * 60 * 1000);
final long MILLSECS_PER_DAY=milis/(24 * 60 * 60 * 1000);
if(milis<60000){
result="Now";
}
if(milis>=60000&&milis<3600000){
result=MILISECS_PER_MINUTE+" min";
}
if(milis>=3600000&&milis<86400000){
result=MILISECS_PER_HOUR+" h";
}
if(milis>=86400000){
result=MILLSECS_PER_DAY+" d";
}
return result;
}
This is the item that always gets populated in the listview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#android:color/white"
android:paddingBottom="20dp"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/somelayout"
android:layout_weight="0.5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_marginLeft="5dp"
android:paddingRight="#dimen/padding_16dp_sw600"
android:gravity="left"
android:layout_marginBottom="5dp">
<customImageView
android:layout_gravity="center"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profilepicture"
app:border_width="0dp"
/>
<TextView
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/username"
android:textSize="14sp"
android:gravity="left"
android:singleLine="true"
android:minLines="1"
android:maxLines="1"
android:lines="1"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/layoutTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:layout_weight="0.5"
android:layout_gravity="center" >
<TextView
android:gravity="right"
android:id="#+id/publishdate"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/container"
android:layout_gravity="center"
android:background="#drawable/border"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.parse.ParseImageView
android:layout_margin="1dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/picture" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<LinearLayout
android:id="#+id/layoutlikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="left"
android:layout_weight="0.5"
android:layout_gravity="center" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/likes"
>
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numlikes"
android:text="0"
android:textSize="14sp"
android:layout_margin="#dimen/margin_16dp_sw600"
/>
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/likepic"
android:background="#drawable/like_off"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sharelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:padding="10dp"
android:layout_weight="0.5"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_gravity="center" >
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sharepic"
android:background="#drawable/ellipsis"
/>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/division_2dp_sw_600"
android:layout_margin="#dimen/margin_16dp_sw600"
android:background="#color/loading" />
<TextView
android:layout_gravity="left"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/comment"
android:textSize= "14sp"
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_marginRight="#dimen/margin_16dp_sw600"
/>
</LinearLayout>
Your biggest performance hit is probably the code below. You should use some sort of caching rather than decoding the Bitmap each time.
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
Also, you are creating a new CustomTypography instance everytime getView() is called. I assume this class extends Typeface, in which case you could just use a single instance that gets initialised in the adapter's constructor.
Here are a couple of things:
1. in your adapter.getView() method, move the
holder = (ViewHolder)v.getTag();
to if/else scope:
if(view ==null){
//creation of viewHolder
}else{
holder = (ViewHolder)v.getTag();
}
2. There is too much code in the adapter.getView(), specially the parse query. You better call it once per item, by caching the result of query for each item in adapter. It is currently being called on every item get visible on scroll.
3. Try to reduce the count of views in your item's xml. Too many views in ListView items cause in memory leak and low performance.
4. Adding the hardwareAccelerated="true" to your activity in manifest might help.
5. Try to comment out the scroll listener, to find out if it is reducing the performance.

android spinner setSelection not working even after call setAdapter

I have this strange behavior, I have class that extend Dialog, and in onCreate() Method I load data and set it to my spinner and then call spinner.setSelection , the spinner is always select the first item.
I have tried
spinner.setSelection(position);
spinner.setSelection(position, true);
spinner.setSelection(position, false);
spinner.post (Runnable)
new Handler().postDelay (Runnable)
so please can any one tell me what is the problem ??
EDIT
public class MyDialog extends Dialog{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
int layourResId = mContext.getResources().getIdentifier("dialog_layout_default", "layout", mContext.getPackageName());
setContentView(layourResId);
initializeUIComponent();
initializeUIComponentData();
initializeUIComponentAction();
}
private void initializeUIComponent () {
mCountriesSpinner = (Spinner) findViewById(countriesResId);
mOperatorsSpinner = (Spinner) findViewById(operatorsResId);
}
private void initializeUIComponentData () {
mCountriesSpinner.setAdapter(getCountriesAdapter());
mOperatorsSpinner.setAdapter(getOperatorsAdapter(getCountriesAdapter().getItem(mCurrentSelectedCountry)));
mMCC = PhoneUtils.getDeviceMCC(mContext);
mMNC = PhoneUtils.getDeviceMNC(mContext);
if (mMCC != null && mMNC != null) {
String plmn = mMCC + mMNC;
plmn = "41503";
getDefaultSelection(plmn);
}
}
private ArrayList<String> getCountries() {
// logic here
return countriesArray;
}
private ArrayList<String> getOperators(String countryName) {
// logic here
return operatorsArray;
}
private ArrayAdapter<String> getCountriesAdapter() {
// logic here
return countriesArrayAdapter;
}
private ArrayAdapter<String> getOperatorsAdapter(String countryName) {
// logic here
return operatorsArrayAdapter;
}
private void getDefaultSelection(String plmn) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i).getPLMN().equals(plmn)) {
object defaultSelection = array.get(i);
if (defaultSelection != null) {
mCountriesSpinner.setSelection(getCountriesAdapter().getPosition(defaultSelection.getCountryName()));
ArrayAdapter<String> adapter = getOperatorsAdapter(defaultSelection.getCountryName());
mOperatorsSpinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
int position = adapter.getPosition(defaultChannel.getOperatorName());
Toast.makeText(mContext, "position to be selected in operator " + position, Toast.LENGTH_SHORT).show();
mOperatorsSpinner.setSelection(position, true);
}
}
}
}
}
EDIT2
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/default_container_bg"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="#string/please_choose_country"
android:textColor="#android:color/black" />
<Spinner
android:id="#+id/countries_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="#string/please_choose_operator"
android:textColor="#android:color/black" />
<Spinner
android:id="#+id/operators_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/payment_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="#string/payment" />
</LinearLayout>
</RelativeLayout>

Inflate two different Itens with different adapters in ListView on Android

I make a ListView that receive data in JSON and define each item according the data received. Its working fine, but now I need to add the first item with a different layout, that will be defined by a different JSON, with different data, how can I do this?
I'm using InfiniteScroll library, but it just make the ListView infinite, the base is the same.
Obs: I've already tried to inflate different layout for position == 0, but didn't work, the first and the last itens of ListView keep with the different layout, and if I do this, I will lost the first item for the JSON data that I'm already using.
Here is how I'm doing the firs part:
public class TabPerfil extends ListActivity {
public static ArrayList<ItensMural> array_itensMural;
private static final int SEVER_SIDE_BATCH_SIZE = 25;
private InfiniteScrollListView demoListView;
private ListAdapterMural demoListAdapter;
private Handler handler;
private AsyncTask<Void, Void, List<ItensMural>> fetchAsyncTask;
private LoadingMode loadingMode = LoadingMode.SCROLL_TO_BOTTOM;
private StopPosition stopPosition = StopPosition.REMAIN_UNCHANGED;
ImageLoader imageLoader;
public TabPerfil () {
super();
array_itensMural = new ArrayList<ItensMural>();
// Set up the image mapping for data points
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_perfil);
handler = new Handler();
demoListView = (InfiniteScrollListView) this.findViewById(android.R.id.list);
demoListView.setLoadingMode(loadingMode);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
demoListView.setLoadingView(layoutInflater.inflate(R.layout.loading_view_demo, null));
demoListAdapter = new ListAdapterMural(getApplicationContext(), new NewPageListener() {
#Override
public void onScrollNext() {
fetchAsyncTask = new AsyncTask<Void, Void, List<ItensMural>>() {
#Override
protected void onPreExecute() {
// Loading lock to allow only one instance of loading
demoListAdapter.lock();
}
#Override
protected List<ItensMural> doInBackground(Void ... params) {
List<ItensMural> result = new ArrayList<ItensMural>();
// Mimic loading data from a remote service
getMuralData();
for(int i = 0; i<SEVER_SIDE_BATCH_SIZE;i++)
{
if(array_itensMural.size()>0 && i<array_itensMural.size())
result.add(array_itensMural.get(i));
else
break;
}
array_itensMural.clear();
return result;
}
#Override
protected void onPostExecute(List<ItensMural> result) {
if (isCancelled() || result == null || result.isEmpty()) {
demoListAdapter.notifyEndOfList();
} else {
// Add data to the placeholder
demoListAdapter.addEntriesToBottom(result);
// Add or remove the loading view depend on if there might be more to load
if (result.size() < SEVER_SIDE_BATCH_SIZE) {
demoListAdapter.notifyEndOfList();
} else {
demoListAdapter.notifyHasMore();
}
// Get the focus to the specified position when loading completes
}
};
#Override
protected void onCancelled() {
// Tell the adapter it is end of the list when task is cancelled
demoListAdapter.notifyEndOfList();
}
}.execute();
}
#Override
public View getInfiniteScrollListView(final int position, View convertView, ViewGroup parent) {
// Customize the row for list view
if(convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_perfil, null);
}
defineLayout(convertView, position);
return convertView;
}
});
demoListView.setAdapter(demoListAdapter);
// Display a toast when a list item is clicked
demoListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
handler.post(new Runnable() {
#Override
public void run() {
}
});
}
});
// Set a listener to be invoked when the list should be refreshed.
((InfiniteScrollListView) getListView()).setOnRefreshListener(new ca.weixiao.widget.InfiniteScrollListView.OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
// Load the first page to start demo
demoListAdapter.onScrollNext();
}
public void getMuralData()
{
//Json Request
String resposta = Services.JsonRequest();
try {
JSONObject jObj = new JSONObject(resposta);
JSONArray items = jObj.getJSONArray(TysdoConstants.JSON_ITEMS);
TabPerfil.array_itensMural = new ArrayList<ItensMural>();
for(int i=0; i<items.length();i++)
{
ItensMural newItem = new ItensMural();
JSONObject item_obj = items.getJSONObject(i);
newItem.items_id = item_obj.getInt("id");
//...
array_itensMural.add(newItem);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void defineLayout(View convertView, int position)
{
final ItensMural itens = (ItensMural) demoListAdapter.getItem(position);
if (itens != null) {
//Set layout things, like TextView.setText("Text") etc
}
}
private class GetDataTask extends AsyncTask<Void, Void, List<ItensMural>> {
#Override
protected void onPreExecute() {
// Loading lock to allow only one instance of loading
demoListAdapter.clearEntries();
}
#Override
protected List<ItensMural> doInBackground(Void... params) {
// Simulates a background job.
demoListAdapter.onScrollNext();
return array_itensMural;
}
#Override
protected void onPostExecute(List<ItensMural> result) {
((InfiniteScrollListView) getListView()).onRefreshComplete();
super.onPostExecute(result);
}
}
}
The tab_perfil.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ca.weixiao.widget.InfiniteScrollListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/infinite_listview_radiogroup_stop_position" />
</RelativeLayout>
the item_perfil.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="fill_parent"
android:layout_height="fill_parent"
android:paddingRight="5dp"
android:paddingLeft="5dp">
<LinearLayout
android:paddingTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/layout_1">
<TextView
android:id="#+id/row_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:textSize="19sp"
android:textColor="#color/dark_grey"/>
<TextView
android:id="#+id/row_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:textSize="19sp"
android:text="18h"
android:textColor="#color/dark_grey"/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/layout_2"
android:layout_below="#+id/layout_1"
android:paddingBottom="-15dp">
<ImageView
android:id="#+id/img_photo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:padding="2dp"
android:scaleType="fitXY" />
<ImageView
android:id="#+id/img_photo_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:src="#drawable/moldura_empresa_big"
android:scaleType="fitXY"
/>
<ImageView
android:id="#+id/img_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingLeft="-1dp"
android:src="#drawable/feito_flag_big"
android:scaleType="fitXY" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/sombra_desejo"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/txt_desejo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/style_btnLogin"
android:gravity="center"/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/layout_2"
android:background="#drawable/barra_branca_desejo">
<LinearLayout
android:id="#+id/layout_curtir"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="15dp"
android:layout_alignParentLeft="true">
<Button
android:id="#+id/btn_like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/icone_curtido_inactive" />
<TextView
android:id="#+id/row_likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:textColor="#color/dark_grey"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="15dp"
android:paddingRight="-15dp"
android:layout_toRightOf="#+id/layout_curtir">
<Button
android:id="#+id/btn_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/icone_comentario" />
<TextView
android:id="#+id/row_comments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/dark_grey"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_incentivo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="15dp"
android:paddingLeft="-15dp"
android:layout_toRightOf="#+id/layout_comment">
<Button
android:id="#+id/btn_incentivar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/icone_incentivo" />
<TextView
android:id="#+id/row_incentivar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/dark_grey"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:textSize="20sp"
android:textStyle="bold"
android:text="999" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentRight="true"
android:padding="20dp">
<Button
android:id="#+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/icone_mais" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
Add Header View in your listview, try something like this-
listMain = (ListView) findViewById(R.id.listMain);
View header = View.inflate(this, R.layout.row_top, null);
listMain.addHeaderView(header);
EDIT:
If above code does not work try this one-
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, listMain, false);
listMain.addHeaderView(header, null, false);
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(this, R.layout.row_top, null);
listMain.addHeaderView(header,null,false);//if you don't want header to be clickable
listMain.addHeaderView(header);//header will 1st item of the list view ie. at 0th index

Categories

Resources