listView does not refresh with new values - android

I have a problem while refreshing the list view from old values to new values.
Through a search for many hours i have got that adapter.notifyDataSetChanged(); has to be used.
But i am unable to understand how do i use it as whenever i use it gives me an error
"The method notifyDataSetChanged() is undefined for the type ListAdapter"
i am not sure whether i am doing the right thing. please Help...
This is my Code
public class Slider extends Activity implements OnClickListener,
OnDrawerOpenListener, OnDrawerCloseListener {
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
ListView list;
TextView t1;
String data, query, is;
Spinner d;
String FILENAME = "http://24.php";
ArrayList<String> pos;
ListAdapter adapter;
ArrayList<HashMap<String, String>> mylist;
HashMap<String, String> map;
static String j_id = null;
static Object j_make = null;
static String j_model = null;
static String j_version = null;
static String j_price = null;
static String j_reg_plc = null;
String ID = "car_id";
String MAKE = "make";
String MODEL = "model";
String VERSION = "version";
String PRICE = "expected_price";
String PLACE_REG = "registration_place";
CheckBox cb1, cb2, cb3, cb4, cb5, cb6, cb7, cb8, cb9, cb10;
Spinner sp1;
int flag = 0;
String drive[] = new String[] { "Select Drive", "Two-Wheel Drive",
"Four-Wheel Drive", "All-Wheel Drive" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.slider);
t1 = (TextView) findViewById(R.id.noRec);
list = (ListView) findViewById(R.id.listView1);
cb1 = (CheckBox) findViewById(R.id.checkBox1);
cb2 = (CheckBox) findViewById(R.id.checkBox2);
cb3 = (CheckBox) findViewById(R.id.checkBox3);
cb4 = (CheckBox) findViewById(R.id.checkBox4);
cb5 = (CheckBox) findViewById(R.id.checkBox5);
cb6 = (CheckBox) findViewById(R.id.checkBox6);
cb7 = (CheckBox) findViewById(R.id.checkBox7);
cb8 = (CheckBox) findViewById(R.id.checkBox8);
cb9 = (CheckBox) findViewById(R.id.checkBox9);
cb10 = (CheckBox) findViewById(R.id.checkBox10);
d = (Spinner) findViewById(R.id.drive);
#SuppressWarnings("unchecked")
ArrayAdapter spdrv = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, drive);
d.setAdapter(spdrv);
t1.setVisibility(View.GONE);
mylist = new ArrayList<HashMap<String, String>>();
pos = new ArrayList<String>();
Bundle bundle = getIntent().getExtras();
String stuff = bundle.getString("stuff");
Toast.makeText(getApplicationContext(), "Stuff= |" + stuff + "|",
Toast.LENGTH_LONG).show();
if (stuff.contains("null")) {
t1.setVisibility(View.VISIBLE);
t1.setText("No Records Found");
Toast.makeText(getApplicationContext(), "No Records Found!",
Toast.LENGTH_LONG).show();
} else {
load_list(stuff); //Load list with values
}
mCloseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
query = "Select make, model, version, expected_price, registration_place FROM `used_cars` where registration_place ="
+ "'" + j_reg_plc + "'";
if (cb1.isChecked()) {
query = query + " AND transmission ='Yes'";
}
if (cb2.isChecked()) {
query = query + " AND ac ='Yes'";
}
if (cb3.isChecked()) {
query = query + " AND car_lockk ='Yes'";
}
if (cb4.isChecked()) {
query = query + " AND sunroof ='Yes'";
}
if (cb5.isChecked()) {
query = query + " AND window ='Yes'";
}
if (cb6.isChecked()) {
query = query + " AND seats ='Yes'";
}
if (cb7.isChecked()) {
query = query + " AND stearing ='Yes'";
}
if (cb8.isChecked()) {
query = query + " AND player ='Yes'";
}
if (cb9.isChecked()) {
query = query + " AND sound_system ='Yes'";
}
if (cb10.isChecked()) {
query = query + " AND wheels ='Yes'";
}
query = query + ";";
Toast.makeText(getApplicationContext(), "QUERY= " + query,
Toast.LENGTH_LONG).show();
System.out.println("QUERY= " + query);
startDownload();
mDrawer.animateClose();
}
});
mOpenButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!mDrawer.isOpened())
mDrawer.animateOpen();
}
});
}
private void startDownload() {
new AppTask().execute(FILENAME);
}
public class AppTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "res" + result,
Toast.LENGTH_LONG).show();
pos = new ArrayList<String>();
mylist.clear();
load_list(result); //Refresh list with new values
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://animsinc.com/filter.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
5);
nameValuePairs.add(new BasicNameValuePair("Qry", query));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return is;
}
}
#Override
public void onContentChanged() {
super.onContentChanged();
mCloseButton = (Button) findViewById(R.id.button_close);
mOpenButton = (Button) findViewById(R.id.button_open);
mDrawer = (MultiDirectionSlidingDrawer) findViewById(R.id.drawer);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerClosed() {
// TODO Auto-generated method stub
// demo.setVisibility(View.VISIBLE);
}
#Override
public void onDrawerOpened() {
// TODO Auto-generated method stub
// demo.setVisibility(View.GONE);
}
public void load_list(String lt) {
// list.setAdapter(null);
Toast.makeText(getApplicationContext(), "Inside load_list", 100).show();
try {
JSONArray jArray = new JSONArray(lt.toString());
for (int i = 0; i < jArray.length(); i++) {
Toast.makeText(getApplicationContext(),
"Inside load_list----FOR", 100).show();
map = new HashMap<String, String>();
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(ID);
j_make = jObject.getString(MAKE);
j_model = jObject.getString(MODEL);
j_version = jObject.getString(VERSION);
j_price = jObject.getString(PRICE);
j_reg_plc = jObject.getString(PLACE_REG);
data = j_make + "";
map.put("make", data);
data = j_model + "";
map.put("model", data);
data = j_version + "";
map.put("version", data);
data = j_price + "";
map.put("price", data);
data = j_reg_plc + "";
map.put("place", data);
mylist.add(map);
pos.add(j_id);
}
} catch (JSONException e) {
e.printStackTrace();
}
list = (ListView) findViewById(R.id.listView1);
String[] from = new String[] { "make", "model", "version", "price",
"place" };
int[] to = new int[] { R.id.text1, R.id.text5, R.id.text3, R.id.text4,
R.id.text2 };
adapter = new SimpleAdapter(this, mylist, R.layout.text_adaptr, from,
to);
Toast.makeText(getApplicationContext(), "B4 list setAdapter", 100)
.show();
// mylist.notifyDataSetChanged();
list.setAdapter(adapter);
// ---------------------------------
int[] colors = { 0, 0xff00ffff, 0 }; // red for the example
list.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
list.setDividerHeight(4);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = pos.get(position) + "";
Toast.makeText(getApplicationContext(), "data: " + data,
Toast.LENGTH_LONG).show();
// Display_Car dc=new Display_Car();
// dc.get_cid(data);
Intent myIntent = new Intent(Slider.this, Buy_View.class);
Bundle bundle = new Bundle();
// Add your data to bundle
bundle.putString("stuff", data);
// Add the bundle to the intent
myIntent.putExtras(bundle);
startActivity(myIntent);
}
});
// ---------------------------------
}
}

Try this,
You can use the runOnUiThread method as follows. If you're not using a ListActivity, just adapt the code to get a reference to your ArrayAdapter.
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});

Try this:
list.setAdapter(adapter);
adapter.notifyDatasetChanged();
You have to remember notifyDataSetChanged() works only when the data inside the adapter has changed, and it rerenders the list. In your case you change the data externally, so you have to change the data inside the adapter.
In such cases, use something like
((ItemArrayAdapter)lv.getAdapter()).notifyDataSetChanged() instead of adapter.notifyDataSetChanged()

SimpleAdapter is a BaseAdapter. Change
ListAdapter adapter;
to
BaseAdapter adapter;
or SimpleAdapter adapter;

Related

ListView Empty When Poputaing

I am trying to add items from database onto a listView, when I use System.out.println I see values but upon trying to populate them onto a custom listview returns no data in the listview.
When launching the app, I get a single row of listview item but of course it's empty.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String jsonResult;
String url = "http://www.mywebsite/query.php";
ListView list;
List<String> arrName;
List<String> arrNumber;
List<String> arrUsername;
List<String> arrStatus;
String name;
String number;
String username;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
arrName = Arrays.asList(name);
arrNumber = Arrays.asList(number);
arrUsername = Arrays.asList(username);
arrStatus = Arrays.asList(status);
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { //SINGLE CLICK
// TODO Auto-generated method stub
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Name;
List<String> Number;
List<String> Username;
List<String> Status;
ContactsAdapter(Context c, List<String> Name, List<String> Number, List<String> Username, List<String> Status)
{
super(c, R.layout.activity_contacts_single, R.id.textName, Name);
this.context=c;
this.Name=Name;
this.Number=Number;
this.Username=Username;
this.Status=Status;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtName = (TextView) row.findViewById(R.id.textName);
TextView txtNumber = (TextView) row.findViewById(R.id.textNumber);
TextView txtUsername = (TextView) row.findViewById(R.id.textUsername);
TextView txtStatus = (TextView) row.findViewById(R.id.textStatus);
txtName.setText(Name.get(position));
txtNumber.setText(Number.get(position));
txtUsername.setText(Username.get(position));
txtStatus.setText(Status.get(position));
return row;
}
}
}
It's because you haven't add those items into your lists, Change this part of your code:
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
//add this part to your code
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
for your second problem I think you can change your code this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
//arrName = Arrays.asList(name);
//arrNumber = Arrays.asList(number);
//arrUsername = Arrays.asList(username);
//arrStatus = Arrays.asList(status);
arrName = new ArrayList<String>();
arrNumber =new ArrayList<String>();
arrUsername =new ArrayList<String>();
arrStatus =new ArrayList<String>();
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}

old data in the ListView remains there when i bind new values to ListView in android

I have one ListView,I have made a custom adapter for binding data to it,I have made an asynctask in the activity for getting data and display it into the listView,I have two different Urls for the same asyctask ,based on the condition i am using it,Thing is that when i am second time the listView doesn't remove the previous values.
main.java
public class MyMessagesActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
private MessageAdapter msgContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, pro_unit;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_messgaes);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
menu.setSelectedTab(3);
header.title.setText("Messages");
msgList = new ArrayList<HashMap<String, String>>();
// url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this,
// Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
tv_switch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
tv_switch.setText("Switch to supplier");
new GetMessages().execute();
flag = false;
} else {
tv_switch.setText("Switch to buyer");
new GetMessages().execute();
flag = true;
}
}
});
// AsyncTAsk for Wholesale Product List...!!!
new GetMessages().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// in = new Intent(getApplicationContext(),
// ProductDetailActivity.class);
/*
* pro_name = ((TextView)
* view.findViewById(R.id.product_label)).getText().toString();
*
* // getting ProductId from the tag...
*
* pro_id = msgList.get(position).get(Const.TAG_PRODUCT_ID);
* pro_name = msgList.get(position).get(Const.TAG_PRODUCT_NAME);
* pro_img = msgList.get(position).get(Const.TAG_PRODUCT_IMG);
* System.out.println(
* ":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
* + pro_name); Toast.makeText(MyMessagesActivity.this,
* pro_name, Toast.LENGTH_SHORT).show();
*/
// startActivity(in);
}
});
}
private class GetMessages extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyMessagesActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGES;
if (flag) {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=1";
} else {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
}
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String subject = c.getString(Const.TAG_SUBJECT);
String msg_read = c.getString(Const.TAG_MESSAGE_READ);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CAT_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_SUBJECT, subject);
message.put(Const.TAG_MESSAGE_READ, msg_read);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(MyMessagesActivity.this, "No messgaes found", "yehki", "Ok");
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
}
}
}
Please help me for it,thank you eve-one
Try to remove the old records from your HashMap arraylist as below to remove all the data from arraylist.
After binding the data into ListView just clear your arraylist as below:
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
msgList.clear();
}
just clear your list
add mgList.clear(); in protected void onPreExecute()..
Put these lines in OnCreate() method itself,
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
Use this line in onPostExecute() of the AsynTask class,
msgContent.notifyDataSetChanged();
If this doesn't work try to add static keyword before msglist variable.
In your doInBackground() add below line before starting for loop:
msgList.clear();
You need to call msgList.clear(); before add data in to msgList arrayList. After that in onPostExecute() method just check condition while set adapter in to listview,
try {
if (msgList!= null
&& msgList.size() > 0) {
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
msgContent.notifyDataSetChanged();
} else {
Toast.makeText(YourActivityName.this,
"No Data connection", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Clearing the msgList is not worked for me. And use
msgList = new ArrayList>();
in doInBackground() before you adding the new content to the list. And just an info, there is no need to call notifyDataSetChanged() when you set a new instance of the adapter to a listview(And there is no problem if you called the notifyDataSetChanged).
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);

To get Id of selected item in spinner android

Here, It is my java file
public class Create_Event extends SherlockFragment
implements OnClickListener {
class Organizer extends AsyncTask<Void, Void, Object> {
private ProgressDialog pdia;
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(getActivity());
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected Object doInBackground(Void... params) {
try {
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost(Constants.BASE_URL
+ "mobile_logins/all_my_event");
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);
nameValuePairs1.add(new BasicNameValuePair("id", Constants.id));
httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse response1 = httpclient1.execute(httppost1);
String _response1 = EntityUtils.toString(response1.getEntity());
Log.e("test", _response1);
jsobj1 = new JSONObject(_response1);
orr = jsobj1.getJSONArray("organizers");
String orggg = orr.toString();
Log.e("Organization", orggg);
return jsobj1;
} catch (Exception e) {
e.printStackTrace();
Log.e("Fail 1", e.toString());
return e;
}
}
protected void onPostExecute(Object jsobj) {
pdia.dismiss();
String post = jsobj.toString();
Log.e("event_rese", post);
int len = orr.length();
Log.e("json_posexe", orr.toString());
Log.e("Onpostexe_arrlength", String.valueOf(len));
try {
JSONArray JA = orr;
JSONObject json1 = null;
final String[] host1 = new String[orr.length()];
final String[] host_id=new String[orr.length()];
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < host1.length; i++) {
list.add(host1[i]);
}
Log.e("onpostexe_list",list.toString());
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
organization=sp.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
if (json instanceof JSONObject) {
asyncrun = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
} else {
ExecptionHandler.register(getActivity(), (Exception) jsobj);
}
}
}
}
}
Here, I need id of the selected organization from spinner. The id and organization name came from Jsonobject(here jsobj1). How to get id of selected item from jsonobject? Is it possible?? Please Help...
Create a Organization bean as below with method #Override toString()
public class Organization {
private Integer orgId; // Long etc.
private String orgName;
// more properties if you need
#Override // Mandatory
public String toString() {
return orgName; // Return anything, what you want to show in spinner
}
// Getter & Setter
}
Then Create a java.util.List<Organization> organizationList; from your API response JSONArray or any other way. And make and set ArrayAdapter<Organization> to load Spinner options.
List<Organization> organizationList = ... // init using JSON Data OR any how;
ArrayAdapter<Organization> orgAdapter = new ArrayAdapter<Organization>(this, android.R.layout.simple_spinner_item, organizationList);
orgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner mySpinner = findViewById(R.id.orgSpinner);
mySpinner.setAdapter(orgAdapter);
Now get selected Organization and its Properties in any Click/Change Event like below
// In any OnClick / OnSelect event
Organization selectedOrganization = (Organization) mySpinner.getSelectedItem();
Integer orgId = selectedOrganization.getOrgId();
String orgName = selectedOrganization.getOrgName();
// and if you have more properties
Yes,it is Possible, try like below.
HashMap<String,String> map_values = new HashMap<String,String>();
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
map_values.put(host1[i],host_id[i]);
}
and spinner
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String value = sp.getSelectedItem().toString();
String id = map_values.get(value);
Log.v("id",""+id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
mSpinner.getSelectedItemId(); // here is your selected item's Id.
BTW google first, ask later :)

my llistview load multiple time same data on screen

my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url",""+URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
JSONObject json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
Category_ID.add((long) i);
school_name
.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString("menu_title");
message = "weekly";
mVal2 = mVal[0];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.

Trying to query for Facebook profiles and sort them into a ListView Android

I am using the Facebook Graph API to request a list of Facebook profiles and return them in a ListView displaying both names and profile pictures. I have two EditText fields in my main acitivty to enter both first and second names. A button starts my ListViewActivity when clicked and the names are passed. The ListView inflates and the request is sent to Facebook and each row in the ListView is updated using a custom adapter.
The problem is, I suspect, a memory leak. It is very temperamental as in, it would work once or twice if I'm lucky and any other attempts to update the ListView wouldn't work, the activity would remain blank. It doesn't work for some more common names either.
Below is my ListViewActivity:
public class ListViewActivity extends Activity implements OnItemClickListener {
public String firstname, secondname;
URL imageURL;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
public static final String[] descriptions = new String[] {"Description"};
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
loadData();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.listview);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
public void loadData() {
Session session = Session.getActiveSession();
firstname = getIntent().getExtras().getString("firstname");
secondname = getIntent().getExtras().getString("secondname");
if(session==null){
session = Session.openActiveSessionFromCache(this);
} else if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("fields", "name, picture, url, id");
params.putString("limit", "10");
Request request = new Request(session, "search?q="+ firstname + "%20" + secondname + "&limit=10&type=user&fields=name,picture", params, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JSONArray jArray = null;
imageURL = null;
try {
jsonObject = new JSONObject(response.getGraphObject().getInnerJSONObject().toString());
jArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject element = null;
element = jArray.getJSONObject(i);
imageURL = new URL("http://graph.facebook.com/"+ element.get("id") +"/picture?type=large");
names.add(element.getString("name").toString());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
bitmaps.add(BitmapFactory.decodeStream(imageURL.openConnection().getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
thread.join();
if (bitmaps.size() == jArray.length()) {
for (int j=0; j<jArray.length(); j++) {
RowItem item = new RowItem(bitmaps.get(j), names.get(j), descriptions[0]);
rowItems.add(item);
}
}
}
} catch (JSONException e) {
System.out.println("JSON EXCEPTION:"+ e);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.d("close", " ");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
Would appreciate it if someone could help spot a memory leak (if that is indeed the issue because i'm getting between 7 - 10% free) and advise whether there is a better way of implementing this? Thanks
EDIT: Just to clarify I'm updating the list by going back to the main activity to enter a new name in the edit text fields and clicking the button to start the list view again
Does scaling the images help any?
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
I added in those two lines at line 67
public class ListViewActivity extends Activity implements OnItemClickListener {
public String firstname, secondname;
URL imageURL;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
public static final String[] descriptions = new String[] {"Description"};
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
loadData();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.listview);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
public void loadData() {
Session session = Session.getActiveSession();
firstname = getIntent().getExtras().getString("firstname");
secondname = getIntent().getExtras().getString("secondname");
if(session==null){
session = Session.openActiveSessionFromCache(this);
} else if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("fields", "name, picture, url, id");
params.putString("limit", "10");
Request request = new Request(session, "search?q="+ firstname + "%20" + secondname + "&limit=10&type=user&fields=name,picture", params, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JSONArray jArray = null;
imageURL = null;
try {
jsonObject = new JSONObject(response.getGraphObject().getInnerJSONObject().toString());
jArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject element = null;
element = jArray.getJSONObject(i);
imageURL = new URL("http://graph.facebook.com/"+ element.get("id") +"/picture?type=large");
names.add(element.getString("name").toString());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
bitmaps.add(BitmapFactory.decodeStream(imageURL.openConnection().getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
thread.join();
if (bitmaps.size() == jArray.length()) {
for (int j=0; j<jArray.length(); j++) {
RowItem item = new RowItem(bitmaps.get(j), names.get(j), descriptions[0]);
rowItems.add(item);
}
}
}
} catch (JSONException e) {
System.out.println("JSON EXCEPTION:"+ e);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.d("close", " ");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}

Categories

Resources