Android Prompt Dialogue Box Upon Event Triggered - java

I am having some logic problem with my Java code to prompt dialogue box. So basically when my ratingBar is onTouch, I will get the star rate and prompt dialogue box:
ratingBar.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
float touchPositionX = event.getX();
float width = ratingBar.getWidth();
float starsf = (touchPositionX / width) * 5.0f;
starRate = (int)starsf + 1;
ratingBar.setRating(starRate);
promptSubmitStar();
return true;
}
});
public void promptSubmitStar(){
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate + " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
Dialog.show();
}
But with these codes, when user selected the star rate, the dialogue box prompted twice. I wonder which part is causing it. Thanks in advance.

It's because onTouch listener is called multiple times, i.e. when your finger lands on the screen (ACTION_DOWN) and when you move your finger up (ACTION_UP).
You want to show the dialog when the latter one fires:
ratingBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
float touchPositionX = event.getX();
float width = ratingBar.getWidth();
float starsf = (touchPositionX / width) * 5.0f;
starRate = (int) starsf + 1;
ratingBar.setRating(starRate);
promptSubmitStar();
}
return true;
}
});
I'm not sure why you'd use a touch listener though. You can listen to the RatingBar changes like this:
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar bar, float rating, boolean user) {
promptSubmitStar();
}
});

Related

Java Clearing Object upon Successful DB Insertion

I was having some difficulty when trying to do some logic in Java. When my map is on single tap, I will create a dialog box. If the user select okay from dialog box, I will then call another method to set value for object. Here are the codes:
public void onSingleTap(float x, float y) {
Event eventModelAdd = null;
eventModelAdd = CreateEvent
.createEventDialog(context, point.getX(), point.getY());
if (eventModelAdd != null) {
new MyAsyncTask().execute(eventModelAdd);
}
}
Then in the CreateEvent class:
static Event addEventModel;
public static Event createEventDialog(final Context context,final double x, final double y) {
AlertDialog.Builder AddDialog = new AlertDialog.Builder(context);
AddDialog.setTitle("Add Event");
LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.create_event, null);
txtEventName = (EditText) dialogView.findViewById(R.id.txtEventName);
txtEventDesc = (EditText) dialogView.findViewById(R.id.txtEventDesc);
radioDiscussion = (RadioButton) dialogView
.findViewById(R.id.radioDiscussion);
AddDialog.setView(dialogView);
AddDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
addEventModel = new Event();
addEventModel = onConfirmAddEventClicked(context, x, y);
dialog.dismiss();
}
});
AddDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AddDialog.show();
return addEventModel;
}
public static Event onConfirmAddEventClicked(Context context, double x , double y) {
Event eventModel = new Event();
// Set the value to Event object
}
return eventModel;
}
With these codes, it can perform DB insertion with no errors. But let's say I've successfully inserted a record into database, when I select another point on the map, and the dialog box pop up, and I select Cancel, the previous object record will be inserted into database again.
I wonder which part of my logic was wrong. Thanks in advance.
Edit
public class MyAsyncTask extends AsyncTask<Event, Integer, Double> {
#Override
protected Double doInBackground(Event... params) {
try {
eventCtrl.retrieveEventJSON();
if (params.length == 1) {
eventCtrl.createEvent(params[0]);
//Refresh map after successfully added event
eventCtrl.retrieveEventJSON();
eventCtrl.plotEventOnMap(context);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
}
If possible, move this code :
if (eventModelAdd != null) {
new MyAsyncTask().execute(eventModelAdd);
}
To your dialog's positive button's onClick to make sure the AsyncTask will only be executed when the user click the positive button.

Android - OnTouchListener() is triggered too early

I have an activitiy where I have a button and when a click on this button I want to set a TextView with some value, so I used onClickListening and it is working:
ButtonPlus.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
ponts = ponts + 1;
resultadoTextView.setText(Integer.toString(ponts));
}
});
But the problem is that I want to keep increasing this textView's value while the button keep being pressed so I tried to use the OnTouchLister:
ButtonPlus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ponts = ponts + 1;
resultTextView.setText(Integer.toString(ponts));
}
});
the problem is that when I give a fast click in the button it increments the TextView's value too much and I want the onTouchListener to be activated just after some time that the button was pressed.
any help please?
Use some additional counter.
int additionalCounter = 0;
ButtonPlus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
++additionalCounter;
if (additionalCounter % X == 0) {
ponts = ponts + 1;
resultTextView.setText(Integer.toString(ponts));
}
}
});
You can set X as you want, i.e. setting it to 5 would make touch event working 5 times slower.
Try this code.
ButtonPlus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ponts = ponts + 1;
resultTextView.setText(Integer.toString(ponts));
ButtonPlus.setClickable(false);
//wait 1 second
ButtonPlus.postDelayed(new Runnable() {
#Override
public void run() {
ButtonPlus.setClickable(true);
}
}, 1000);
return false;
}
});

onClick and onLongClick Selection in Textview

I have searched for the answer to this question for a couple of days with no result. When using onClick on a TextView I get the desired result of selecting the word clicked by using:
textView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View arg0) {
Spannable span = (Spannable)textView.getText();
Layout layout = textView.getLayout();
Toast.makeText(arg0.getContext(), "Selection: " + Selection.getSelectionStart(textView.getText().toString()) + Selection.getSelectionEnd(textView.getText().toString()), Toast.LENGTH_SHORT).show();
// returns -1, -1
Toast.makeText(arg0.getContext(), "Selection: " + textView.getSelectionStart() + textView.getSelectionEnd(), Toast.LENGTH_SHORT).show();
//returns -1, -1
Selection.moveToLeftEdge(span, layout);
Selection.extendToRightEdge(span, layout);
final int start = textView.getSelectionStart();
final int end = textView.getSelectionEnd();
String string = textView.getText().toString().substring(start, end);
AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
builder.setTitle("Delete: " + string)
.setMessage("Are you sure? This operation can't be undone!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteItem(start, end);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.show();
return true;
}
});
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Spannable span = (Spannable)textView.getText();
Layout layout = textView.getLayout();
Selection.moveToLeftEdge(span, layout);
Selection.extendToRightEdge(span, layout);
writeStrikes(textView.getSelectionStart(), textView.getSelectionEnd());
}
});
When I try using the same code for an onLongClick the selection is -1, -1. If I return false from onLongClick the next selection is where the last should have been. So, the cursor is set when the user releases the long click, after the onLongClick has been called. How do I set the cursor to the position of the long click just before the onLongClick() is called?

Referencing multiple Checkboxes in AlertDialog

Hey fellow Android Developers, Im having a issue currently with the below code. I am unable to figure out a way i can easily reference which Checkbox is clicked, Currently the code below is simply a Preference that when clicked, displays a AlertDialog with multiple Checkboxes.
The goal is do something specific when that Checkbox is checked, however i want to do something different possibly with each item.
Code
Preference checkboxalert = (Preference) findPreference("checkboxalert");
checkboxalert
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};
final ArrayList<Integer> selectedItems=new ArrayList<Integer>();
public boolean onPreferenceClick(Preference preference) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
//WHERE I WANT TO REFERENCE WHICH CHECKBOX IS CLICKED
selectedItems.add(indexSelected);
Log.i("Preference - Checkbox", "Something was clicked");
} else if (selectedItems.contains(indexSelected)) {
selectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();
return true;
}
});
What's wrong with using the index?
#Override
public void onClick(DialogInterface dialog, int indexSelected,boolean isChecked)
{
if (isChecked) {
selectedItems.add(indexSelected);
//WHERE I WANT TO REFERENCE WHICH CHECKBOX IS CLICKED
switch (indexSelected)
{
case 0:
// do something if the first box is checked
break;
case 1:
// do something if the second box is checked
break;
...
}
}
It seems like this should work unless I am missing what you want.

How to implement an AlertDialog.Builder selected item click event?

I want to implement AlertDialog.Builder selected items click event. Below is what I have tried so far. I'm quite new to Android and I'm not sure how to access that event. How to implement the click event for each individual item in the list?
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class MakeCallAlertDialog {
public static AlertDialog.Builder getAlertDialog(String strArray[],
String strTitle, Activity activity) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(strTitle);
alertDialogBuilder.setItems(strArray, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int arg) {
// TODO Auto-generated method stub
}
});
return alertDialogBuilder;
}
}
Since you assigned an OnClickListener specific to that method, the int parameter is the position in the list:
Parameters
dialog The dialog that received the click.
which The button that was clicked (e.g. BUTTON1) or the position of the item clicked
This means inside your method, you should be able to do this:
public static AlertDialog.Builder getAlertDialog(final String strArray[],
String strTitle, final Activity activity) {
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(strTitle);
alertDialogBuilder.setItems(strArray,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(activity, strArray [which], Toast.LENGTH_SHORT).show();
//rest of your implementation
}
});
return alertDialogBuilder;
}
in onClick() event use switch statement to write click method for each button.
#Override
public void onClick(DialogInterface dialogInterface, int arg) {
// TODO Auto-generated method stub
switch (arg) {
case 0:
//you code for button at 0 index click
break;
case 1:
//you code for button at 1 index click
break;
default:
break;
}
}
Here, arg indicates the index of the button pressed. you can also access that button using strArray[arg]
Check my answer below if you are using single choice item selected for the strArray: Try this code
int selectedItem = 0;
// here take TempSelectOneTypeList = strArray
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
Activity_Form_Data.this);
alt_bld.setTitle("Select One");
selectedItem = 0;
for (int j = 0; j < TempSelectOneTypeList.length; j++) {
if (txt_sub_lable2
.getText()
.toString()
.equals(TempSelectOneTypeList[j].toString())) {
selectedItem = j;
}
}
Log.i(TAG, "Selected Item is " + selectedItem);
alt_bld.setSingleChoiceItems(
ArraylistSelectOneTypeList.get(selected),
selectedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
selectedItem = item;
// you can ocde here for the perticular selected item
}
});
alt_bld.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
txt_sub_lable2
.setText(""
+ TempSelectOneTypeList[selectedItem]
.toString());
}
});
alt_bld.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
Hope it will solve your problem

Categories

Resources