I have an Vertical listview i want listview should be closed. For example if the last item is reached in Listview then show the first item below the last item. It means item should be in circular format. And if i scroll from first item it should show last item before first item. I want scrolling for both side.
public class MainActivity extends Activity {
ListView list;
long startTime;
long endTime;
List<String> mList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
downloadDetails();
String str;
for (int i = 0; i < 10; i++) {
str = new String("Data --- " + i);
mList.add(str);
}
CircularAdapter adapter = new CircularAdapter(this, 0, mList);
list.setAdapter(adapter);
final YourRunnable runy = new YourRunnable();
list.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
startTime = (new Date()).getTime();
runy.onPause();// pausing thread actually pauses scrolling
}
if (event.getAction() == MotionEvent.ACTION_UP) {
endTime = (new Date()).getTime();
if ((endTime - startTime) <= 100) {// 100 mill second limit
// for click
// Log.i("ITEM CLICK() ", "item : ");
}
runy.onResume(); // resume scrolling
}
return false;
}
});
new Thread(runy).start();
}
class YourRunnable implements Runnable {
private Object mPauseLock;
private boolean mPaused;
private boolean mFinished;
public YourRunnable() {
mPauseLock = new Object();
mPaused = false;
mFinished = false;
}
#SuppressLint("NewApi")
public void run() {
while (!mFinished) {
// for loop is not infinite but enough as Integer.MAX_VALUE
for (int index = 0; index < list.getAdapter().getCount(); index++) {
list.smoothScrollToPositionFromTop(list.getLastVisiblePosition() + 1, 0, 10000);
try {
// it helps scrolling to stay smooth as possible (by
// experiment)
Thread.sleep(3000);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();// putting thread in wait
// list of mPauseLock
// object
} catch (InterruptedException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// to pause list
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
// resume thread
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();// notify all object that are waiting on
// the wait list of mPauseLock object
}
}
}
private class CircularAdapter extends ArrayAdapter {
List<String> mlist;
Context mContext;
LayoutInflater inflater;
public final int HALF_MAX_VALUE = Integer.MAX_VALUE / 2;
public final int MIDDLE;
#SuppressWarnings("unchecked")
public CircularAdapter(Context ctx, int resId, List<String> objects) {
super(ctx, resId, objects);
mContext = ctx;
mlist = objects;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % mlist.size();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
int relativePos = position % mlist.size();
Log.i("RELATIVE : ", " POS:" + relativePos);
return mlist.get(relativePos);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String model = getItem(position);
holder.name.setText(model);
convertView.setOnClickListener(new ListenerT(model) {
#Override
public void onClick(View v) {
Log.i("CLICK", "ITEM---" + name);
}
});
return convertView;
}
}
// use your own listener to pass parameter
private class ListenerT implements OnClickListener {
String name;
public ListenerT(String nm) {
name = nm;
}
#Override
public void onClick(View v) {
}
}
private class ViewHolder {
TextView name;
}
}
Related
I have created a custom listview adapter to fit a button, a custom chronometer and a textview. When i scroll my listview, the rows that are "hidden" refresh themselves and so chronometers, how can i keep chronometers running even if they're hidden?
I am quite new to Android development so i may have done something wrong; I know that listview refresh its rows when scrolled but maybe there's something that i missed to make chronometers running in background
public class MyCustomAdapter extends BaseAdapter {
ArrayList<String> users;
Context context;
LayoutInflater inflater = null;
public MyCustomAdapter(Activity mainActivity, ArrayList<String> usersList) {
// TODO Auto-generated constructor stub
users = usersList;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return users.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return users.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
private class Holder {
TextView tv;
CustomChrono cr;
Button but;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.customized_list_view, null);
holder.tv = (TextView) rowView.findViewById(R.id.names_laps);
holder.cr = (CustomChrono) rowView.findViewById(R.id.chronometer_laps);
holder.but = (Button) rowView.findViewById(R.id.stop_button);
holder.cr.start();
holder.but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//((ListView) parent).performItemClick(v, position, 0);
holder.cr.stop();
stopped = true;
}
});
holder.tv.setText(users.get(position));
rowView.setTag(holder);
return rowView;
}
}
Then I have my activity class where I use this adapter
public class RunnerLaps extends AppCompatActivity {
ListView list;
ArrayList<String> runner_array;
private Map<Runner,String> map = new HashMap<Runner,String>(10);
private boolean isClicked = true;
private boolean isStartedNow = false;
boolean stopped = false;
ArrayList<Runner> arr_runners;
ArrayList<Runner> runners_arrList;
private long previousClickTime1 = 0;
Runner r = null;
String m = "";
SerializableManager serializableManager;
String filename = "myfile";
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
//Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_laps);
Intent i = getIntent();
serializableManager = new SerializableManager();
runner_array = (ArrayList<String>) getIntent().getSerializableExtra("KEY");
ArrayList<Runner> running = getIntent().getExtras().getParcelableArrayList("arr2");
runners_arrList = new ArrayList<Runner>(runner_array.size());
for (String r : runner_array)
{
runners_arrList.add(new Runner(r));
}
for (int f = 0; f < runners_arrList.size();f++)
{
Log.d("Runner: " + f,runners_arrList.get(f).getName());
}
m = getIntent().getExtras().getString("booly");
for (int j = 0; j < runner_array.size(); j++) {
Runner r = new Runner(runner_array.get(j));
map.put(r, runner_array.get(j));
}
if (m!= null)
{
stopped = true;
}
list = (ListView) findViewById(R.id.laps_list);
final MyCustomAdapter adapter = new MyCustomAdapter(RunnerLaps.this,runner_array);
list.setAdapter(adapter);
//addRunners();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomChrono chr = (CustomChrono) view.findViewById(R.id.chronometer_laps);
r = runners_arrList.get(position);
r.setTemp(System.currentTimeMillis());
long temp = r.getTemp();
previousClickTime1 = temp;
if (previousClickTime1 != 0 && previousClickTime1 - temp < 300)
{
if (stopped == true)
{
chr.stop();
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
Intent i = new Intent (RunnerLaps.this,Runner_Display.class);
i.putExtra("key",(Serializable) r);
i.putParcelableArrayListExtra("arr",arr_runners);
for (int h = 0; h < runners_arrList.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
startActivity(i);
}
else
{
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
for (int h = 0; h < runner_array.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
}
}
else
{}
}
});
}
}
I have a ListView, and I want to implement fastscroll with SectionIndexer with 3 item ImageViews per row item like this:
https://www.dropbox.com/s/th83hznhqzr01ds/cap2.png?dl=0
I want implement onclicklistener for each imageview 1, 2, 3 but when I use
imageview1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO here
}
});
it doesn't work - onClickListener is not caught, I don't know why.
Here is my adapter code:
public class LazyImageLoadAdapter extends BaseAdapter implements SectionIndexer{
private Context _context;
private TopActivity _parentActivity;
private static LayoutInflater inflater=null;
public CoverBookLoader _coverBookLoader;
private ArrayList<RowBook> _arrListRowBooks;
private int sizeView;
public LazyImageLoadAdapter(Context context, ArrayList<RowBook> arrListRowBooks) {
this._context = context;
this._parentActivity = (TopActivity) context;
this.sizeView = _parentActivity.getScreenWidth();
this._arrListRowBooks = arrListRowBooks;
inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_coverBookLoader = new CoverBookLoader(_context);
}
public int getCount() {
// return data.length;
return _arrListRowBooks.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public LinearLayout llBook1;
public ImageView ivBookCover1;
public ProgressBar pbLoadingBookCover1;
public LinearLayout llBook2;
public ImageView ivBookCover2;
public ProgressBar pbLoadingBookCover2;
public LinearLayout llBook3;
public ImageView ivBookCover3;
public ProgressBar pbLoadingBookCover3;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holderBook;
LayoutParams lpSizeBook = new LayoutParams(sizeView / 3, sizeView * 3 / 5);
if(convertView==null){
vi = inflater.inflate(R.layout.listview_row, parent, false);
holderBook = new ViewHolder();
holderBook.llBook1 = (LinearLayout) vi.findViewById(R.id.llBook1);
holderBook.llBook1.setLayoutParams(lpSizeBook);
holderBook.ivBookCover1 = (ImageView) vi.findViewById(R.id.ivBookCover1);
holderBook.pbLoadingBookCover1 = (ProgressBar) vi.findViewById(R.id.pbLoadingCoverImageBook1);
holderBook.llBook2 = (LinearLayout) vi.findViewById(R.id.llBook2);
holderBook.llBook2.setLayoutParams(lpSizeBook);
holderBook.ivBookCover2 = (ImageView) vi.findViewById(R.id.ivBookCover2);
holderBook.pbLoadingBookCover2 = (ProgressBar) vi.findViewById(R.id.pbLoadingCoverImageBook2);
holderBook.llBook3 = (LinearLayout) vi.findViewById(R.id.llBook3);
holderBook.llBook3.setLayoutParams(lpSizeBook);
holderBook.ivBookCover3 = (ImageView) vi.findViewById(R.id.ivBookCover3);
holderBook.pbLoadingBookCover3 = (ProgressBar) vi.findViewById(R.id.pbLoadingCoverImageBook3);
vi.setTag( holderBook );
}
else {
holderBook=(ViewHolder)vi.getTag();
}
LinearLayout llBook1 = holderBook.llBook1;
llBook1.setLayoutParams(lpSizeBook);
ImageView ivBookCover1 = holderBook.ivBookCover1;
ProgressBar pbLoadingBookCover1 = holderBook.pbLoadingBookCover1;
LinearLayout llBook2 = holderBook.llBook2;
llBook2.setLayoutParams(lpSizeBook);
ImageView ivBookCover2 = holderBook.ivBookCover2;
ProgressBar pbLoadingBookCover2 = holderBook.pbLoadingBookCover2;
LinearLayout llBook3 = holderBook.llBook3;
llBook3.setLayoutParams(lpSizeBook);
ImageView ivBookCover3 = holderBook.ivBookCover3;
ProgressBar pbLoadingBookCover3 = holderBook.pbLoadingBookCover3;
RowBook rowBook = _arrListRowBooks.get(position);
if (rowBook.getSize() < 3) {
llBook3.setVisibility(View.VISIBLE);
}
if (rowBook.getSize() < 2) {
llBook2.setVisibility(View.VISIBLE);
}
if (rowBook != null) {
for (int i = 0; i < rowBook.getSize(); i++) {
switch (i) {
case 0:
addBook(rowBook.getBookAt(i), ivBookCover1, pbLoadingBookCover1);
break;
case 1:
addBook(rowBook.getBookAt(i), ivBookCover2, pbLoadingBookCover2);
break;
case 2:
addBook(rowBook.getBookAt(i), ivBookCover3, pbLoadingBookCover3);
break;
}
}
}
return vi;
}
private void addBook(Books book , ImageView ivBookCover, ProgressBar pbLoadingCoverImageBook){
ivBookCover.setImageResource(R.drawable.blank_book);
ivBookCover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO here
}
});
JSONObject objBookTag = new JSONObject();
try {
objBookTag.put(Define.KEY_JSONOBJ_BOOK_ID, book.getId());
objBookTag.put(Define.KEY_JSONOBJ_BOOK_URL_THUMBNAIL, book.urlThumbnail);
ivBookCover.setTag(objBookTag);
} catch (JSONException e) {
e.printStackTrace();
ivBookCover.setTag("{\""+Define.KEY_JSONOBJ_BOOK_ID+"\":\"" + book.getId()+"\", \""+Define.KEY_JSONOBJ_BOOK_URL_THUMBNAIL+"\":\""+book.urlThumbnail+"\"");
}
_coverBookLoader.DisplayImage(book.urlThumbnail, ivBookCover, book.getId(), pbLoadingCoverImageBook);
}
private String[] mSections;
public void initSection(String[] sections){
mSections = sections;
}
#Override
public Object[] getSections() {
Log.d("ListView", "Get sections");
if (mSections != null) {
String[] sectionsArr = new String[mSections.length];
for (int i=0; i < mSections.length; i++) {
sectionsArr[i] = "" + mSections[i];
}
return sectionsArr;
}
return null;
}
#Override
public int getPositionForSection(int sectionIndex) {
if (mSections != null) {
Log.d("ListView", "Get position for section");
for (int i=0; i < this.getCount(); i++) {
if (mSections[sectionIndex].equals("" + i)) {
return i;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
Log.d("ListView", "Get section");
return 0;
}
}
As my above comment reply, my adapter not fault, my fault is in my custom listview :
public class IndexableListView extends ListView {
// TODO
#Override
/**
* intercept touch event - **WRONG HERE**
*/
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
// TODO
}
And when i remove onInterceptTouchEvent, my problem is resolved
Now i should implement infinite scrolling to listview, for this i had found one easiest code that is
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//leave this empty
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - threshold) {
currentPage++;
//load more list items:
loadElements(currentPage);
}
}
}
but now i dont know what to include in the place if loadElements(current Page)
Here is an example code for you. this list scrolls infinite and using thread, it scrolls automatically. (pauses for while and coninues ...)
When you touch the list, list scrolling pauses and when you release it continues to automatic scroll.
If you touch under 100 miliseconds then it will considered item on click.
You can also scroll down or up, it will eventually continue to auto scrolling.
Come to think of it, it has turn into web like list. shame. :(
///////////////////////////////////////////////////////////////////////
List Item XML layout : item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:orientation="vertical" >
<TextView
android:background="#00ff00"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:id="#+id/name"
android:textColor="#000000"
android:textSize="26sp"
android:gravity="center"
android:textStyle="bold"/>
</LinearLayout>
///////////////////////////////////////////////////////////////////////
activity layout : activity_main.xml
<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:padding="25dp"
android:gravity="center"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="450dp"
android:background="#bbbbbb"
android:divider="#000000"/>
</RelativeLayout>
///////////////////////////////////////////////////////////////////////
activiy code (includes adapter and runnable thread) : MainActivity.java
public class MainActivity extends Activity {
ListView list;
long startTime;
long endTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
List<String> mList = new ArrayList<String>();
String str;
for(int i=0;i<10;i++){
str = new String("Data --- "+i);
mList.add(str);
}
LAdapter adapter = new LAdapter(this,0,mList);
list.setAdapter(adapter);
final YourRunnable runy = new YourRunnable();
list.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN ){
startTime= (new Date()).getTime();
runy.onPause();//pausing thread actually pauses scrolling
}
if(event.getAction() == MotionEvent.ACTION_UP){
endTime= (new Date()).getTime();
if((endTime - startTime)<=100){//100 mill second limit for click
//Log.i("ITEM CLICK() ", "item : ");
}
runy.onResume(); //resume scrolling
}
return false;
}
});
new Thread(runy).start();
}
class YourRunnable implements Runnable {
private Object mPauseLock;
private boolean mPaused;
private boolean mFinished;
public YourRunnable() {
mPauseLock = new Object();
mPaused = false;
mFinished = false;
}
public void run() {
while (!mFinished) {
//for loop is not infinite but enough as Integer.MAX_VALUE
for (int index = 0; index < list.getAdapter().getCount(); index++) {
list.smoothScrollToPositionFromTop(list.getLastVisiblePosition() + 1, 0, 10000);
try {
// it helps scrolling to stay smooth as possible (by experiment)
Thread.sleep(10000);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();//putting thread in wait list of mPauseLock object
} catch (InterruptedException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Call this method to pause thread.
*/
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
/**
* Call this method to resume thread.
*/
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();//notify all object that are waiting on the wait list of mPauseLock object
}
}
}
private class LAdapter extends ArrayAdapter{
List<String> mlist;
Context mContext;
LayoutInflater inflater;
public final int HALF_MAX_VALUE = Integer.MAX_VALUE/2;
public final int MIDDLE;
public LAdapter(Context ctx,int resId, List<String> objects){
super(ctx, resId, objects);
mContext = ctx;
mlist = objects;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % mlist.size();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
int relativePos = position % mlist.size();
Log.i("RELATIVE : "," POS:"+relativePos);
return mlist.get(relativePos);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Log.i("POSITION TAG", "POSITION : "+position);
// if(position>(getCount()-1)){
// return null;
// }
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
String model = getItem(position);
holder.name.setText(model);
convertView.setOnClickListener(new ListenerT(model) {
#Override
public void onClick(View v) {
Log.i("CLICK", "ITEM---"+name );
}
});
return convertView;
}
}
//use your own listener to pass parameter
private class ListenerT implements OnClickListener{
String name;
public ListenerT(String nm){
name = nm;
}
#Override
public void onClick(View v) {
}
}
private class ViewHolder{
TextView name;
}
}
In my application I am using a listview which displays the data from a CustomAdapter.In my arraylist I have two items.My listview shows the last added data two times instead of first item.
This is my custom Adapter:
public class NodeListViewCustomAdapter extends BaseAdapter {
LayoutInflater inflater;
Activity mActivity;
ArrayList<Node> mNodeList;
double mRecvProgress;
double mSentProgress;
String repeatSentprogress;
String repeatRecvprogress;
ViewHolder holder;
Node node;
public NodeListViewCustomAdapter(Activity aContext,Node node,ArrayList<Node> nodeList){
super();
mActivity = aContext;
this.node = node;
this.inflater = (LayoutInflater)aContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mNodeList = nodeList;
}
#Override
public int getCount() {
return mNodeList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public static class ViewHolder
{
TextView txtViewnodeTitle;
TextView sentStatustxtView;
TextView recvStatustxtView;
TextView msgsentvalue;
TextView msgrecvvalue;
TextView sentindicator;
TextView recvindicator;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.nodelistitem_row, null);
} else{
holder=(ViewHolder)convertView.getTag();
}
if(node.advertise)
convertView.setBackgroundColor(Color.YELLOW);
node.advertise = false;
convertView.setBackgroundColor(Color.BLACK);
holder.txtViewnodeTitle = (TextView) convertView.findViewById(R.id.txtViewnodeTitle);
holder.sentStatustxtView = (TextView) convertView.findViewById(R.id.sentstatustxtView);
holder.recvStatustxtView = (TextView) convertView.findViewById(R.id.recvstatustextView);
holder.msgsentvalue = (TextView) convertView.findViewById(R.id.msgsenttitle);
holder.msgrecvvalue = (TextView) convertView.findViewById(R.id.msgrecvtitle);
convertView.setTag(holder);
holder.sentStatustxtView.setGravity(Gravity.LEFT);
holder.recvStatustxtView.setGravity(Gravity.LEFT);
computeProgress();
holder.txtViewnodeTitle.setText(String.valueOf(node.nodeID));
holder.msgsentvalue.setText("< "+String.valueOf(node.ms)+"/"+node.MS);
holder.sentStatustxtView.setText(repeatSentprogress);
holder.msgrecvvalue.setText("> "+String.valueOf(node.mr)+"/"+node.MR);
holder.recvStatustxtView.setText(repeatRecvprogress);
return convertView;
}
private void computeProgress() {
mSentProgress = ((double)node.ms/(double)node.MS)*20;
mRecvProgress = ((double)node.mr/(double)node.MR)*20;
repeatSentprogress = new String(new char[(int)mSentProgress]).replace('\0', (char) 9608);
repeatRecvprogress = new String(new char[(int)mRecvProgress]).replace('\0', (char) 9608);
if(node.ms == node.MS)holder.sentStatustxtView.setTextColor(Color.GREEN);
else holder.sentStatustxtView.setTextColor(Color.BLUE);
if(node.mr == node.MR)holder.recvStatustxtView.setTextColor(Color.GREEN);
else holder.recvStatustxtView.setTextColor(Color.BLUE);
}
}
This is my Activity:
public class Nodes extends Activity implements OnItemClickListener {
ListView mListView;
NodeListViewCustomAdapter mNodeListAdapter;
public ArrayList <Node> mNodesList ;
TextView nodeIdView;
Timer mTimer;
Timer mInnerTimer;
int delay = 500;
int period = 500;
boolean found = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nodes);
mListView = (ListView)findViewById(R.id.node_list);
mNodesList = new ArrayList<Node>();
doTimerTask();
mListView.setOnItemClickListener(this);
}
private void doTimerTask() {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
while(true){
try{
String PeardOutput = null;
synchronized(AndroidPeardServer.nodestatsqe){
PeardOutput = AndroidPeardServer.nodestatsqe.poll();
if (PeardOutput == null) return;
}
String msg = PeardOutput.substring(3);
process_nodeStats(msg);
mNodeListAdapter.notifyDataSetChanged();
}
catch(Exception e){
e.printStackTrace();
}
}
}
});
}
}, delay, period);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
private void process_nodeStats(String msg) {
String[] nodeStats = msg.split(":");
String type = nodeStats[0];
int nodeID = Integer.parseInt(nodeStats[1]);
int value = Integer.parseInt(nodeStats[2]);
int cycle = Integer.parseInt(nodeStats[3]);
// Iterate through the nodelist
found = false;
for(Node node: mNodesList){
if (node.nodeID != nodeID) {
continue;
}
else found = true;
populateNode(node,type, nodeID, value, cycle);
mNodeListAdapter = new NodeListViewCustomAdapter(getParent(),node,mNodesList);
mListView.setAdapter(mNodeListAdapter);
break;
}
if (!found){
Node node = new Node();
mNodesList.add(node);
populateNode(node,type,nodeID,value,cycle);
mNodeListAdapter = new NodeListViewCustomAdapter(getParent(),node,mNodesList);
mListView.setAdapter(mNodeListAdapter);
}
}
private void populateNode(Node node,String type,int nodeId, int value, int cycle) {
node.nodeID = nodeId;
if(type.equals("MS")){
node.MS = value;
node.CS = cycle;
node.ms = 0;
}else if(type.equals("MR")){
node.MR = value;
node.CR = cycle;
node.mr = 0;
}else if(type.equals("ms")){
if(cycle==node.CS) node.ms = + value;
else node.ms = value;
}else if(type.equals("mr")){
if(cycle==node.CR) node.mr = + value;
else node.mr = value;
}else if (type.equals("NL")){
mNodesList.remove(node);
}else if(type.equals("NA")){
node.advertise = true;
}
}
//========= Node class to store in NodeList =================
public class Node {
int nodeID;
int MS; //Total Messages to Send to nodeID
int ms; //number of Messages sent so far
int MR ; //Total Messages expected from nodeID
int mr; //number of Messages received so far
int CS; //Investigation Cycle for Sending
int CR; //Investigation Cycle for Receiving
boolean advertise = false; // To know the advertisements received
}
}
I finally got tit right.I have not taken the node from the arraylist.So this line done it for me.
node = mNodeList.get(position);
Thanks for all.
I'm trying to update the TextView within a custom ListView at a set time interval, for example the TextView will update every 200ms however I can't figure out how to do this. The object updates with a number internally and I would like to show that in the mTitleText Textview however as the code below shows at the moment I can only achieve it when the user presses a button.
public class ListAdapter extends BaseAdapter {
private ArrayList< Object > mObjects;
private int mNumObjs = 0;
private LayoutInflater mLayoutInflater;
private Context mContext;
public ListAdapter ( Context context, ArrayList< Object > objects ) {
mObjects;= objects;
mLayoutInflater = LayoutInflater.from(context);
mContext = context;
}
public int getCount() {
return mObjects;.size();
}
public Object getItem( int position ) {
return mObjects;.get(position);
}
public long getItemId( int position ) {
return position;
}
public void addObject( Object obj) {
obj.setId(mNumObjs);
mObjects.add( obj );
(mNumObjs);++;
notifyDataSetChanged();
}
public void deleteObject( int pos ) {
mObjects;.remove( pos );
notifyDataSetChanged();
}
public View getView( final int position, View convertView, ViewGroup parent ) {
final TimerView holder;
if( convertView == null ) {
convertView = mLayoutInflater.inflate( R.layout.customlistview, null );
holder = new HolderView();
holder.mListPosition = position;
holder.mDeleteButton = (Button)convertView.findViewById(R.id.Delete);
holder.mDeleteButton.setText( "Button No: " + position );
holder.mDeleteButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteObject(holder.mListPosition);
}
});
holder.mButton = (Button)convertView.findViewById(R.id.Button);
holder.mButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Object obj = mObjects.get(holder.mListPosition);
mTitleText.setText(obj.getNum());
}
});
convertView.setTag(holder);
}
else {
holder = (TimerView) convertView.getTag();
}
holder.mListPosition = position;
holder.mDeleteButton.setText( "Button No: " + position );
return convertView;
}
class HolderView{
int mListPosition;
Button mDeleteButton;
Button mButton;
TextView mTitleText;
}
}
Okay I managed to figure this out myself, if your updates don't need to be very frequent ( >1 sec ) you can use notifyDataSetChanged() however if like me you need to constantly update the listview every 200ms or so you need to iterate through the visible objects on the list view and update it.
private Runnable showUpdate = new Runnable(){
public void run(){
mAdapter.updateList();
//mAdapter.notifyDataSetChanged();
int count = mListView.getCount();
for( int i = 0; i < count; i ++ )
{
View convertView = mListView.getChildAt( i );
if( convertView != null )
{
HolderView holder = (HolderView) convertView.getTag();
Object obj = (Object)mAdapter.getItem( holder.mListPosition );
holder.mTitleText.setText( obj.getText() );
}
}
}
};
Thread mThread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(100);
mHandler.post(showUpdate);
//mHandler.sendEmptyMessage(MSG_UPDATE);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Update the text in your list mObjects and call notifyDataSetChanged() on your adapter.