Listview doesn't get refreshed - android

I have an issue with the ListView that it doesn't refreshed on changing the Spinner value.
What i did,
Step 1:
Created Custom Adapter and passes the the List to initialize my Adpater.
list = handler.getdata(loc);
if (list.size() > 0) {
ordList = new MicListAdapter(InventoryCount.this, list);
lstView.setAdapter(ordList);
}
Step 2:
Created one Spinner with seletion Listener
mspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
spinlocation = mspinner.getItemAtPosition(arg2).toString();
loc = spinlocation;
String item = (String) arg0.getItemAtPosition(arg2);
((TextView) arg0.getChildAt(0)).setTextColor(Color
.parseColor("#000000"));
((TextView) arg0.getChildAt(0)).setTextSize(20);
if (!changeSpinner) {
new InflateList(spinlocation).execute();
} else {
changeSpinner = false;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
new InflateList(spinlocation).execute();
}
});
Step 3:
Once spinner's value changed it will call Asynctask where i'm loading the new list in the Listview but its not reflecting anything in ListView
class InflateList extends AsyncTask<String, String, List<MIC_OrderDetails>> {
ProgressDialog dialog;
Context context;
String spinLoc;
public InflateList(String spinloc) {
dialog = new ProgressDialog(InventoryCount.this);
dialog.setCancelable(false);
this.spinLoc = spinloc;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait while Data is Loading...");
dialog.show();
}
#Override
protected List<MIC_OrderDetails> doInBackground(String... params) {
// TODO Auto-generated method stub
String result = "";
List<MIC_OrderDetails> lst = new ArrayList<MIC_OrderDetails>();
try {
lst = handler.getdata(spinLoc);
result = "success";
MIC_OrderDetails mic_OrderDetails = new MIC_OrderDetails();
mic_OrderDetails.setResult(result);
lst.add(mic_OrderDetails);
}
catch (Exception e) {
result = "error";
MIC_OrderDetails mic_OrderDetails = new MIC_OrderDetails();
mic_OrderDetails.setResult(result);
lst.add(mic_OrderDetails);
dialog.dismiss();
Log.e("Failed", e.getLocalizedMessage());
}
return lst;
}
protected void onPostExecute(List<MIC_OrderDetails> lst) {
dialog.setMessage("Inflating Data...");
if (lst.get(lst.size() - 1).getResult().contains(("success"))) {
list.clear();
ordList.clear();
list.addAll(lst);
// ordList.notifyDataSetInvalidated();
ordList.notifyDataSetChanged();
dialog.dismiss();
/*
* ordList = new MicListAdapter(InventoryCount.this, lst);
* lstView.setAdapter(ordList);
*
* dialog.dismiss();
*/
} else {
dialog.dismiss();
toastText.setText("Problem in loading Items");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastLayout);
toast.show();
}
}
}

Listview doesn't get refreshed
Create a method in MicListAdapter for updating new data in current data-source of Adapter like:
In MicListAdapter class create a method addAll:
public void addAll(List<MIC_OrderDetails> lst){
this.list.clear();
this.list.addAll(lst);
this.notifyDataSetChanged();
}
Where this.list is List object which is used to return count from getCount method.
and call addAll method using ordList from onPostExecute for updating ListView with latest data:
ordList.addAll(lst);

Related

pass filtered listview item to next activity

Here i am using using BaseAdapter to filter my listview items.when without using search option if i click on my listview item the listView.setOnItemClickListener works well, I mean the item at the clicked position is passed to next activity.But on the filtered result if i click on the item,some other data is passed to next activity..what might be the issue.?can anyone please help me to solve this issue..?
Activity
public class BindTenGPS extends Activity {
private MenuItem menuItem;
DbaAdapter db;
private ProgressDialog progressDialog;
ListView listView ;
EditText inputSearch;
private BindTenDeviceBaseAdapter adapter;
List<RowTenDevice> rowTenDevice;
ArrayList<String> DeviceName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list1_main);
inputSearch = (EditText)findViewById(R.id.inputSearch);
db=new DbaAdapter(getApplicationContext());
new LoadTrackNumbers().execute();
}
private class LoadTrackNumbers extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPreExecute()
{
//Create a new progress dialog
progressDialog = new ProgressDialog(BindTenGPS.this);
//Set the progress dialog to display a horizontal progress bar
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
//Set the dialog message to 'Loading application View, please wait...'
progressDialog.setMessage("Loading application View, please wait...");
//This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(true);
//This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
//The maximum number of items is 100
progressDialog.setMax(100);
//Set the current progress to zero
progressDialog.setProgress(0);
//Display the progress dialog
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
//Get the current thread's token
synchronized (this)
{
DeviceName.clear();
publishProgress(10);
this.wait(500);
Connection conn = null;
try {
Log.w("Error connection","shyam1");
String driver = "net.sourceforge.jtds.jdbc.Driver";
Log.w("Error connection","shyam2");
Log.i("Android"," MySQL Connect Example0.");
Class.forName(driver).newInstance();
Log.w("Error connection","shyam3");
String connString = "jdbc:jtds:sqlserver://ip address;instance=SQLEXPRESS;DatabaseName=AAUMConnect;";
String username = "username";
String password = "password";
Log.w("Error connection","shyam4");
publishProgress(20);
this.wait(500);
publishProgress(30);
this.wait(500);
publishProgress(40);
this.wait(500);
publishProgress(50);
this.wait(500);
conn = DriverManager.getConnection(connString,username,password);
publishProgress(80);
Log.w("Error connection","shyam5");
Statement stmt = conn.createStatement();
ResultSet reset;
db.open();
int superuser = db.GetISSuperUser();
db.close();
db.open();
int clientid = db.GetClientID();
db.close();
if(superuser == 0)
{
db.open();
String branch = db.GetBranch();
db.close();
reset = stmt.executeQuery("SELECT dbo.fn_AddEveryNthItem(LEFT(AssignVehicleToTrackTable, LEN(AssignVehicleToTrackTable) - 1), ',','#', 1) AS DeviceName FROM (SELECT DeviceName + ',' FROM AssignVehicleToTrack where ClientID = " + clientid + " and BranchName = '" + branch.trim() + "' and VirtualNo = 'GPS' order by DeviceName FOR XML PATH ('')) T1 (AssignVehicleToTrackTable)");
}
else
{
reset = stmt.executeQuery("SELECT dbo.fn_AddEveryNthItem(LEFT(AssignVehicleToTrackTable, LEN(AssignVehicleToTrackTable) - 1), ',','#', 1) AS DeviceName FROM (SELECT DeviceName + ',' FROM AssignVehicleToTrack where ClientID = " + clientid + " and VirtualNo = 'GPS' order by DeviceName FOR XML PATH ('')) T1 (AssignVehicleToTrackTable)");
}
//Print the data to the console
Log.w("Error connection","shyam6");
int i1 = 0, c = 0;
try
{
while(reset.next()){
publishProgress(c);
String[] tokens = new String[100];
tokens = reset.getString(1).split("#");
for(int i=0;i<tokens.length;i++)
{
DeviceName.add(tokens[i].substring(1));
}
i1++;
c+=10;
}
}
catch(Exception ex)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "GPS Device not available", Toast.LENGTH_LONG).show();
}
});
}
reset.close();
conn.close();
rowTenDevice = new ArrayList<RowTenDevice>();
for (int j = 0; j < DeviceName.size(); j++) {
RowTenDevice item = new RowTenDevice(DeviceName.get(j));
Log.w("Data:","D"+j+" : "+DeviceName.get(j));
rowTenDevice.add(item);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
listView = (ListView) findViewById(R.id.list);
Log.w("Data:","E1");
adapter = new BindTenDeviceBaseAdapter(BindTenGPS.this, rowTenDevice);
Log.w("Data:","E2");
listView.setAdapter(adapter);
Log.w("Data:","E3");
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
BindTenGPS.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(
AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(BindTenGPS.this, ShowGPS.class);
intent.putExtra("DeviceList", rowTenDevice.get(position).getDeviceName());
startActivity(intent);
}
});
Log.w("Data:","E4");
}
});
} catch (Exception e)
{
Log.w("Error connection","shyam" + e.getMessage());
e.printStackTrace();
}
this.wait(500);
publishProgress(100);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
//after executing the code in the thread
#Override
protected void onPostExecute(Void result)
{
//close the progress dialog
progressDialog.dismiss();
//initialize the View
//setContentView(R.layout.list1_main);
}
}
}
BaseAdapter
public class BindTenDeviceBaseAdapter extends BaseAdapter implements Filterable {
Context context;
List<RowTenDevice> rowTenDevice;
List<RowTenDevice> arrayList; //temporary list to store filtered values.
LayoutInflater inflater;
public BindTenDeviceBaseAdapter(Context context, List<RowTenDevice> items) {
this.context = context;
this.rowTenDevice = items;
this.arrayList = items;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView txtTenDevice;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return arrayList.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_tendevice, null);
holder = new ViewHolder();
holder.txtTenDevice = (TextView) convertView.findViewById(R.id.tvTenDevice);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowTenDevice rowItem = (RowTenDevice) getItem(position);
holder.txtTenDevice.setText(rowItem.getDeviceName());
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
Filter filter = new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
arrayList = (List<RowTenDevice>) results.values; // has the filtered values
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults results = new FilterResults();
List<RowTenDevice> FilteredArrList = new ArrayList<RowTenDevice>();
if (rowTenDevice == null) {
rowTenDevice = new ArrayList<RowTenDevice>(arrayList); // saves the original data in rowTenDevice
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = rowTenDevice.size();
results.values = rowTenDevice;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < rowTenDevice.size(); i++) {
RowTenDevice data = rowTenDevice.get(i);
if(data.getDeviceName().toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
RowTenDevice
public class RowTenDevice {
private String devicename;
public RowTenDevice(String devicename) {
this.devicename = devicename;
}
public String getDeviceName() {
return devicename;
}
public void setDeviceName(String devicename) {
this.devicename = devicename;
}
}
In onItemClick you are using rowTenDevice.get(position).getDeviceName(). This causes the problem. You need filtered item so create a public method in adapter to get arrayList.get(position).getDeviceName(). As arrayList is filtered list, it will give you required result.
Use following code:-
Replace line :- intent.putExtra("DeviceList", rowTenDevice.get(position).getDeviceName());
With
intent.putExtra("DeviceList", ((RowTenDevice)adapter.getItem(position)).getDeviceName());

how to get selectd code and selected name value from spinner in android

this is my Asynk task am getting data from server and calling in Oncreate method
class download extends AsyncTask<Void, Void, Void> {
String result;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(RDistributor.this);
pDialog.setTitle("CheckUser Connection");
pDialog.setMessage("Please wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
result = JSONfunctions2.getJSONfromURL(URL + "?spokecode="
+ "GUJAHM270");
_jarray1 = new JSONArray(result);
stringArray = new ArrayList<String>();
// stringArray.add("Select Role");
for (int i = 0; i <= _jarray1.length(); i++) {
JSONObject _obj = _jarray1.getJSONObject(i);
SpokeCode = _obj.getString("SpokeCode").toString();
DistributerCode = _obj.getString("DistributerCode")
.toString();
DistributerName = _obj.getString("DistributerName")
.toString();
stringArray.add(DistributerName);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (_jarray1.length() == 0) {
showpopup("All Distributers had already been registered!");
} else {
dataAdapter = new ArrayAdapter<String>(RDistributor.this,
R.layout.spinner_item, stringArray);
// ArrayAdapter<String> dataAdapter = new
// ArrayAdapter<String>(this,R.layout.spinner_item,
// stringArray);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// set the ArrayAdapter to the spinner
rolespinner.setAdapter(dataAdapter);
}
pDialog.dismiss();
super.onPostExecute(result);
}
}
this is itemselected of spinner and getting value .
rolespinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
DistributerName=rolespinner.getSelectedItem().toString();
Toast.makeText(RDistributor.this, DistributerName, 10000).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
i am printing data distributerName in Spinner which is coming from server also distributerCode and spoke code coming from server i want when i select distributor name corresponding i get value of distributor code and spoke code selection of ditributorname from drop down please suggest me how i will achieve this .i am facing issue to get this .
Declare :
HashMap<String, String> spinnerMap = new HashMap<String, String>();
for (int i = 0; i <= _jarray1.length(); i++) {
JSONObject _obj = _jarray1.getJSONObject(i);
SpokeCode = _obj.getString("SpokeCode").toString();
DistributerCode = _obj.getString("DistributerCode")
.toString();
DistributerName = _obj.getString("DistributerName")
.toString();
spinnerMap.put(DistributerName, DistributerCode);
stringArray.add(DistributerName);
}
and spinner item-select Method update this :
rolespinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String to= spinnerMap.get(rolespinner.getSelectedItem());
Toast.makeText(MainActivity.this,
to, 10000);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
enjoy!!!
I think you need to wrap a object for storing these property.
public class Model {
public String spokeCode;
public String DistributerCode;
.......
}
ArrayList<Model> list = new ArrayList<Model>();
list.add(model);
list.add(model);//
// and so on
//do search
DistributerName=rolespinner.getSelectedItem().toString();
Model searchModel;
for (Model m : list) {
if (m.distributerName.equals(DistributerName)) {
searchModel = m;
break;
}
}

adding data to existing listview

I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.

notifyDataSetChanged is not working

I fetched data in JSON from web service and then i put data into a custom ListView.
On clicking an item of ListView , I open a new Activity. Now I click on "Submit" Button of this activity I go back to the same ListView ,
When I get back to the ListView, I want to change the text of listitem in which I clicked before
I just want to refresh or re-call the activity when it again comes to listticket.java
Right now data is static . I used web services.
listticket.java
public class listticket extends Activity {
static ListView listView;
ArrayList<String> aryTicket = new ArrayList<String>();
private String[] listArr = { "A", "B" };
private String[] listStatus = { "Alert", "Alert" };
private String[] listTicketid = { "1", "2" };
ArrayList<String> ary_ticket_code = new ArrayList<String>();
ArrayList<String> ary_address = new ArrayList<String>();
ArrayList<String> ary_ticketid = new ArrayList<String>();
public static ArrayList<String> ary_status = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listticket);
listView = (ListView) findViewById(R.id.itemList);
// filllistdata();
listArr = new String[ary_ticket_code.size()];
listArr = ary_ticket_code.toArray(listArr);
listStatus = new String[ary_status.size()];
listStatus = ary_status.toArray(listStatus);
listTicketid = new String[ary_ticketid.size()];
listTicketid = ary_ticketid.toArray(listTicketid);
MyArrayAdapter adapter = new MyArrayAdapter(this, listArr);
listView.setAdapter(adapter);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ary_status.set(0, "Work Done");
((MyArrayAdapter) listView.getAdapter()).notifyDataSetChanged();
}
public class MyArrayAdapter extends ArrayAdapter<String> {
Activity context;
String[] listArr;
private TextView btnchkout;
// private final integer[] image;
public MyArrayAdapter(Activity context, String[] objects) {
super(context, R.layout.ticket, objects);
// TODO Auto-generated constructor stub
this.context = context;
listArr = objects;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ticket, null, true);
TextView textView = (TextView) view.findViewById(R.id.txtTicketNo);
textView.setText(listArr[position]);
final TextView txtAlert = (TextView) view
.findViewById(R.id.txtAlert1);
// Toast.makeText(getApplicationContext(), listStatus[position],
// Toast.LENGTH_LONG).show();
String statusCheck = listStatus[position].toString().trim();
if (statusCheck.equals("Alert") == true) {
txtAlert.setText(statusCheck);
txtAlert.setTextColor(getResources().getColor(R.color.red));
} else if (statusCheck.equals("In Progress") == true) {
txtAlert.setText(statusCheck);
txtAlert.setTextColor(getResources().getColor(R.color.view));
} else if (statusCheck.equals("Work Complete Pending paperwork") == true) {
txtAlert.setText("Work Done");
txtAlert.setTextColor(getResources().getColor(R.color.green));
} else {
txtAlert.setText(statusCheck);
// txtAlert.setTextColor(getResources().getColor(R.color.defaulttextcolor));
}
final TextView btntextView = (TextView) view
.findViewById(R.id.btnCheckin);
if (statusCheck.equals("In Progress")) {
Drawable d = getResources().getDrawable(R.drawable.btncheckin);
btntextView.setBackgroundDrawable(d);
}
btnchkout = (TextView) view.findViewById(R.id.btnCheckout);
btnchkout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(listticket.this,
ticket_detail.class);
startActivity(intent);
}
});
return view;
}
}
}
Another layout in when click on ListItem
ticketdetail.java
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_detail);
btnSubmit = (TextView) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AsyncAction().execute(null,null,null);
//onBackPressed();
}
});
}
private class AsyncAction extends AsyncTask<String, Void, String>
{
public boolean status=false;
private ProgressDialog pd;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
Intent intent = new Intent(ticket_detail.this,listticket.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
//finish();
}
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(ticket_detail.this);
pd.setMessage("Please Wait ...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent a = new Intent(ticket_detail.this,listticket.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
Make adapter object globally and initialize once within onCreate and inside onResume() notify to your adapter like below:
Delcaration
MyArrayAdapter adapter;
onCreate
adapter = new MyArrayAdapter(this, listArr);
listView.setAdapter(adapter);
onResume()
adapter.notifyDataSetChanged();
Try this, add, clear and remove calls notifyDataSetChanged itself and you dont have to change your adapter everytime you refresh your information, its expensive.
adapter.clear()
for (Object o : object)
adapter.add(o)

how to update listview item when get new data from server after few seconds

I have facing problem in listview i am getting data from server and after parsing this data i am using custom adpater for showing the data in listview.I want to update the listview item each after 3 seconds and add new data to list.how can it possible.
i am using adapter.notifyDataSetChanged() method but my listview is not updating it is showing the old data that i gets first time.how to show new data in listview that i got each after 3 seconds.i am using the update method like this.
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
//list.clearTextFilter();
getVisitorDetailFromServer();
list.invalidateViews();
adapter.notifyDataSetChanged();
try {
Log.i("UPDATE", "Handler called");
// searchAdapter = getFeed(URL);
adapter.notifyDataSetChanged();
handler.postDelayed(this, 3000);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
Using getVisitorDetailFromServer() i am getting the data.
adapter class code is
private class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public void setContext(Context context) {
// TODO Auto-generated method stub
//caching. notifyDataSetChanged();
}
public int getCount() {
return sizeoflist;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row1, null);
holder = new ViewHolder();
holder.IP = (TextView) convertView.findViewById(R.id.ip);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.status =(TextView) convertView.findViewById(R.id.status);
holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
holder.deny = (Button) convertView.findViewById(R.id.btndeny);
holder.deny.setVisibility(View.INVISIBLE);
holder.invite.setId(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String result = response;
String delimiter = "<fld>";
String delimiter1 = "<ln>";
String delimiter2 = "<blk>";
String delimiter3 = "<fld><fld><blk>";
operatorDetail = result.split(delimiter1);
String[] operatorlist = result.split(delimiter3);
noofvisitors = operatorlist[1].split(delimiter2);
System.out.println("no of visitor================"+noofvisitors[0]);
for(int i=0;i<operatorDetail.length;i++){
operatorList = operatorDetail[i].split(delimiter);
operatorlist = result.split(delimiter2);
SessionText.add(operatorList[0]);
IPText.add(operatorList[1]);
DurationText.add(operatorList[4]);
StatusText.add(operatorList[3]);
NoOfVisit.add(operatorList[2]);
ButtonText.add(operatorList[6]);
iptext = IPText.get(i) ;
sessionid = SessionText.get(i);
//System.out.println("session value is"+SessionText.get(position));
//System.out.println("ip values are"+IPText.get(position));
//System.out.println("duration values are"+DurationText.get(position));
//System.out.println("status values are"+StatusText.get(position));
//System.out.println("no of visit"+NoOfVisit.get(position));
if(StatusText.get(position).equalsIgnoreCase("chat request")){
holder.deny.setVisibility(View.VISIBLE);
holder.invite.setText("Accept");
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
holder.invite.setText("Join");
holder.deny.setVisibility(View.INVISIBLE);
}
});
}
else{
holder.invite.setText("Invite");
holder.deny.setVisibility(View.INVISIBLE);
}
if(holder.invite.getText().equals("Join")){
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
chatRequest(iptext,sessionid);
}
});
}
holder.IP.setText(IPText.get(position));
holder.duration.setText(DurationText.get(position));
holder.status.setText(StatusText.get(position));
holder.noOfVisit.setText(NoOfVisit.get(position));
//---------------------When user click on invite Button---------------------
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
callToServer(SessionText.get(position));
}
});
//-----------------------------When user click on deny button------------------------
holder.deny.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
refuseToServer(sessionid);
holder.deny.setVisibility(View.INVISIBLE);
}
});
}
System.out.println("no of visitor================"+noofvisitors[0]);
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent i=new Intent(Visitors.this,VisitorDetail.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
i.putExtra("SessionText", SessionText.get(position));
i.putExtra("IPTEXT",IPText.get(position));
startActivity(i);
}});
//startService();
return convertView;
}
class ViewHolder {
TextView IP;
TextView duration;
Button deny;
TextView status;
TextView noOfVisit;
Button invite;
}
}
my class code is
public class Visitors extends Activity {
private ListView list;
private final int NOTIFICATION_ID = 1010;
private Timer timer = new Timer();
private String response,response1;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText;
private ArrayList<String> StatusText,NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
public static String from,sessionid,id,text,iptext,status;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
private CustomAdapter adapter;
NotificationManager notificationManager;
final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
//list.clearTextFilter();
getVisitorDetailFromServer();
list.invalidateViews();
adapter.notifyDataSetChanged();
try {
adapter.notifyDataSetChanged();
handler.postDelayed(this, 3000);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor);
list = (ListView) findViewById(R.id.list01);
logout = (Button) findViewById(R.id.btnlogout);
adapter = new CustomAdapter(Visitors.this);
updater.run();
//-----------------Making the object of arrayList----------------
SessionText = new ArrayList<String>();
IPText = new ArrayList<String>();
DurationText = new ArrayList<String>();
StatusText = new ArrayList<String>();
NoOfVisit = new ArrayList<String>();
ButtonText = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
IsSoundEnable = Controls.IsSoundEnable;
IsChatOnly = Controls.IsChatOnly;
IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
extras.getString("From");
position=extras.getInt("Position");
}
}
#Override
protected void onStart() {
super.onStart();
//------------Getting the visitor detail-------------------------
getVisitorDetailFromServer();
//---------------When user click on logout button-----------------------------------
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
logoutFromServer();
}
});
}
//----------------------------Getting the detail from server of monitoring window-------------------------
private void getVisitorDetailFromServer() {
// TODO Auto-generated method stub
if(IsChatOnly){
url = "http://sa.live2support.com/cpn/wz1-allonlineu.php?";
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "Y");
}
else{
url = "http://sa.live2support.com/cpn/wz1-allonlineu.php?";
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "N");
}
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
String result = response;
String delimiter1 = "<ln>";
String delimiter = "<fld>";
operatorDetail = result.split(delimiter1);
for(int i=0;i<operatorDetail.length;i++){
operatorList = operatorDetail[i].split(delimiter);
SessionText.add(operatorList[0]);
IPText.add(operatorList[1]);
DurationText.add(operatorList[4]);
StatusText.add(operatorList[3]);
NoOfVisit.add(operatorList[2]);
ButtonText.add(operatorList[6]);
}
//--------Getting the size of the list---------------------
sizeoflist = operatorDetail.length;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playsound3();
noofchat =0;
System.out.println(response);
list.setAdapter(adapter);
list.getDrawingCache(false);
list.invalidateViews();
list.setCacheColorHint(Color.TRANSPARENT);
list.requestFocus(0);
list.setSelected(false);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
if(IsChatOnly==false){
TimerTask timerTask = new TimerTask()
{
#Override
public void run()
{
//triggerNotification();
//playsound();
}
};
timer.schedule(timerTask, 3000);
}
else{
playsound();
}
}
});
}
else {
ShowAlert();
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//--------------------When internet connection is failed show alert
private void ShowAlert() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
alert.setTitle("Live2Support");
alert.setMessage("Internet Connection failed");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//startActivity(new Intent(CreateAccount.this,CreateAccount.class));
alert.dismiss();
}
});
alert.show();
}
//--------------------Play sound when notification occurs-------------------
private void playsound() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);
mp.start();
}
Simple calling adapter.notifyDataSetChanged() will not work unless you actually update the dataset 'within the adapter class'.
I suspect you are not passing the updated information into your Adapter class. Check to see if the datastructure referenced by your Adapter's getCount() method is the same as the one being updated by the getVisitorDetailFromServer() server.
If that is not the problem, you'll need to post more code.
I was having the same problem. I cleared the list before adding the new data and it resolved

Categories

Resources