I am working in Android Technology.In my application i am fetching the data from web service i used A sync Task for consuming web service.It show the data correctly on Toast i.e true or false but My Progress Bar is continuously moving it does not stopped when Background task completed its execution i called dismiss method in onPostExecute().But it failed to dismiss the progress bar.Again it start calling web service but progress bar is not dismmed.
Can you tell me what i did wrong in my code.Please solve my problem..
I am attaching source code here
Async task
public class MyTask extends AsyncTask<String,Void,String>
{
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
Toast.makeText(getApplicationContext(), ""+result,Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("Please Wait");
pd.setCancelable(false);
pd.setIndeterminate(false);
pd.show();
}
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
v=new Validate();
String result;
result=v.SendParam(url,user,pass);
return result;
}
}
Here id Validate.java code
class Validate
{
ArrayList<NameValuePair> namevaluepair;
InputStream is;
String res;
public String SendParam(String url,String username,String password)
{
try
{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
// add parameter here
namevaluepair=new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("id",username));
namevaluepair.add(new BasicNameValuePair("password",password));
post.setEntity(new UrlEncodedFormEntity(namevaluepair));
HttpResponse response=client.execute(post);
HttpEntity entity=response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
Log.d("Httpconnection","error",e);
}
// read response from
try
{
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder builder=new StringBuilder();
String line;
while((line=reader.readLine())!=null)
{
builder.append(line+"\n");
}
is.close();
res=builder.toString();
}
catch(Exception e)
{
Log.d("reading Input Stream","",e);
}
return res;
}
}
Your code should work fine (the dialog should be dismissed without problems).
However I'm guessing your sendParam method is throwing an error, and so the onPostExecute method is not reached. Replace doInBackground with this in your code :
#Override
protected String doInBackground(String... arg0) {
try {
v=new Validate();
String result;
result=v.SendParam(url,user,pass);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
super.onPostExecute(result);
Try to remove this and execute. hope it works.
Related
I am trying to use pagination in an android project.There are 60 pieces of data which i want to display 10 at a time in a listview.But the problem is i am getting duplicates in the list that loads, i.e the first 10 are followed by the same 10 again:
The code:
public class VideoActivity extends Activity {
private ConnectionDetector cd;
public HttpResponse video_respons;
public String video_string_response1;
public ArrayList<NameValuePair> nameValuePairs_Video;
ArrayList<Ice_data> ice_list;
String URL="http://footballultimate.com/icebucket/index.php/api/getVideo";
String URL1="http://footballultimate.com/icebucket/index.php/api/getVideoByLimit";
JSONObject jsonobj;
JSONArray jsonarr;
Ice_data iceobj;
CustomIceAdapter ciadp;
ListView list;
int start = 1;
int limit = 10;
boolean loadingMore = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
ice_list=new ArrayList<Ice_data>();
// GEt all Data for Video
cd = new ConnectionDetector(VideoActivity.this);
Config.isInternetPresent = cd.isConnectingToInternet();
if (!Config.isInternetPresent) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
// Shuld be fail icon
builder.setIcon(R.drawable.ic_launcher);
builder.setMessage("Connection Not Available !" + "\n"
+ "Please enable your Internet Connection");
builder.setTitle("INTERNET CONNECTION");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
new GetVideos().execute();
}
// Get all Data for Video
list= (ListView) findViewById(R.id.videoList);
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new GetVideos().execute();
}
}
});
}
class GetVideos extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
private HttpResponse vip_respons;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(VideoActivity.this);
pDialog.setTitle("Processing...");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
loadingMore = true;
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("start",String.valueOf(start)));
nameValuePairs.add(new BasicNameValuePair("limit",String.valueOf(limit)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
video_respons = httpclient.execute(httppost);
//video_string_response1 = getResponseBody(video_respons);
video_string_response1=responsetostring.getResponseBody(video_respons);
//Log.d("Store_Response", the_string_response1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String video_string) {
try{
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
pDialog.dismiss();
}
if (video_string_response1!=null) {
//displayjsonstring();
geticevalues(video_string_response1);
}
}
}
public void geticevalues(String result)
{
try {
jsonobj=new JSONObject(result);
//ice_list=new ArrayList<Ice_data>();
jsonarr=jsonobj.getJSONArray("video_data");
for(int i=0;i<jsonarr.length();i++)
{
JSONObject jso=jsonarr.getJSONObject(i);
iceobj=new Ice_data();
iceobj.title=jso.getString("title");
iceobj.image_URL=jso.getString("image");
iceobj.video_URL=jso.getString("url");
ice_list.add(iceobj);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ciadp=new CustomIceAdapter(VideoActivity.this,ice_list);
ciadp.notifyDataSetChanged();
loadingMore = false;
list.setAdapter(ciadp);
start+=10;
}
The start and limit are the values which show the starting and the number of items in each request.I have also increamented the start value as start+=10.I am passing the start and limit values to the webservice in the async class.
Is there a more elegant way to do the above?Or can you fix the above code.Please help!!
initialization of ice_list inside doInBackground will eliminate duplicates
protected String doInBackground(String... arg0) {
loadingMore = true;
ice_list=new ArrayList<Ice_data>();
// TODO Auto-generated method stub
try {......................
I am creating a page in Android that gets ID & Name and then inserts it to my database but I get this error in logcat.
error in logcat is:
pass 1(854): connection success
pass2(854): connection success
fail 3(854): java.lang.NullPointerException
my code is:
public class Sampleactivity extends Activity {
String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainprogram);
final EditText e_id=(EditText) findViewById(R.id.editText1);
final EditText e_name=(EditText) findViewById(R.id.editText2);
Button insert=(Button) findViewById(R.id.button1);
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
id=e_id.getText().toString();
name=e_name.getText().toString();
insert();
}
});
}
public void insert()
{
ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", id));
nameValuePairs.add(new BasicNameValuePair("name", name));
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://10.0.2.2/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
Log.e("pass 1","connection success");
}
catch(Exception e)
{
Log.e("fail 1",e.toString());
Toast.makeText(getApplicationContext(), "invalid ip address",Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader=new BufferedReader
(new InputStreamReader(is, "iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
{
sb.append(line + "\n");
}
is.close();
String result=sb.toString();
Log.e("pass2","connection success");
}
catch(Exception e)
{
Log.e("fail2",e.toString());
}
try
{
JSONParser parser_obj=new JSONParser();
JSONArray jsonArray=(JSONArray)parser_obj.parse(result);
JSONObject json_data=new JSONObject();
for(int i=0;i<jsonArray.length();i++)
{
json_data=jsonArray.getJSONObject(i);
}
code=json_data.getInt("code");
if(code==1)
{
Toast.makeText(getApplicationContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "sorry try again",Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("fail 3",e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.activity_mainprogram, menu);
return true;
}
}
I don't know the NPE was thrown. Any ideas ?
Please use e.getStackTrace() in your catchs and NOT e.toString() !, so you'll know where exactly the NPE is thrown. (And eventually, edit your initial post to include the full stacktrace)
From what I see here, the NPE has a lot of chances to come from
JSONArray jsonArray = (JSONArray)parser_obj.parse(result); // right operand probably returns null
json_data = jsonArray.getJSONObject(i); // NPE is thrown
So, you've got to check if jsonArray is null, before using it. If I'm right, you will so have to check what's going on in result.
I khow what is problem
the problem is in directory of php file
I used xampp and in htdocs ,I make folder and put php file in it,but its not true and then put this code
> HttpPost httppost=new HttpPost("http://10.0.2.2/insert.php");
I put php file in htdocs and make true
thanks and sorry about my problem
Semi-noob with Java here.
I am trying to set a TextView inside my doInBackground() inside of my Async task. According to my research, I can not modify the main thread doing this so messing around with TextViews is out of the question here. So what I would like to do instead is use a string. I need this string to be accessible in the main class.
How can I do this?
I tried String loginresult = "Login Successful! Please Wait..."; but I am not able to access that string anywhere. I tried marking it as public but that is an illegal modifier inside a doInBackground().
Maybe strings is not the best way to go about doing this, if so, what would all you geniuses out there suggest?
Here is my async code, I put arrows in the areas I am having an issue. Any help would be appreciated for this noob :)
class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
//Executes link, login.php returns true if username and password match in db
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
-----> result.setText("Login Successful! Please Wait...");
}else
{
Log.w("SENCIDE", "FALSE");
------> result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "All Done!";
}//end doinbackground
StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}//end StringBuilder
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// turns the text in the textview "Tbl_result" into a text string called "tblresult"
TextView tblresult = (TextView) findViewById(R.id.tbl_result);
// If "tblresult" text string matches the string "Login Successful! Please Wait..." exactly, it will switch to next activity
if (tblresult.getText().toString().equals("Login Successful! Please Wait...")) {
Intent intent = new Intent(NewAndroidLogin.this, Homepage.class);
//take text in the username/password text boxes and put them into an extra and push to next activity
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
EditText pword2 = (EditText)findViewById(R.id.txt_password);
String password2 = pword2.getText().toString();
intent.putExtra("username2", username2 + "&pword=" + password2);
startActivity(intent);
}
}//end onPostExecute
}//end async task
Change your AsyncTask to use String as progress parameter type:
AsyncTask<String, String, String>
Change onProgressUpdate() to update progress
#Override
protected void onProgressUpdate(String... values) {
result.setText(values[0]);
}
And then report the progress:
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
publishProgress("Login Successful! Please Wait...");
}else
{
Log.w("SENCIDE", "FALSE");
publishProgress(str);
}
Make String loginresult = "Login Successful! Please Wait..."; as global and
runOnUiThread(new Runnable() {
#Override
public void run() {
str = inputStreamToString(response.getEntity().getContent()).toString();
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
result.setText("Login Successful! Please Wait...");
}
else
{
Log.w("SENCIDE", "FALSE");
result.setText(str);
}
}
} );
Declare Handler at class level:
Handler handler;
Initialize Handler in onCreate() method of Activity:
// Doing this inside the onCreate() method of Activity
// will help the handler to hold the reference to this Activity.
handler = new Handler();
Call it within the background thread:
#Override
protected String doInBackground(String... params) {
handler.post(new Runnable(){
public void run(){
// SET UI COMPONENTS FROM HERE.
}
});
}
Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
try {
HttpResponse response = httpclient
.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
});
}
});
}
i'am getting NetworkOnMainThreadException. I think the problem is in the httppost, but i couldn't figure it out.
This exception is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Run your code in AsyncTask:
// use async task like this .this will solve ur problem
Class A{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
new RequestLogInFromServer().execute();
}
});
}
});
}
public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
{
#Override
protected Object doInBackground(Object... params)
{
String responsearray[] = new String[2];
//JSONObject jsonResponse = null;
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://shopstable.turkcell.com.tr/timme/getPerosConfig.do");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
// Add your data
in case if u want to pass any data to server else leave it
List<NameValuePair> signinDetails = new ArrayList<NameValuePair>();
signinDetails.add(new BasicNameValuePair("name",uname));
signinDetails.add(new BasicNameValuePair("pass",pwd));
httpPost.setEntity(new UrlEncodedFormEntity(signinDetails));
// Execute HTTP Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("Post Status", "Code: "
+ httpResponse.getStatusLine().getStatusCode());
responseCode = httpResponse.getStatusLine().getStatusCode();
Log.e("responseBody", String.valueOf(responseCode));
responsearray[0]=String.valueOf(responseCode);
switch(responseCode){
case 200:
Log.e("responseCode", String.valueOf(responseCode));
HttpEntity entity = httpResponse.getEntity();
Log.e("entity", String.valueOf(entity));
if (entity != null) {
responsearray[1] = EntityUtils.toString(entity);
Log.e("responsearray", String.valueOf(responsearray));
/* Log.e("responseBody", String.valueOf(responseBody));
JSONTokener jsonTokener = new JSONTokener(responseBody);
jsonResponse = new JSONObject(jsonTokener);
Log.e("finalResult", String.valueOf(jsonResponse));
JSONObject response = jsonResponse.getJSONObject("response");
// Getting String inside response object
String status = response.getString("status");
String message = response.getString("message");
Log.e("status", String.valueOf(status));
Log.e("message", String.valueOf(message));
*/
} // if (entity != null) end
break;
case 503:
responsearray[1]="";
break;
default:
responsearray[1]="";
break;
}//switch end
} catch (ClientProtocolException cpeExp) {
// TODO Auto-generated catch block
} catch (Exception allExp) {
// TODO Auto-generated catch block
}
return responsearray;
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
super.onPreExecute();
}
}
} //close class A
you have simply use this so get solution:
Here SDK version is your app's minimum sdk version ..so you have to set your minimum sdk version here. And put this code after onCreate() method:
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
And also add this permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I'm getting strings from a HttpGet and I want to place them into the listview. How could I do this? I can't find any information on it anywhere. At the movement, I just have some test data in place.
Eg.
"Test1"
But I want it to be dynamic, from the strings the phone get's from the HttpGet.
Thanks.
My Code so far: (Apologies for the code being messy, I'll rewrite it soon!)
public class ChatService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
try {
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CheckLogin();
ListView list = (ListView) findViewById(R.id.ListView01);
list.setClickable(true);
final List<PhoneBook> listOfPhonebook = new ArrayList<PhoneBook>();
listOfPhonebook.add(new PhoneBook("a", "9981728", "test#test.com"));
listOfPhonebook
.add(new PhoneBook("Test1", "1234455", "test1#test.com"));
listOfPhonebook.add(new PhoneBook("Test2", "00000", "test2#test.com"));
PhonebookAdapter adapter = new PhonebookAdapter(this, listOfPhonebook);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int position, long index) {
System.out.println("sadsfsf");
showToast(listOfPhonebook.get(position).getName());
}
});
list.setAdapter(adapter);
}
private void CheckLogin() {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//put intent here(21/3/12);
} else {
Log.w("HttpPost", "FALSE");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//now we'll return the data that the PHP set from the MySQL Database.
// just some test code, to see if the HttpGet was working.
if (in.equals("True")); {
Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
}
}
// end bracket for "ContactsandIm"
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
From the code, i see that PhonebookAdapter is your custom adapter class. Why not parse the http response of type PhoneBook and add it to listOfPhonebook. That should show the parsed contents in the listView.
As I understand you need to add new PhoneBook entry every time your Http request is succeeded.
If so, you have to options to make everything dynamic:
Recreate adapter every time you receive new portion of data:
Make your listView global variable (to make it accessible from any function within the class)
Do the same with your List
Once you have received new portion of data - add this data to your List, create new adapter and set this adapter to your ListView
Create a custom adapter with possibility to update ListItems:
public class YourCustomAdapter extends BaseAdapter
{
private final LayoutInflater inflater;
private ArrayList list = new ArrayList();
private Handler uiHandler = new Handler();
/*..... default set of functions from BaseAdapter ......*/
public void setList(ArrayList<PhoneBook> list)
{
this.list = list;
}
public void addEntry(final PhoneBook entry)
{
uiHandler.post(new Runnable()
{
#Override
public void run()
{
list.add(entry);
YourCustomAdapter.notifyDataSetChanged();
}
});
}
}
please note that in this case you are allowed to modify underlying list ONLY from UI thread
Hope this helps