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, ...))
Related
I have an activity with a button, when the user clicks on the button, an AlertDialog appear with 2 EditText where you put email and password to login.
When I try to get the text from the EditText i always get only empty strings.
The layout login_alert is the layout of the AlertDialog.
Here the code:
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
String email = ((EditText) view.findViewById(R.id.emailEditText)).getText().toString();
String password = ((EditText) view.findViewById(R.id.passwordEditText)).getText().toString();
System.out.println("DEBUG: "+email+", "+password); // Empty strings
EDIT:
Activity code:
public class MainActivity extends FragmentActivity {
public static final String mAPP_ID = "...";
public static final String USER_DB_URL = "...";
AssetsExtracter mTask;
private MainFragment mainFragment;
private List<User> usersList = new ArrayList<User>();
private User currentUser = null;
private Button labLoginButton;
private EditText emailET;
private EditText passwordET;
private ProgressDialog dialog;
private View alertView; /* THIS IS THE SOLUTION */
boolean userIsLogged = false;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
/*View view = getLayoutInflater().inflate(R.layout.login_alert, null, false); BEFORE*/
alertView = getLayoutInflater().inflate(R.layout.login_alert, null, false);
emailET = (EditText) view.findViewById(R.id.emailEditText);
passwordET = (EditText) view.findViewById(R.id.passwordEditText);
labLoginButton = (Button) findViewById(R.id.loginLabButton);
updateLoginButton();
dialog = new ProgressDialog(this);
dialog.setMessage("Signin in...");
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mTask = new AssetsExtracter();
mTask.execute(0);
}
/* THIS METHOD IS CALLED BY THE LOGIN BUTTON IN THE MAIN ACTIVITY LAYOUT */
public void onLabLoginButtonClick(View v) {
if (userIsLogged) {
currentUser = null;
userIsLogged = false;
updateLoginButton();
Toast.makeText(this, "Disconnected from Lab", Toast.LENGTH_SHORT)
.show();
} else {
/*View messageView = getLayoutInflater().inflate(
R.layout.login_alert, null, false); BEFORE */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon_launcher);
builder.setTitle(R.string.login_string);
builder.setView(alertView); /* USING THE GLOBAL VARIABLE */
builder.setPositiveButton("Sign me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog.show();
// Download user and return a List of User
DownloadFilesAsyncTask task = new DownloadFilesAsyncTask(USER_DB_URL) {
#Override
protected void onPostExecute(final List<User> result) {
usersList = result;
loginCheckRoutine(); //HERE I MANAGE THE LOGIN AND GETTING EMPTY STRING
}
};
task.execute();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create();
builder.show();
}
}
public void updateLoginButton() {
if (userIsLogged) {
labLoginButton.setText(R.string.logout_string);
} else {
labLoginButton.setText(R.string.login_string);
}
}
public void loginCheckRoutine() {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
System.out.println("DEBUG: " + email + ", " + password); // EMPTY
// controllo nella lista se c'è l'utente coi dati inseriti
for (int i = 0; i < usersList.size(); i++) {
if (usersList.get(i).getEmail().equals(email)
&& password.equals("admin")) {
currentUser = usersList.get(i);
userIsLogged = true;
updateLoginButton();
dialog.dismiss();
break;
}
}
if (!userIsLogged) {
userIsLogged = false;
updateLoginButton();
dialog.dismiss();
Toast.makeText(MainActivity.this, "Login Failed",
Toast.LENGTH_SHORT).show();
}
}
}
PROBLEM SOLVED, SOLUTION:
In the onCreate() I inflate the alert_dialog layout in a View variable. I made that View variable global (before onCreate()) and then in onLabLoginButtonClick() I don't inflate the view again, but I use that global instantiated in the onCreate(). hope its clear. thank you all!
You getText just after initialization. Untill you have text in xml you won't get the text. In onclick of alertdialog button get the text.
Declare
EdiText ed1,ed2; // before onCreate if in activity and onCraeteView in fragment
as a instance variable
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
ed1= (EditText) view.findViewById(R.id.emailEditText))
ed2 = (EditText) view.findViewById(R.id.emailEditText);
then on Alert dialog Button click
String email = ed1.getText().toString();
String password= ed2.getText().toString()
you must get the text when you click on login button of alert dialog box
the above mentioned code you get text when you show alert dialog it always return always empty string you should follow the following procedure
first you make a custom alert box layout having two edit text and one button
user write text to edittext for login and give password and then click login button
when you call login button click listener you can get text of edittext easyly
You are trying to get the text immediately after you inflated the view. Try doing it when the user clicks the done button instead.
Before onCreate add:
EditText email;
EditText pass;
Add this in your onCreate
etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);
Then add this to when your button is clicked
String email = etEmail.getText().toString();
String pass = etEmail.getText().toString();
Just ensure that the editText.getText.toString() method is inside the OnClick() method, eg:
TextView submit = enquiryFragment.findViewById(R.id.query_submit_button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
query_type = query_type_editText.getText().toString();
query_text = query_editText.getText().toString();
if (query_text.length()!=0 && query_type.length()!=0) {
postQuery(query_type, query_text, store_id);
// Log.e("query_type ",query_type );
}else{
Toast.makeText(getContext(), "Enter something !", Toast.LENGTH_SHORT).show();
}
}
});
Alternatively add a TextChangedListener to you textview to change the change the string every time the textboxtext changes.
A textwatcher is also possible
you should get the text when you click on save or done button.
If you get this text on click of alert dialog button, you may end up taking it multiple times.
I am trying to use an AlertDialog in my app to select the quantity of an item. The problem is that the activity that calls the AlertDialog doesn't wait for it to update the item before it adds it to the SQLite Database and change intents.
At the moment, the QuantitySelector (AlertDialog) appears, then disappears straight away and changes the MealActivity class (which is just a ListView that reads from the database) through the intent change with an update to the database with quantity 0.
I need the Activity to wait for the AlertDialog to close before it updates the database.
What would be the correct way of implementing this?
Here is some code for you:
QuantitySelector (which runs the alertdialog):
public class QuantitySelector{
protected static final int RESULT_OK = 0;
private Context _context;
private DatabaseHandler db;
private HashMap<String, Double> measures;
private Item item;
private View v;
private EditText quan;
private NumberPicker pick;
private int value;
private Quantity quantity;
/**
* Function calls the quantity selector AlertDialog
* #param _c: The application context
* #param item: The item to be added to consumption
* #return The quantity that is consumed
*/
public void select(Context _c, Item item, Quantity quantity){
this._context = _c;
this.item = item;
this.quantity = quantity;
db = new DatabaseHandler(_context);
//Get the measures to display
createData();
//Set up the custom view
LayoutInflater inflater = LayoutInflater.from(_context);
v = inflater.inflate(R.layout.quantity_selector, null);
//Set up the input fields
quan = (EditText) v.findViewById(R.id.quantityNumber);
pick = (NumberPicker) v.findViewById(R.id.numberPicker1);
//Set up the custom measures into pick
pick.setMaxValue(measures.size()-1);
pick.setDisplayedValues(measures.keySet().toArray(new String[0]));
//Start the alert dialog
runDialog();
}
public void createData(){
measures = new HashMap<String, Double>();
//Get the measurements from the database
if(item!=null){
measures.putAll(db.getMeasures(item));
}
//Add grams as the default measurement
if(!measures.keySet().contains("grams")){
//Add grams as a standard measure
measures.put("grams", 1.0);
}
}
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
}
The method from favouritesAdapter (which calls the alertdialog):
add.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
QuantitySelector q = new QuantitySelector();
Quantity quan = new Quantity();
q.select(_context, db.getItem(p.getID()), quan);
db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE");
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
}
});
All help is appreciated :)
Use Async task and update data in doInBackGround and in onPostExecute method Show Dialog.
The way you want to go about this is to actually start the next intent when the person presses the positive button. In short, you need to be starting your next Activity in the OnClickListener that is attached to your positive button of your AlertDialog.
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
dialog.dismiss();
//The only catch now is passing through your _context
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
Actually your problem is you are calling the start activity for MealACtivity before destroying the alert dialogue so can update your code as follows:
Update your method which calls the alertdialogue by this code:
add.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
QuantitySelector q = new QuantitySelector();
Quantity quan = new Quantity();
q.select(_context, db.getItem(p.getID()), quan);
db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE");
/* Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);*/
}
});
and update your Quantity Selector class with the following :
public class QuantitySelector{
protected static final int RESULT_OK = 0;
private Context _context;
private DatabaseHandler db;
private HashMap<String, Double> measures;
private Item item;
private View v;
private EditText quan;
private NumberPicker pick;
private int value;
private Quantity quantity;
/**
* Function calls the quantity selector AlertDialog
* #param _c: The application context
* #param item: The item to be added to consumption
* #return The quantity that is consumed
*/
public void select(Context _c, Item item, Quantity quantity){
this._context = _c;
this.item = item;
this.quantity = quantity;
db = new DatabaseHandler(_context);
//Get the measures to display
createData();
//Set up the custom view
LayoutInflater inflater = LayoutInflater.from(_context);
v = inflater.inflate(R.layout.quantity_selector, null);
//Set up the input fields
quan = (EditText) v.findViewById(R.id.quantityNumber);
pick = (NumberPicker) v.findViewById(R.id.numberPicker1);
//Set up the custom measures into pick
pick.setMaxValue(measures.size()-1);
pick.setDisplayedValues(measures.keySet().toArray(new String[0]));
//Start the alert dialog
runDialog();
}
public void createData(){
measures = new HashMap<String, Double>();
//Get the measurements from the database
if(item!=null){
measures.putAll(db.getMeasures(item));
}
//Add grams as the default measurement
if(!measures.keySet().contains("grams")){
//Add grams as a standard measure
measures.put("grams", 1.0);
}
}
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
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.
I am trying to pass information form one Activity to the other and while doing that I would like to have a progress dialog show. Mainly when the second activity is processing the information. I have been reading up and the proper way of doing it seems to be asynctask. Or is there another way of doing it?
Here is my code: Activity one
public class SearchActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
return true;
}
return false;
}
});
final Button button = (Button) findViewById(R.id.searchButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
}
});
}
}
This is the Second activity:
public class DissertationActivity extends ListActivity {
/** Called when the activity is first created. */
public ArrayList<String> book_Array = new ArrayList<String>();
ArrayAdapter<String> adapter;
String href = "";
String href1 = "";
String search_Word = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
search_Word = extras.getString("query1");
adapter = new ArrayAdapter<String>(this, R.layout.list_item_1,
book_Array);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
try {
Document doc = null;
Document guestLink = null;
guestLink = Jsoup.connect("https://aulib.abdn.ac.uk:443/F").get();
Element link = guestLink.select("p > a").first();
href1 = link.attr("href");
href = href1.substring(0, href1.length() - 2); // removes -0 from
// the
// href_Array.add(href); //adds href to the array because string
// wont add to the public var.
doc = Jsoup.connect(
href + "&request=" + search_Word
+ "&find_code=WRD&adjacent=N&x=0&y=0").get();
// System.out.println(doc);
Elements headings = doc.select("td:eq(3)");
// System.out.println(headings);
for (Element heading : headings) {
// System.out.println(heading.text());
String j = heading.text();
book_Array.add(j);
}
} catch (IOException e) {
e.printStackTrace();
}
book_Array.remove(0);
adapter.notifyDataSetChanged();
book_Array.remove(1);
adapter.notifyDataSetChanged();
book_Array.remove(2);
adapter.notifyDataSetChanged();
book_Array.remove("Search");
adapter.notifyDataSetChanged();
book_Array.remove(" | ");
adapter.notifyDataSetChanged();
book_Array.remove(0);
adapter.notifyDataSetChanged();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
// Context context = getApplicationContext();
int query = position;
// String text = book_Array.get(position);
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,
// String.valueOf(position), //shows the postion in the array
// list
// duration);
// toast.show();
Intent intent = new Intent(DissertationActivity.this,
FullDetailsActivity.class);
intent.putExtra("href", href);
intent.putExtra("query1", (int) query);
intent.putExtra("search_Word", search_Word);
startActivity(intent);
}
});
}
}
I tried using:
this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
But that didn't work.
How would I go about, so that it displays a progress dialog in between the activities?
Thanks for your help!
Calling ProgressDialog.show will block the UI thread. So the progress dialog/bar will not show up until the method has returned. So we can create a thread for our method to run within it. This will avoid blocking the main UI Thread.
Sample code -
ProgressDialog spinnerDialog = ProgressDialog.show(
Placeholder.this, "","Your text ", true);
new Thread(new Runnable() {
public void run() {
//your method code
return;
}
}).start();
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();