Refreshing a listview in android - android

I have a listview that contains values from webservice.Each page contains only 10 listitems and the next 10 in page 2 etc.Each listitem is clickable and it contains a button which is mainly for voting.So when i click the button in list item 1 ,a value is added to webservice.
The button click codes are placed in a custom base adapter class.So that i can easily add the vote.But the problem is,When i submit the vote,i want to refresh my listview also.Suppose if iam in page no 5,refresh that listview page.
How can i refresh this listview instantly after submitting the value to webservice?
sample code for main.java
private class ProgressThreadNextPageLoading extends
AsyncTask<String, Void, String> {
// private String Content;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(KidsCrackMeUp.this);
progressDialog.setMessage("Loading..Please Wait..");
progressDialog.setIcon(R.drawable.icon);
progressDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
// call ur webservice here
try {
// pagenum = 1;
posts= web
.getAllposts(pagenum);
response = "Yes";
} catch (Exception e) {
e.printStackTrace();
response = "Failure";
}
return response;
}
#Override
protected void onPostExecute(String result) {
// below line code is to dismiss the progress bar
progressDialog.dismiss();
if (posts != null) {
adapter = new DynamicListAdapter(
main.this, posts
lstPosts.setAdapter(adapter);
adapter.notifyDataSetChanged();
//btnState.setPressed(true);
}
----------------------------------custom adapter class
viewHolder.btnVoting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog d = new Dialog(activity);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.voteselectornew);
Button btnCategoryCancel = (Button) d
.findViewById(R.id.btnCategoryCancel);
Button twcVote = (Button) d
.findViewById(R.id.btnTwcVote);
twcVote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String confirm = web
.addTwcVote(UserSessionKey, Userlist.get(position).contentid);
if (confirm.contains("Successfully")) {
d.dismiss();
}

You have to notify your ListView adapter that the data has changed.
listViewAdapater.notifyDataSetChanged();
you can just reasing your adapter via the constructor with the updated array.

call your listview adapter's method to update the change as:
adapter.notifyDataSetChanged();

Related

making visible and invisible a button

So my problem is the following ive made 2 fucntion which the objective is to return if a edittext has something writen or not, if it has i want it to make a button visible if not i want the buton to stay invisible. But this isnt working im gona show all my code
functions, this are the functions ive made:
private boolean checkEditText(EditText edit) {
return edit.getText().length() == 0;
}
void updateButtonState() {
if(checkEditText(inputdtestab) && checkEditText(quantidade))
{
inputdtestab.setError("yipikaei");
quantidade.setError("mudfukkerrr");
}
else{
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.button2);
btnCreateProduct.setVisibility(View.visible);
}
}
this dont work and i think the reason is because it doesnt run the else part of the code, because i tried creating a button and when i click on it make the button appear and it works fine. But doing as i want, it doesnt work.
All code:
#SuppressLint({ "NewApi", "CutPasteId" })
public class Newlin_ProductActivity extends Activity{
/** WebServices */
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputdtestab;
EditText inputdata;
EditText inputhora;
EditText quantidade;
EditText etDate;
Button change_date;
String id2;
String data;
String data2;
int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
// url to create new product
private static String url_create_product = "http://10.0.2.2/webprojecto4/inserir_lin_doc.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_ID = "id";
private static final String DATA = "dt";
private static final String DATA2 = "dt2";
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_linha);
Intent i = getIntent();
id2 = i.getStringExtra(TAG_ID);
data = i.getStringExtra(DATA);
data2 = i.getStringExtra(DATA2);
/** WebServices */
inputdtestab= (EditText) findViewById(R.id.editestab);
inputdata = (EditText) findViewById(R.id.editdata);
inputhora = (EditText) findViewById(R.id.edithora);
quantidade = (EditText) findViewById(R.id.editquantidade);
inputhora.setText(hr);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.button2);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
updateButtonState();
}
//restriƧoes ver
private boolean checkEditText(EditText edit) {
return edit.getText().length() == 0;
}
void updateButtonState() {
if(checkEditText(inputdtestab) && checkEditText(quantidade))
{
inputdtestab.setError("yipikaei");
quantidade.setError("mudfukkerrr");
}
else{
Button btnCreateProduct = (Button) findViewById(R.id.button2);
btnCreateProduct.setVisibility(View.visible);
}
}
private OnDateSetListener onDateSet=new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
System.out.println("2");
sYear=year;
sMonth=monthOfYear;
sDay=dayOfMonth;
updateDateDisplay(sYear,sMonth,sDay);
}
};
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Newlin_ProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String id_estab = inputdtestab.getText().toString();
String quantidades = quantidade.getText().toString();
String data = inputdata.getText().toString();
String hr = inputhora.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id_cab_doc", id2));
params.add(new BasicNameValuePair("num_lin", ""));//ir buscar criar
params.add(new BasicNameValuePair("id_produto", "00000"));
params.add(new BasicNameValuePair("id_tipo_produto", "00"));
params.add(new BasicNameValuePair("id_estab", id_estab));
params.add(new BasicNameValuePair("quantidade", quantidades));
params.add(new BasicNameValuePair("dt", data));
params.add(new BasicNameValuePair("hr", hr));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Linhas_pesagem.class);
i.putExtra(TAG_ID, id2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
Intent i = new Intent(getApplicationContext(), Linhas_pesagem.class);
i.putExtra(TAG_ID, id2);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
"So my problem is the following ive made 2 fucntion which the objective is to return if a edittext has something writen or not, if it has i want it to make a button visible if not i want the buton to stay invisible. But this isnt working im gona show all my code."
So basically you want to display the button if input value is provided in your EditText views. And hide the button otherwise.
Edit your updateButtonState() method as follows:
void updateButtonState() {
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.button2);
if(checkEditText(inputdtestab) && checkEditText(quantidade)) {
inputdtestab.setError("yipikaei");
quantidade.setError("mudfukkerrr");
// ==========================================
// make the button invisible.
btnCreateProduct.setVisibility(View.INVISIBLE); // or use View.GONE
} else {
// ==========================================
// make button visible.
// use the method "setVisibility", not "setViewVisibility"
// and "VISIBLE" in "View.VISIBLE" is in full cap:
btnCreateProduct.setVisibility(View.VISIBLE);
}
}
To make the button invisible, write btnCreateProduct.setVisibility(View.INVISIBLE);.
If you would like the button to take up the space when it is not visible, you can use View.GONE instead of View.INVISIBLE.
UPDATE
To display the button immediately when the EditTexts are filled in, you have to listen to the change of the text of the EditTexts. First you implement the TextWatcher.
private TextWatcher myTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
public void afterTextChanged(Editable editable) {
// invoke the following method here:
updateButtonState();
}
};
and then add the watcher as the listener for both of your EditTexts.
inputdtestab.addTextChangedListener(myTextWatcher);
quantidade.addTextChangedListener(myTextWatcher);
setViewVisibility means that you need to define the id of the view. Instead, use:
yourButton.setVisibility( View.(GONE, HIDDEN, VISIBLE, ...))

Trouble clearing spinner data android

I have a problem with my spinners in my android app. I have two spinners implemented. Both loads contents from json. The first one look as,
// Code for First spinner
loc = json.getJSONArray("location");
for(int i = 0; i < loc.length(); i++){
JSONObject c = loc.getJSONObject(i);
//put json obkject on variable
String l = c.getString("stock_location");
locationList.add(l);
// Set Spinner Adapter
location.setAdapter(new ArrayAdapter<String>OfferedDiesel.this,android.R.layout.simple_spinner_dropdown_item,locationList));
// Spinner on item click listener
location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
place = locationList.get(position);
selected = place;
new LoadProduct().execute();
product_title.setVisibility(View.VISIBLE);
product.setVisibility(View.VISIBLE);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
place = null;
}
});
}
//Following is the LoadProduct
private class LoadProduct extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OfferedDiesel.this);
pDialog.setMessage("Loading Product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getProductFromLocation(selected);
return json;
}
protected void onPostExecute(JSONObject json) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
// Locate the spinner in activity_main.xml
/*LOcate site node*/
try{
if(json.has("error_msg")){
String err = json.getString("error_msg");
alert.showAlertDialog(OfferedDiesel.this, "ALert !!", err, null);
}else{
prod = json.getJSONArray("product");
for(int i = 0; i < prod.length(); i++){
JSONObject d = prod.getJSONObject(i);
//put json obkject on variable
String k = d.getString("stock_name");
productList.add(k);
arrayAdapter = new ArrayAdapter<String>(OfferedDiesel.this,android.R.layout.simple_spinner_dropdown_item,productList);
// Set Spinner Adapter
product.setAdapter(arrayAdapter);
// Spinner on item click listener
product.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
good = locationList.get(position);
//selected = place;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
place = null;
}
});
}
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}/*End of Spinner Populate*/
Here, whenever I am selecting a new item in above spinner it will execute new LoadProduct().execute(); and on my second spinner I am getting the data but the date are appended. I mean for example if by defalt '1' on my first spiner then at second spinner I will get "First" and when I select '2' (change on first spinner) then I will get "Second" it is appended on 'First' and Hence I get 2 items "First" and "Second" instead of just one i.e'Second'. I now need to clear all the spinner list before loading the new. For both spinners I am using json to load data.
Thanks in advance.
I'm going to take a few guesses here about what you are trying to do, because I'm not 100% sure I understood... Here's what I think you are trying to do:
There are two ListViews.
When you click on the first one, it sets up text in the second one to load.
It does so via an AsyncTask called LoadProduct.
selected is used in the LoadProduct to determine what to load.
You aren't getting quite the results you expect.
Okay, so if I'm right here, I would suggest a few changes.
Pass in the selected value to the AsyncTask.
Clear the previous adapter from it's values.
Add the new values.
The AsyncTask should be able to take the input, no problem.
You just need to clear array list using clear method before adding new data to array,this would defiantly help you

Changing string value in OnClick

Fairly new to android programming and having trouble changing the string value "channel" when a button is clicked. Having issues trying to close the onCreate but it only seems to let me close it at the end of the activity. I get an error of 'token "}". please delete' if i try to close it elsewhere. I'm having a hard time trying to wrap my head around this even though it's probably very simple.
public class MainActivity extends Activity {
String channel = "bbc1";
// This method creates main application view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
setContentView(R.layout.main);
final ViewSwitcher switcher = (ViewSwitcher)findViewById(R.id.ViewSwitcher1);
Button bbcButton = (Button) findViewById(R.id.bbcButton);
Button bbc2Button = (Button) findViewById(R.id.bbc2Button);
bbcButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
channel = "bbc1";
switcher.showNext();
}
});
bbc2Button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
channel = "bbc2";
switcher.showNext();
}
});
try{
// This line creates RSS reader
RssReader rssReader = new RssReader("http://bleb.org/tv/data/rss.php?ch="+channel+"&day=0");
// This line gets a ListView from main view
ListView tvItems = (ListView) findViewById(R.id.listMainView);
// This line creates a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());
// This line sets list adapter for the ListView
tvItems.setAdapter(adapter);
} catch (Exception e) {
Log.e("Tv RSS Reader", e.getMessage());
}
}
}
I'm guessing that you want to change the RSS feed when you press the button. But since you are fetching the RSS info in the onCreate, you won't update the data, even though you are pressing the buttons. But you are changing the value of the string channel.
onCreate is only called once when you create the activity!
Try moving the try-statement into a seperate method and call this method in your two onClickListeners.
bbc2Button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
channel = "bbc2";
updateRSS();
switcher.showNext();
}
});
public void updateRSS(){
try{
// This line creates RSS reader
RssReader rssReader = new RssReader("http://bleb.org/tv/data/rss.php?ch="+channel+"&day=0");
// This line gets a ListView from main view
ListView tvItems = (ListView) findViewById(R.id.listMainView);
// This line creates a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());
// This line sets list adapter for the ListView
tvItems.setAdapter(adapter);
} catch (Exception e) {
Log.e("Tv RSS Reader", e.getMessage());
}

AsyncTask filling a ListView in a Dialog launched from a button click doesn't work right

I've spent all day trying to figure this out, and it's drinving me nuts, hoping the experts around here can help me figure this out so I stop pulling my hair out. I'm trying to fill a ListView in a Dialog window that pops up when a button is clicked. If I put the asynctask code to start when the activity starts, everything works fine, but if I try to move the code into either where the button OnClickListener, it starts double filling the listview.
Here's the code:
In my OnCreate:
new LoadAllProducts().execute();
Which runs the following code:
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_get_classes, "GET",
params);
// Check your log cat for JSON response
Log.d("All Classes: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// classes found
// Getting Array of Classes
classes = json.getJSONArray(TAG_CLASSES);
// looping through All Classes
for (int i = 0; i < classes.length(); i++) {
JSONObject c = classes.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_CLASSID);
String name = c.getString(TAG_CLASSNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CLASSID, id);
map.put(TAG_CLASSNAME, name);
// adding HashList to ArrayList
classesList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
In my button's OnClickListener, I have the following:
onCreateDialog().show();
which launches the following dialog:
protected Dialog onCreateDialog() {
//Set up dialog
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.checkindialog);
Button canceldialog = (Button) dialog.findViewById(R.id.btncancel);
//Define ListView and set it's empty view in case no results come back
this.lv = (ListView) dialog.findViewById(R.id.lvCheckin);
this.lv.setEmptyView(dialog.findViewById(R.id.empty));
TextView header = (TextView) dialog.findViewById(R.id.lblCheckin);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/roboto-light.ttf");
header.setTypeface(tf);
//ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
// R.layout.checkin_item, R.id.list_content, checkinOptions);
ListAdapter adapter = new SimpleAdapter(Checkin.this, classesList,
R.layout.checkin_item, new String[] { TAG_CLASSID,
TAG_CLASSNAME }, new int[] { R.id.pid, R.id.name });
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listAdapter, View arg1,
int position, long arg3) {
CheckIn checkin = new CheckIn();
TextView txt = (TextView) listAdapter.getChildAt(
position - lv.getFirstVisiblePosition()).findViewById(
R.id.name);
String CheckinMessage = Utilities.getFacebookCheckinMessage(txt
.getText().toString(), context);
checkin.CheckInToFacebook(CheckinMessage, activity);
}
});
canceldialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
return dialog;
}
So like I said, this works fine, except the listview only gets it's data when the activity is launched, and I'm trying to have it happen when the button gets clicked. I've tried two things. Moving the "onCreateDialog().show();" to the "onPostExecute" of the AsncTask, but this doesn't work right, and I've tried moving the "new LoadAllProducts().execute();" into both the ondialog create event, as well as inline with the button click listener. Both of these only end up continually adding to the listview, instead of clearing/refreshing the listview each time.
Really hope someone can help, as I'm sure it's probably something stupid but this has been kicking my butt all day today.
Thanks in advance!
Evan try overriding the protected Dialog onCreateDialog(int id) function for show dialog and also override public void onPrepareDialog(int id, Dialog dialog). In onPrepareDialog function call removeDialog(int id) function this will help in creating a fresh dialog every time and remove previously cached data.

How to access values defined in AsyncTask from an activity

I have code like this
#Override
public void onCreate(Bundle savedInstanceState) {
addItemsOnSpinnerOrgaLevel();
btn_getReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//How can i access map and list defined in orgaLevelTask(AsyncTask)???
Like
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
// Both are defined in AsyncTask ??
}); //end of anonymous class
} //end of onCreate()
public void addItemsOnSpinnerOrgaLevel() {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of addItemsOnSpinnerOrgaLevel()
In AsyncTask onPostExecute() Method i have
#Override
protected void onPostExecute(ArrayList<OrgaLevel> result) {
super.onPostExecute(result);
if (result != null) {
addItemsOnSpinnerOrgaLevel(result);
}
dialog.dismiss();
} //end of onPostExecute()
public void addItemsOnSpinnerOrgaLevel(ArrayList<OrgaLevel> result) {
orgaLevelElementslist = new ArrayList<String>();
orgaLevelElementslist.add("All");
orgaLevelMap = new HashMap<String, Integer>();
orgaLevelMap.put("All", 0);
for (int i=0; i<result.size(); i++) {
OrgaLevel orgaLevelRecord = (OrgaLevel) result.get(i);
String key = orgaLevelRecord.getOrgaName();
String value = orgaLevelRecord.getOrgaCode();
orgaLevelMap.put(key, Integer.parseInt(value));
orgaLevelElementslist.add(key);
} //end of for()
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(accountReportActivity, android.R.layout.simple_spinner_item, orgaLevelElementslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_orgaLevel.setAdapter(dataAdapter);
setSpinnerOrgaLevelListener();
} //end of addItemsOnSpinnerOrgaLevel()
private void setSpinnerOrgaLevelListener() {
spinner_orgaLevel.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
subOrgaLevelTask = new SubOrgaLevelTask(accountReportActivity, spinner_branch, orgaCode);
subOrgaLevelTask.execute();
} //end of onItemSelected()
}); //end of anonymous class
} //end of setSpinnerOrgaLevelListener()
In the subOrgaLevelTask i also have the same hash map as in this class. You can see that what i am trying to do is, put a key value in spinner. So when my btn_getReport button get click then i get the value of the selected item. Like if All is slected then i get 0 and so on. This key value thing is working. The problem is when btn_getReport get click then how can i get the value of the selected item. Because i am filling items in a background thread(In OrgaLevelTask and SubOrgaLevelTask) and my button is in Activity. So how can i do that when button get click, then i get the values from the map defined in OrgaLevelTask and SubOrgaLevelTask ?
Thanks
well, make them public in orgaLevelTask, and simply access them. orgaLevelTask should be a variable in you activity class. Have you tried it? any errors?
You must make sure orgaLevelTask members will be accessed in thread safe manner

Categories

Resources