How to update listview when ever data is updated? - android

I am new in android, i want to update my list view when ever data is inserted in mysql database.I have searched in internet and i have used adapter.notifyDataSetChanged(); but i keep getting the error "The method notifyDataSetChanged() is undefined for the type ListAdapter"
Code:
public class Messages extends BaseActivity{
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_RESULTS="result";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "message_recd";
private static final String TAG_ADD ="message_sent";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
TextView textView = (TextView) findViewById(R.id.fname);
textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
editTextName = (EditText) findViewById(R.id.editTextName);
b=(Button)findViewById(R.id.button1);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etname=(EditText)findViewById(R.id.editTextName);
if( etname.getText().toString().trim().equals("")){
etname.setError( "Cannot be left empty!" );
}
// TODO Auto-generated method stub
else{
Intent intent = getIntent();
String fName = intent.getStringExtra("fname");
String message = etname.getText().toString();
insertToDatabase(message, fName);
}
etname.setText("");
}
});
}
//send messages start
private void insertToDatabase(String message, String fName1){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String fname = params[1];
//InputStream is = null;
String message = editTextName.getText().toString();
Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("message", message));
nameValuePairs.add(new BasicNameValuePair("username", fName));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/test/test.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//is = entity.getContent();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(message, fName1);
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
if(c.has("message_recd"))
name = c.getString("message_recd");
else
address = c.getString("message_sent");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
/*ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);*/
ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);
// http://www.vogella.com/tutorials/AndroidListView/article.html
// http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view
list.setAdapter(adapter);
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://10.0.2.2/progress_card/messages/get_messages.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}

The notifyDataSetChanged method is defined and implemented in BaseAdapter, the supertype of SimpleAdapter. So just add a cast to BaseAdapter or SimpleAdapter.

when you perfrom any add() or remove() operation to your personlist,
call adpater.notifyDataSetChanged(); method to Update ListView
Refernce : notifyDataSetChanged example

Related

Vertical Progress Bar on Android

I want to implement progress bar on list view for data that am getting from Mysql server here is my code any new suggestion are welcome for an example change your layout or anything which will make implementation easy as am neophyte
public class teststatusActivity extends BaseActivity {
String myJSON = "" ;
private static final String TAG_RESULTS = "result";
private static final String TAG_TICKET = "ticket_id";
private static final String TAG_Status = "ticket_status";
private static final String TAG_Status1 = "ticket_status1";
private static final String TAG_Status2 = "ticket_status2";
private static final String TAG_Status3 = "ticket_status3";
private static final String TAG_I = "";
public static final String DATA_URL = "http://103.3.62.23/complain_dashboard/api/getTicketStatus.php?ticket_id=";
public String ticketID;
JSONArray peoples = null;
ListView list;
ArrayList<HashMap<String, String>> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teststatus);
list = (ListView) findViewById(R.id.listView);
usersList = new ArrayList<HashMap<String, String>>();
getData();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONObject pe = jsonObj.getJSONObject(TAG_RESULTS);
String id = pe.getString("ticket_id");
String status = pe.getString("ticket_status");
String stat = null;
String stat1 = null;
String stat2 = null;
String stat3 = null;
if (pe.get("ticket_status").equals("0")) {
stat = "Feedback Sent To Team";
}
if (pe.get("ticket_status").equals("1")) {
stat1 = "Technical Team is Working on it";
}
if (pe.get("ticket_status").equals("2")) {
stat2 = "Your Report is About To Resolve";
}
if (pe.get("ticket_status").equals("3")) {
stat3 = "Resolved";
}
HashMap<String, String> users = new HashMap<String, String>();
users.put( TAG_TICKET , id );
users.put(TAG_Status, stat );
users.put(TAG_Status1, stat1 );
users.put(TAG_Status2, stat2);
users.put(TAG_Status3, stat3);
usersList.add(users);
ListAdapter adapter = new SimpleAdapter(
teststatusActivity.this, usersList, R.layout.list_item,
new String[]{TAG_TICKET, TAG_Status,TAG_Status1, TAG_Status2, TAG_Status3 },
new int[]{R.id.feed, R.id.feedS, R.id.feedwork, R.id.abouttoresolve, R.id.resolved}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
SharedPreferences sharedPref = getSharedPreferences("tcktid", Context.MODE_WORLD_READABLE);
final String ticket =sharedPref.getString("tid", null);
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(DATA_URL + ticket);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
} ;

How to refresh listview items once list items are updated - to be used in onResume

I have an update fragment using which i will update data in my database. Once the update is done i move back to 'view the data from database' fragment and i need the list to be updated. I think i have to write code for this inside onResume() but i don't know how to do it.
Code for 'view the data from database' fragment:
public class Testing extends Fragment {
String uname="921312104053";
private static final String TAG_RESULTS="result";
private static final String TAG_Sname = "Subject_name";
private static final String TAG_Scode = "Subject_code";
private static final String TAG_Sgrade ="Grade";
ListView lv;
JSONArray subjects = null;
String myJSON;
ListAdapter adapter;
ArrayList<HashMap<String, String>> subList,subList1;
public Testing() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_testing,
container, false);
disp(view);
return view;
}
public void disp(View view)
{
lv = (ListView)view.findViewById(R.id.list);
subList = new ArrayList<HashMap<String,String>>();
getData(view);
}
public void getData(View view){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.0.2.2/markolepsy/android_connect/testing.php?usrname="+uname);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
subjects = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<subjects.length();i++){
JSONObject c = subjects.getJSONObject(i);
String sname = c.getString(TAG_Sname);
String scode = c.getString(TAG_Scode);
String sgrade = c.getString(TAG_Sgrade);
HashMap<String,String> records = new HashMap<String,String>();
records.put(TAG_Sname,sname);
records.put(TAG_Scode,scode);
records.put(TAG_Sgrade,sgrade);
subList.add(records);
}
adapter = new SimpleAdapter(
getActivity(), subList, R.layout.list_layout,
new String[]{TAG_Sname,TAG_Scode,TAG_Sgrade},
new int[]{R.id.subject_name, R.id.subject_code, R.id.grade}
);
lv.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Using notifyDataSetChanged() may suite your needs.
Refer to this: How to refresh Android listview?
Edit:
adapter = new SimpleAdapter(
getActivity(), subList, R.layout.list_layout,
new String[]{TAG_Sname,TAG_Scode,TAG_Sgrade},
new int[]{R.id.subject_name, R.id.subject_code, R.id.grade}
);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
The above code should help.

How to pass value from dynamic list view to activity?

I am new in android,I have created a simple listview which is fetching data from mysql and every thing is working fine but now i want to pass the values of listview(Row) to another activity and when i am clicking on particular row i am getting null value.
public class AdminNotice extends Activity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noticelist);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
// String session_id= myprefs.getString("session_id", null);
//TextView textView = (TextView) findViewById(R.id.fname);
//textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, date=null;
/*if(c==null){
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
}*/
if(c.has("notice"))
if(c.has("ndate"))
progressBar.setVisibility(View.GONE);
name = c.getString("notice");
date = c.getString("ndate");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, Object> data = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
Intent intent = new Intent(getApplicationContext(), SingleMessage.class);
intent.putExtra("KEY", data);
startActivity(intent);
}
});
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_DATE,date);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
AdminNotice.this, personList, R.layout.list_item1,
new String[]{TAG_NAME,TAG_DATE},
new int[]{R.id.name, R.id.date}
);
list.setAdapter(adapter);
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});*/
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
set the OnItemClickListener to the list view
public boolean onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
/ /write your code here to send data like
ModelClass obj = getItem(position);
String name = obj.getName();
Intent intent = new Intent(Activity.this, Activity2.class);
intent.putExtras("Name", name);
startActivity(intent);
}
or you can do like this way also
interfaceObj.sendData(obj);

How to put data in listview which received using AsyncTask?

I am successfully retrieving but unable to put data into listview. how to update ui thread
after retrieving data.
here is the class of asynctask that retrieves data
I tried to update in onPostExecute but couldn't succeed.
class GetJson extends AsyncTask<String, Integer, ArrayList<RowItem>> {
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
//ArrayList<ArrayList<String>> fullscreens = new ArrayList<ArrayList<String>>() ;
public AsyncResponse delegate = null;
private CustomListViewAdapter arrayadapter;
private ProgressDialog pDialog;
private Context Mycontext;
private ArrayList<String> alist;
private ListView listView;
public GetJson(Context cnxt,ArrayList<String> alist, CustomListViewAdapter adapt,ListView listView) {
Mycontext = cnxt ;
//this.rowItems = rowItems;
this.alist = alist;
this.listView = listView;
}
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
this.pDialog = new ProgressDialog(Mycontext);
this.pDialog.setMessage("Please wait..");
this.pDialog.setIndeterminate(true);
this.pDialog.setCancelable(false);
this.pDialog.show();
//alist.add("fifa");
}
#Override
protected ArrayList<RowItem> doInBackground(String... passing) {
here i am recieving data
return rowItems;
}
#Override
protected void onPostExecute(ArrayList<RowItem> Items) {
super.onPostExecute(Items);
this.pDialog.dismiss();
}
}
I laso tried runuithread in doinBackgroung method
there also i am getting runtime errors
here is my code
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
String result = null;
InputStream is = null;
JSONObject json_data=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray ja = new JSONArray();
List<NameValuePair> params = new LinkedList<NameValuePair>();
for(String s : alist)
{
Log.d("s",s);
params.add(new BasicNameValuePair("list[]",s));
}
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
// 2. make POST request to the given URL
HttpGet httpPost = new HttpGet("http://10.0.3.2/infogamma/getapps.php?"+paramString);
// 4. convert JSONObject to JSON to String
String json = ja.toString();
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
is.close();
result = stringbuilder.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
//get json data
try{
//JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
Log.d("app_lentgh", Integer.toString(jArray.length()));
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
// this.donnees.add("title: "+ json_data.getString("title") + " appid: " + json_data.getString("appid") );
try{
//commmand http
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://10.0.3.2/infogamma/getAppDetails.php?appid="+json_data.getString("appid"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
ArrayList<String> screenitem = new ArrayList<String>();
try{
JSONObject j = new JSONObject(result);
screenitem.add(j.getString("scr1"));
screenitem.add(j.getString("scr2"));
screenitem.add(j.getString("scr3"));
// this.fullscreens.add(screenitem);
// RowItem(ImageView imageId, String title, String desc,String catgs,String downloads,String rating,String discription)
RowItem item = new RowItem(j.getString("coverimage"), j.getString("title"), j.getString("category"),j.getString("downloads"),j.getString("rating"),
j.getString("scr1"),j.getString("scr2"),j.getString("scr3"),j.getString("discription"),j.getString("developer"),j.getString("price")
,json_data.getString("appid"));
rowItems.add(item);
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
//SharedPreferences.Editor editor = ((Activity) Mycontext).getPreferences(Mycontext.MODE_PRIVATE).edit();
//editor.;
//editor.commit();
//Log.i("title",json_data.getString("title"));
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
} catch (ParseException e) {
Log.i("tagjsonpars",""+e.toString());
}
adapt = new CustomListViewAdapter(getApplicationContext(),
R.layout.list_item, rowItems);
listView.setAdapter(adapt);
}});
return (null);
}
You can populate the list view from doInBackground by this code
runOnUiThread(new Runnable() {
public void run() {
//set listview Adapter here
}
});
this thing is not preferable. One more thing you can do is create a class which can hold the data you want to show on the item of a list and pass the array of that class object to onPostExecute method from where you can handle the UI thread.
Do it in onPostExecute() or if you want to add them from doInBackground() instantly, do it using runOnUiThread().
Edit:
After reading your comments, You are using CustomListViewAdapter, do you have a constructor with Context,int,ArrayList<String> as parameters in your adapter class?

Update Android Listview after Asynchronous update

I am converting my HTTP calls to asynchronous calls from synchronous ones. Because the connection is running in the background the data isn't there when I originally set my list adaptor. How can I get the list adaptor to update after my HTTP call? I've tried a few things like not setting the adaptor until data gets sent back and setting the adaptor again, but nothing has worked. Here's my current oncreate code
protected void onCreate(Bundle savedInstanceState) {
overridePendingTransition(R.layout.anim_out,R.layout.anim_in);
setTheme(R.style.Theme_D_theme);
setContentView(R.layout.news_fragment);
super.onCreate(savedInstanceState);
text = (TextView) this.findViewById(R.id.nomore);
list = (ListView) this.findViewById(R.id.newslist);
list.setDividerHeight(2);
new MyAsyncTask().execute("THIS");
list.setOnItemClickListener(this);
list.setCacheColorHint(Color.WHITE);
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
}
And my AsyncTast
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
in on post execution add this line. in the end.
x.add(temp);
adapter.notifyDataSetChanged();
Do this way
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
//UPDATE HERE
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
list.setAdapter(adapter);
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}

Categories

Resources