RSS reader unit testing - android

Build a android simple RSS reader application ,I have simple class "ReaderAppActivity" which use onCreate method as following to parsing a particular RSS site
public class ReaderAppActivity extends Activity {
/**
* This method creates main application view
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
setContentView(R.layout.main);
try {
// Create RSS reader
RssReader rssReader = new RssReader("http://rss.cnn.com/rss/edition.rss");
// Get a ListView from main view
ListView itcItems = (ListView) findViewById(R.id.listMainView);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());
// Set list adapter for the ListView
itcItems.setAdapter(adapter);
// Set list view item click listener
itcItems.setOnItemClickListener(new ListListener(rssReader.getItems(), this));
} catch (Exception e) {
Log.e("Reader", e.getMessage());
}
}
Now want to develop a Junit testing really don't understand on
1) which parameter I should taste my app ? for example assertest, timeout
2) For internet base project is there any unit testing tutorial for beginners ?

You need to read this:
https://developer.android.com/training/testing/start/index.html
https://developer.android.com/studio/test/index.html
In the manuals you find answers for your questions. Also it will help to you to understand what you need to test (1st question).

Related

ParseQueryAdapter; using class in Android

I feel like a broken record.
After many attempts, I have failed at getting a listview through Parse data to display a specific set of information.
Here is my model...this is all data from users:
#ParseClassName("Midwifefirm")
public class Midwifefirm extends ParseObject {
public Midwifefirm() {
// A default constructor is required.
}
//practice name
public String getPracticeName() {
return getString("practicename");
}
public void setPracticeName(String practicename) {
put("practicename", practicename);
}
//education
public String getEducation() {
return getString("education");
}
public void setEducation(String education) {
put("education", education);
}
//years in practice
public String getYearsinPractice() {
return getString("yearsinpractice");
}
public void setYearsinPractice(String yearsinpractice) {
put("yearsinpractice", yearsinpractice);
}
//practice philosophy
public String getPracticePhilosophy() {
return getString("practicephilosophy");
}
public void setPracticePhilosophy(String practicephilosophy) {
put("practicephilosophy", practicephilosophy);
}
I have this adapter; I am wondering what to place in the query section, as I just want to pull the data into the ListView that is defined in the data model:
public class CustomMidwifeAdapter extends ParseQueryAdapter<Midwifefirm> {
public CustomMidwifeAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<Midwifefirm>() {
public ParseQuery<Midwifefirm> create() {
// Here we can configure a ParseQuery to display
// only top-rated meals.
ParseQuery query = new ParseQuery("Midwives");
return query;
}
});
}
#Override
public View getItemView(Midwifefirm midwifefirm, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.activity_midwife_result_list, null);
}
//use midwifefirm as item view/list
super.getItemView(midwifefirm, view, parent);
// find in layout the practice name
TextView titleTextView = (TextView) view.findViewById(R.id.practicename);
//in the midwifefirm data model, call getPracticename
titleTextView.setText(midwifefirm.getString("practicename"));
// Add education view
TextView EducationView = (TextView) view.findViewById(R.id.education);
EducationView.setText(midwifefirm.getString("education"));
// Add yearsexperience view
TextView ExperienceView = (TextView) view.findViewById(R.id.yearsinpractice);
ExperienceView.setText(midwifefirm.getString("yearsinpractice"));
//Add practice philosophy view
TextView PracticePhilosophyView = (TextView) view.findViewById(R.id.practicephilosophy);
PracticePhilosophyView.setText(midwifefirm.getString("practicephilosophy"));
return view;
}
}
And here is the Main Activity:
public class MidwifeResultList extends ListActivity {
private ParseQueryAdapter<ParseObject> mainAdapter;
private CustomMidwifeAdapter midwifeListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialize main ParseQueryAdapter
mainAdapter = new ParseQueryAdapter<ParseObject>(this, Midwifefirm.class);
//which keys in Midwife object
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
// Initialize the subclass of ParseQueryAdapter
midwifeListAdapter = new CustomMidwifeAdapter(this);
// Default view is all meals
setListAdapter(mainAdapter);
}
Every time I run this, I get no results.
Thanks in advance for any help
Michael
I can tell you why I think it fails now and I can tell you why I'm very sure it will fail after you sort out the current issue.
It seems that you're trying to use different classes
#ParseClassName("Midwifefirm")
public class Midwifefirm extends ParseObject {
and
ParseQuery query = new ParseQuery("Midwives");
You need to be consistent and use the same name. Either use Midwives or Midwifefirm for both. Let's assume you picked the latter. You're also saying
all that is stored in the user table...wasn't sure if I needed to create new tables.
The query above wants to get all entries of type Midwives. If there's no such type, it'll return nothing. So you have two options:
In you Parse dashboard, reate a class Midwifefirm (don't forget to update the String inside #ParseClassName above) and store your Midwifefirm data in there. You don't need to change your query for this.
Add a column to your ParseUser class, such as type, that you can set to Midwifefirm or whatever if that user is a Midwifefirm or whatever. Then in your query you need to add:
ParseQuery query = new ParseQuery("Midwives");
query.whereEquals("type", "Midwifefirm");
I greatly prefer the former.
Anyway, once your done that, the issue is that you're not using a custom view for this. You're relying on the one provided by Android by default for ListActivity. I am fairly sure it doesn't have any of the fields you're after, so you should create a custom view for this, then at the top of onCreate in your Activity make sure you use it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_custom_view);
By the way, the following are redundant if you populate then in getItemView anyway:
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
One final advice: if you're still having issues, set breakpoints and do some investigations first. What you need to check is:
Whether you get anything at all from Parse when you do your query. Your adapter has an useful addOnQueryLoadListener that you may use to check whether anything's been retrieved at all.
If stuff is retrieved successfully, you need to check whether the list view is populated correctly. Again, use breakpoints, this time in getItemView maybe.
I'm going to do a wild guess here using the lovely brainwrecking API help of Parse.com about ParseQueryAdapters
Before continuing, may I mind you that my experience with ParseQueryAdapters is a minimum but I think I have a basic knowledge about them + I have some experience with Parse on its own. ANYHOW,
As an example they use both these
final ParseQueryAdapter adapter = new ParseQueryAdapter(this, "Midwives");
adapter.setTextKey("name");
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
and
// Instantiate a QueryFactory to define the ParseQuery to be used for fetching items in this
// Adapter.
ParseQueryAdapter.QueryFactory<ParseObject> factory =
new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Midwives");
return query;
}
};
// Pass the factory into the ParseQueryAdapter's constructor.
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(this, factory);
adapter.setTextKey("name");
// Perhaps set a callback to be fired upon successful loading of a new set of ParseObjects.
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
public void onLoading() {
// Trigger any "loading" UI
}
public void onLoaded(List<ParseObject> objects, ParseException e) {
// Execute any post-loading logic, hide "loading" UI
}
});
// Attach it to your ListView, as in the example above
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
To start of, the reason why I think nothing is loading inside your list has to do with a little mixup between the initilization of your ParseQueryAdapter and your custom adapter.
You configure the basic adapter, and also initialize a custom adapter but you don't do anything with the custom adapter, tho the custom adapter seems to contain the logics to load your data model.
I think what you're looking for is something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialize main ParseQueryAdapter
mainAdapter = new CustomMidwifeAdapter<ParseObject>(this);
//which keys in Midwife object
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
// Default view is all meals
setListAdapter(mainAdapter);
}
All you need to pass is the context (aka "this"), and the constructor of your custom class will handle the factory internal
super(context, new ParseQueryAdapter.QueryFactory<Midwifefirm>() {
public ParseQuery<Midwifefirm> create() {
// Here we can configure a ParseQuery to display
// only top-rated meals.
ParseQuery query = new ParseQuery("Midwives");
return query;
}
});
Tho to be honest since you do:
new ParseQueryAdapter<ParseObject>(this, Midwifefirm.class);
I wonder if you'd need to change your "QueryFactory" to
super(context, new ParseQueryAdapter.QueryFactory<Midwifefirm>() {
public ParseQuery<Midwifefirm> create() {
// Here we can configure a ParseQuery to display
// only top-rated meals.
ParseQuery query = new ParseQuery(MidWifefirm.class);
return query;
}
});
Where you pass a class to the the query rather than the tableName, but I could be wrong on that one.
Either way I hope this has helped in some way!

How to test a ListActivity with test data?

I'm writing tests for a simple Android application (it's a school project) and I'm having trouble testing the activity ContactListActivity which extends Android's ListActivity.
What I would like to test
Clicking the first item in ContactListActivity's ListView and checking if the ContactDetailActivity was started.
Problem
The list data comes from an SQLite database. For testing, I'm loading test data into the ListView, so the test won't be working with live data. Loading the test data works fine. Watching the emulator while running the test, I can see the activity being started and the test data appearing in the list. However, trying to access the first (and only) list item fails.
Test method
#UiThreadTest
public final void testLoadContactDetail() {
ListView list = activity.getListView();
assertNotNull(list);
ContactsListAdapter adapter = new ContactsListAdapter(
getInstrumentation().getContext(),
createData() // Creates an ArrayList of test data
);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
// list.getAdapter().getCount() is expectedly 1
// list.getChildCount() is unexpectedly 0
assertNotNull(list.getChildAt(0)); // Assertion fails
// (...)
}
As can be seen, I'm annotating the test with #UIThreadTest to be able to manipulate view elements. A new ListAdapter is created with test data and set to the list. Then, adapter.notifyDataSetChanged() makes sure that the list knows about the new data.
Question
How can I load test data from within an ActivityInstrumentationTestCase2 into a ListView so that the data will not only be displayed on screen, but actually "be there", meaning the list item can be fetched with list.getChildAt(0) and be clicked?
Entire test case
public class ContactListActivityFunctionalTest extends
ActivityInstrumentationTestCase2<ContactListActivity> {
private ContactListActivity activity;
public ContactListActivityFunctionalTest() {
super(ContactListActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
activity = getActivity();
}
protected void tearDown() throws Exception {
super.tearDown();
}
#UiThreadTest
public final void testLoadContactDetail() {
ListView list = activity.getListView();
assertNotNull(list);
ContactsListAdapter adapter = new ContactsListAdapter(
getInstrumentation().getContext(),
createData()
);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
assertNotNull(list.getChildAt(0));
// Anything beyond this point is never executed,
// because the above assertion fails, and I have no idea
// if this test code is correct at all.
ActivityMonitor monitor = getInstrumentation().addMonitor(
ContactDetailActivity.class.getName(), null, false
);
TouchUtils.clickView(this, list.getChildAt(0));
ContactDetailActivity contactDetailActivity =
(ContactDetailActivity)monitor.waitForActivityWithTimeout(2000);
assertNotNull(contactDetailActivity);
assertTrue(getInstrumentation().checkMonitorHit(monitor, 1));
contactDetailActivity.finish();
}
private List<ContactInterface> createData() {
ContactInterface contact = new Contact();
contact.setId(1L);
contact.setName("Unit Test").setPhone("0123456789").setPosition(3);
List<ContactInterface> contacts = new ArrayList<ContactInterface>();
contacts.add(contact);
return contacts;
}
}
It looks like the listView.getChildAt method returns visible views. https://stackoverflow.com/a/6767006/693752
So, my guess is that the item is not visible yet. None are as getChildCount is returning 0. Maybe you should either :
wait a bit before asserting. Ok, it's dirty but UI testing needs it sometime.
post the assert inside a runnable on the ui thread so that it gets executed after the listview is executed. This will turn your test into something a bit more complex as you would have to synchronize the future runnable and the current testing thread a countDownLatch. And for this, you should consider not using #UIThreadTest.
I know I've asked how to load test data from within an ActivityInstrumentationTestCase2, but perhaps the answer to the question is to use ActivityUnitTestCase rather than ActivityInstrumentationTestCase2 in this particular case:
General activity behaviour is being tested, rather than interaction with other components
Well, it works...
Here is the rewritten, working test case that tests whether the ListView exists and whether the correct activity is started after a click on the list's first item.
public class ContactListActivityTest
extends ActivityUnitTestCase<ContactListActivity> {
private ContactListActivity activity;
public ContactListActivityTest() {
super(ContactListActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
Intent intent = new Intent(
getInstrumentation().getTargetContext(), ContactListActivity.class
);
startActivity(intent, null, null);
activity = getActivity();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testItemClick() {
getInstrumentation().callActivityOnStart(activity);
getInstrumentation().callActivityOnResume(activity);
// Check if list exists
ListView list = activity.getListView();
assertNotNull("Intent was null", list);
// Load test data
ContactsListAdapter adapter = new ContactsListAdapter(
getInstrumentation().getContext(),
createData()
);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
assertEquals(2, adapter.getCount());
// Check if list has at least one item to click
View firstItem = list.getAdapter().getView(0, null, null);
assertNotNull(firstItem);
// Perform a click on the first item
list.performItemClick(
firstItem,
0,
list.getAdapter().getItemId(0)
);
// Check if the contact details activity got started
Intent intent = getStartedActivityIntent();
assertNotNull(intent);
assertEquals(
ContactDetailActivity.class.getName(),
intent.getComponent().getClassName()
);
}
private List<ContactInterface> createData() {
List<ContactInterface> contacts = new ArrayList<ContactInterface>();
ContactInterface contact = new Contact();
contact.setId(1L);
contact.setName("Jane Doe").setPhone("0123456789").setPosition(1);
contacts.add(contact);
ContactInterface contact2 = new Contact();
contact2.setId(2L);
contact2.setName("John Doe").setPhone("0234567890").setPosition(2);
contacts.add(contact2);
return contacts;
}
}

Android: notifyDataSetChanged(); not working

I have a database in a server and from a Tablet I take some values from one table in the database. I load this information correctly into a list but I would like to know why when there is a change, nothing happens even if I use notifyDataSetChanged();. I must say that for loading the loading data y use the AsyncTaskClass
So, my problem is that I don't know if use the notifyDataSetChanged(); method correctly ,because if there's is a change I would like to refresh the image. Here is some part of the code of the class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
candidatosList = new ArrayList<HashMap<String, String>>();
new CargarCandidatos().execute();
}
// public void timer(){
// new CountDownTimer(tiempo, 100) {
//
// public void onTick(long millisUntilFinished) {
//
// }
//
// public void onFinish() {
// // new CargarCandidatos().execute();
//
// }
// }.start();}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class CargarCandidatos extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Monitorizacion.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_candidatos, "GET", params);
Log.d("Candidatos: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
candidatos = json.getJSONArray(TAG_CANDIDATOS);
for (int i = 0; i < candidatos.length(); i++) {
JSONObject c = candidatos.getJSONObject(i);
// Storing each json item in variable
String nserie = c.getString(TAG_NSERIE);
String dni = c.getString(TAG_DNI);
String nombre = c.getString(TAG_NOMBRE);
String test = c.getString(TAG_TEST);
String pregunta = c.getString(TAG_PREGUNTA);
String bateria = c.getString(TAG_BATERIA);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NSERIE, nserie);
map.put(TAG_DNI, dni);
map.put(TAG_NOMBRE, nombre);
map.put(TAG_TEST, test);
map.put(TAG_PREGUNTA, pregunta);
map.put(TAG_BATERIA, bateria);
// adding HashList to ArrayList
candidatosList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_NSERIE,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA},
new int[] { R.id.id, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria});
setListAdapter(adapter);
adapter.notifyDataSetChanged();
// timer();
}
});
}
}
}
One of the main reasons notifyDataSetChanged() won't work for you - is,
Your adapter loses reference to your list.
When you first initialize the Adapter it takes a reference of your arrayList and passes it to its superclass. But if you reinitialize your existing arrayList it loses the reference, and hence, the communication channel with Adapter.
When creating and adding a new list to the Adapter. Always follow these guidelines:
Initialise the arrayList while declaring it globally.
Add the List to the adapter directly without checking for null and empty values. Set the adapter to the list directly (don't check for any condition). Adapter guarantees you that wherever you make changes to the data of the arrayList it will take care of it, but never
lose the reference.
Always modify the data in the arrayList itself (if your data is completely new then you can call adapter.clear() and arrayList.clear() before actually adding data to the list) but don't set the adapter i.e If the new data is populated in the arrayList than just adapter.notifyDataSetChanged()
Stay true to the Documentation.
The thing you need to edit is put your
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_NSERIE,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA},
new int[] { R.id.id, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria});
setListAdapter(adapter);
adapter.notifyDataSetChanged();
// timer();
}
});
into the OnCreate(). and return the list candidatosList from Asynctask. than set timer for updating candidatosList list.
It might be worth checking if you have an empty override for registerDataSetObserver(). Android Studio added one for me without implementing the call to super. Adding it in as follows was enough to get my listView working again:
#Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
An adapter define the comportement of the layout !
-> setListAdapter() : Define the adapter for a ListView/GridView/Gallery...
but you need to specify the data !
I recommend to you, to initialize 'setListAdapter' in the 'onCreate' or in the constructor.
After you set the data into the adapter (exemple : adapter.setItem(yourData))
And NOW ! You should to call notifyDataSetChanged !
Because you have changed the data but the view isn't refresh and notifydatasetchanged() reload the content of the view (ListView/GridView/Gallery...)
For a good practice and understand correctly I recommend to you to use a 'custom adapter' using 'baseAdapter'
Read and do this tutorial (I haver learn with this): http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Read the documentation : http://developer.android.com/reference/android/widget/BaseAdapter.html
The update function should be called from UI thread.
My answer is actually similar to #user1621629's answer with that difference that I am using rxJava, so here's working code that solve this problem for me:
this.subscriber = myAdapter.getSubscriber(); // keep for unsubscribe in destroy
dataSource.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(this.subscriber);
So I set all execution in order to get data for the list to computation thread, but showing result in UI thread.
Here's how I create subscriber for this:
public class MyListAdapter extends RecyclerView.Adapter<LocationListAdapter.ViewHolder> {
private List<ListItem> mDataset = new ArrayList<>();
public Subscriber<ListItem[]> getSubscriber() {
return Subscribers.create(new Action1<ListItem[]>() {
#Override
public void call(ListItem[] listItems) {
mDataset.clear();
mDataset.addAll(Arrays.asList(listItems));
notifyDataSetChanged();
}
});
}
......
As Hissain describes above,
you need to maintain a reference to the list
Here's how I got it to work:
Let the list being sent to the adapter be set as an instance member in the activity
In the logic that performs a change to the data, make sure it updates the same list instance that the activity passed to the adapter
Then calling .notifyDataSetChanged(); worked
Remember that listView position starts at 1, so you will have to do (listViewPosition - 1) for your your java.util.List
I dont have much reputation to comment on Mr. Hissain answer.It is correct but I want to mention one more thing that reference to the list should not change. If data source underlying is changing, dont change the reference to new list. Actions only need to be done on the same list object. To do the same,clear the list using clear() and then add data to the same list using add() or addALL() and then call notifyDataSetChanged(). eg.
On first initialization of the list
list = dataSource.getList();
then one can add and remove the content from the list and call notifyDataSetChanged() it works fine but if in the code, one tries to change the reference to the other object. Like
list = dataSource.getList();
where getList() returns the new list everytime, hence the reference changes to some other list object and calling notifyDataSetChnaged does not have impact on the list.But if getList() returns the same list object, it works fine.
If everything you set fine and still not working then your list...
Is it Mutablekind of the List or not...!
private val demoList: MutableList<AnyClass> = mutableListOf()
once you define your list like above mutable manner then you can get the method
.add
.addAll
.remove
etc...
else if you have created normal list then that will not work as notifyDataSetChanged

how to append latest data to custom base adapter list view in android?

I have implemented an application with Custom base adapter for display data in list view.In my application i have displayed some content to list view by using Custom base adapter that content will come from web service.I have used a button for get the latest data from service.when i get the latest data from service then i would like to append the latest data to list view at bottom without deleting previous data in list view.
I have implemented my application as follows:
result = new ParseXml().convertMessages(new Model().getMessages("0"));
count = Integer.parseInt(result.get(0).getMessageID());
((Button)findViewById(R.id.oldMessagesButton)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fetchNewMessages();
}
});
protected void fetchOldMessages() {
// TODO Auto-generated method stub
waitProgreess = ProgressDialog.show(this, "Please wait", "Loading...");
new Thread() {
public void run() {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
}
newmessageHandler.sendEmptyMessage(0);
}
}.start();
}
private Handler newmessageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.v("000000", "count :"+count);
if(count>0){
newmsgResult = new ParseXml().convertMessages(new Model().getNewMessages(""+count));
CustomeAdapter adapter = new CustomeAdapter(GetMsgsScreen.this,newmsgResult);
lst.setAdapter(adapter);
adapter.notifyDataSetChanged();
count=Integer.parseInt(newmsgResult.get(oldmsgResult.size()-1).getMessageID());
}
waitProgreess.dismiss();
}
};
I have implemented the above code based on user clicking on button count value will be send to service then get latest from service.When i get the latest list from servie the that list would like append to list view.
from the above code i can get only latest previous are deleting.
How can i append latest data(list) to listview in my above case?
please any body help me....
CustomeAdapter adapter = new CustomeAdapter(GetMsgsScreen.this,newmsgResult);
define this adapter andnewmsgResult at top of your class..not a local variable inside a class..
Now, whenever you want to update the data in list view, update the values/data in newmsgResult and call adapter.notifyDataSetChanged()
I think it is happening because you are creating a new custom adapter every time you are getting new messages.. in this line
CustomeAdapter adapter = new CustomeAdapter(GetMsgsScreen.this,newmsgResult);
dont do this and try to use adapter.add(Newmessage); you can use array list to make work easier
ok.. you should have an add function in your custom adapter class for that.. you can do so by adding this to your custom adapter class
private void customadd(String newmsg)
{
//ArrayList<String> msg=new List<String>; create this array list as a source to your adapter
msg.add(newmsg);
adapter.notifyDataSetChanged();
}
Initially load the your list view with customAdapter using result(By assumption result is arraylist)
CustomeAdapter adapter = new CustomeAdapter(GetMsgsScreen.this,result);
lst.setAdapter(adapter);
once you have new value no need to create new result and adapter object, simply append you result in your adapter object,
result.add("append your new result");
then simply adapter.notifyDataSetChanged();
Dont create a new adapter. Keep the original one and pass the new data to it for appending it.

Displaying object details in a ListView in Android

As part of an Activity, I have a class encapsulating functionality for a single object and want to display details of the object in a ListView when a particular button is pressed.
Attempt One:
If I pass the ListView and this to the object to store (!) and then try to call the ArrayAdapter, I get a runtime error:
Source not found
Code segment (method within the class)...
private void displayTouch(Touch lasttouch) {
String mLine = "";
/* Build up line of analysis */
...
/* Display line */
mAnalysis[lasttouch.mSequence] = mLine;
mViewAnalysis.setAdapter(new ArrayAdapter<String> (mActivity,R.layout.simplerow,mAnalysis));
} // End of method displayTouch
Attempt Two
If I try to display data in the ListView from within the OnClick Listener, I get an error message in Eclipse:
The constructor ArrayAdapter (new View.OnClickListener(){}, int, String[] is undefined.
Code segment (within the OnClick Listener of the Activity)...
/* Record details */
OnClickListener CourtListener = new OnClickListener() {
public void onClick(View v) {
...
/* Analyse */
...
/* Capture analysis */
lRoster.setAdapter(new ArrayAdapter<String> (this,R.layout.simplerow,playerArray));
} // End of event onClick
}; // End of listener CourtListener
In this code playerArray is dimensioned within the Activity's onCreate;
Both attempts have weaknesses of approach (in addition to not working) so I'll re-factor once I can get something working.
Essentially, how do I display data generated within an object to a ListView within an Activity from the OnClick Listener of another View in the same Activity? Everything is within one package and within the Activity.
Perhaps this blogpost might help: Putting custom objects in ListView

Categories

Resources