The difference between onratingbarchanged and onratingbarclicked android - android

I've got a rating bar in my android application which is in a custom adapter. I've set the ratingbar to listen for a change and on that change, update the database through a cient/server architecture. I then use the custom adapter in a master/details view. The problem is, everytime I load the details page on click of the left-hand list item, it updates the rating bar. This is not what I want. I only want to update the rating bar once it's been clicked, not everytime the adapter is used.
Is there way to only fire an event when it is clicked and not changed. Is there a major difference between onratingbarchanged (which it is currently) and onratingbarclicked (which I'm assuming is what I should be doing?)
My code is as follows:
//Should this rather be setOnClickListener()???
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener()
{
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser)
{
questions.get(position).TotalRating = rating;
String newRating = "" + rating;
ratingBar.setRating(rating);
Toast.makeText(getContext(),
"Rating set to: " + rating + " for the position: " + position, Toast.LENGTH_SHORT).show();
String question = questions.get(position).Question;
//Create XML with both position/question to send to doAsyncTask
serverUpdateRating update = new serverUpdateRating();
Document doc;
try
{
//Create an XML document with question from the selected position as well as the new rating
doc = x.createDoc();
Element tutor = doc.createElement("Update");
tutor.appendChild(x.UpdateRating(doc, newRating, question));
doc.appendChild(tutor);
//Create a string
String s = x.getStringFromDocument(doc);
String result = update.execute(s).get();
//return either true (updated correctly) or false (problem)
if (result.equals("true"))
{
Toast.makeText(getContext(),
"Rating successfully updated", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getContext(),
"Rating update unsuccessful", Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I don't know if there is a workaround for this, but if there is, I would be extremely grateful!

You could use fromUser in onRatingChanged
onRatingChanged :
[...] fromUser True if the rating change was initiated by a user's touch
gesture or arrow key/horizontal trackbell movement.

Related

How can I update key values in realtime database?

I want to update key values when it removed, so I wrote codes below. These codes are in the Checkbox listener.
What I did first :
if(isChecked) {
Long size = dataSnapshot.child("Bookmark").getChildrenCount();
ref_h.child(userUid).child("Bookmark").child(Long.toString(size + 1)).setValue(diningUid);
} else {
for (int i = 1; i <= dataSnapshot.child("Bookmark").getChildrenCount(); i++) {
if (dataSnapshot.child("Bookmark").child(Integer.toString(i)).getValue().toString().equals(diningUid)) {
dataSnapshot.child("Bookmark").child(Integer.toString(i)).getRef().removeValue();
isRemoved = true;
}
if(isRemoved) {
if(i != dataSnapshot.child("Bookmark").getChildrenCount()){
String newDiningUid;
newDiningUid = dataSnapshot.child("Bookmark").child(Integer.toString(i + 1)).getValue().toString();
Log.d("newUID", newDiningUid);
ref_h.child(userUid).child("Bookmark").child(Integer.toString(i)).setValue(newDiningUid);
} else {
dataSnapshot.child("Bookmark").child(Integer.toString(i)).getRef().removeValue();
}
}
}
}
But when the Checkbox status changes rapidly, key values are messed up.
like this
data structure 2
Then I fixed the code with try-catch phrase.
if(isChecked) {//if not checked before listener runs, add to bookmark
Long size = dataSnapshot.child("Bookmark").getChildrenCount();
ref_h.child(userUid).child("Bookmark").child(Long.toString(size + 1)).setValue(diningUid);
} else {//if checked before listener runs, remove from bookmark
for (int i = 1; i <= dataSnapshot.child("Bookmark").getChildrenCount(); i++) {
try {
if (dataSnapshot.child("Bookmark").child(Integer.toString(i)).getValue().toString().equals(diningUid)) {
dataSnapshot.child("Bookmark").child(Integer.toString(i)).getRef().removeValue();
isRemoved = true;
}
} catch (NullPointerException e) {
if (dataSnapshot.child("Bookmark").child(Integer.toString(i + 1)).getValue().toString().equals(diningUid)) {
dataSnapshot.child("Bookmark").child(Integer.toString(i + 1)).getRef().removeValue();
isRemoved = true;
}
}
if(isRemoved) {
//update afterward value's index
if(i != dataSnapshot.child("Bookmark").getChildrenCount()){
String newDiningUid;
newDiningUid = dataSnapshot.child("Bookmark").child(Integer.toString(i + 1)).getValue().toString();
ref_h.child(userUid).child("Bookmark").child(Integer.toString(i)).setValue(newDiningUid);
} else {//remove last value
try {
dataSnapshot.child("Bookmark").child(Integer.toString(i)).getRef().removeValue();
} catch (NullPointerException e) {
dataSnapshot.child("Bookmark").child(Integer.toString(i + 1)).getRef().removeValue();
}
}
}
}
}
But I don't think I solved this problem.
How can I update key values properly?
or do I need to add a delay to Checkbox?
or change the data structure?
The best solution is to not use sequential numeric keys, but rely on Firebase's push IDs. For reasons on why this is a better approach and how they work, see these classic Firebase blog posts:
Best Practices: Arrays in Firebase
The 2^120 Ways to Ensure Unique Identifiers
If you insist on using array-like keys, you will have to use a transaction on the entire bookmark node to determine the next index. This is the only way to prevent the race condition that you now encounter when the array contents frequently change.

How to check if new added item exist in recyclerView?

Actually i'm developing an inventory app where i scan some EAN codes then i insert the quantity of an item and then i add it to an ArrayList in recyclerView.
For now i had no problem as i've made the inventory part where the items had to have different lines for each in recyclerView but now i have to make the order part and here if an item exist yet in ArrayList i have to sum it's quantity and put it to top of recyclerView.
I was trying to make something like a for loop when i'm going to add a new item and check if it's exist in ArrayList, if it's exist i was going to sum that item quantity with old one but the problem was that sometimes the app was going to crash and that the item wasn't going on top of recyclerView.
Do you have any suggestion on how can i do it?
for (ItemModel item : itemModel) {
if (item.getCodiceArticolo()
.equals(code.getText()
.toString())) {
item.setQta(String.valueOf(
Integer.parseInt(item.getQta()) + 1));
}
}
I was trying to make something like that.
Try this code:
ItemModel matchedItem = null;
int matchedItemIndex = -1;
for (ItemModel item : itemModel) {
if (item.getCodiceArticolo()
.equals(code.getText()
.toString())) {
item.setQta(String.valueOf(
Integer.parseInt(item.getQta()) + 1));
matchedItem = item;
matchedItemIndex = itemModel.indexOf(item);
break;
}
}
if (matchedItemIndex > -1) {
itemModel.remove(matchedItem);
itemModel.add(
0,
matchedItem);
notifyItemMoved(index,
0);
}
You do not adderror log to your list, so I guess your program crashes because sometimes there is a value that has no quantity (there is no valid number) and therefore can not parse the number, so in this case you just write that there is one item in list that has not been there yet.
for (ItemModel item : itemModel) {
if (item.getCodiceArticolo()
.equals(code.getText()
.toString())) {
try {
item.setQta(String.valueOf(
Integer.parseInt(item.getQta()) + 1));
}
catch (Exception ex) {
item.setQta(String.valueOf(1));
}
}
}
If this does not help, please attach error log.
Since the app is crashing, your ArrayList might not have been initialized as suggested in the comments.
For checking if the item exists you can use
if (arraylist_of_items != null && arraylist_of_items.contains(item)) {
// do your stuff here
}
Three days a go i was getting the "ConcurrentModificationException" but now i'm trying another approach inspired by other answers or better the following one:
boolean nuovo = true;
for (ItemModel itemModels : itemModel) {
if (itemModels.getCodiceArticolo()
.equals(code.getText()
.toString())) {
itemModels.setQta(String.valueOf(
Integer.parseInt(itemModels.getQta()) + 1));
nuovo = false;
break;
}
}
if (nuovo) {
itemModel.add(new ItemModel(
code.getText()
.toString(),
"1"));
}
And is not crashing anymore and seems to work fine.
Thank's all for suggestions.
UPDATE
THANKS TO kartik malik ANSWER i was able to even "update" my items by adding the last one added on top, as i'm using reverse recyclerView i've done it by this wasy instead of putting the item to position 0
ItemModel matchedItem = null;
int matchedItemIndex = -1;
boolean nuovo = true;
for (ItemModel itemModels : itemModel) {
if (itemModels.getCodiceArticolo()
.equals(code.getText()
.toString())) {
itemModels.setQta(String.valueOf(
Integer.parseInt(itemModels.getQta()) +
Integer.parseInt(qta.getText()
.toString())));
MediaPlayer mpFound = MediaPlayer.create(
OrdiniActivity.this,
R.raw.errorsound);
mpFound.start();
matchedItem = itemModels;
matchedItemIndex = itemModel.indexOf(itemModels);
nuovo = false;
break;
}
}
if (matchedItemIndex > -1) {
itemModel.remove(matchedItem);
itemModel.add(matchedItem);
}
if (nuovo) {
itemModel.add(new ItemModel(
code.getText()
.toString(),
qta.getText()
.toString()));
}
With the boolean i'm checking if the item exist or not and if it doesn't exist i add the item as a new one.

Integrating Dibs Payment Gateway in Android

I am working on Dibs Payment integration but unable to achieve success. All things are working good in demo mode but when merchant id is supplied to it then before opening card details form it gives an error "Data has been tampered. Checksome is not valid". I dont know what is it. After my googling i found it is something related to MAC calculated but how to calculate MAC in my code. My whole class for payment is as follows with all comments.
public class CheckOut extends Activity {
private static final String TAG = "DIBS." + CheckOut.class.getSimpleName();
private DibsPayment paymentWindow;
public static String total, resname, resid, userid, menunames, itemnames,
itemquantity, ordertype, address, city, contactno, pincode,
deliverttime, orderid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkout);
RandomStringGenerator randomorderid = new RandomStringGenerator();
Intent i = getIntent();
// total=String.valueOf(1);
total = i.getStringExtra("grandTotal");
resname = i.getStringExtra("res_name");
resid = i.getStringExtra("res_id");
userid = i.getStringExtra("user_id");
menunames = i.getStringExtra("menu_names");
itemnames = i.getStringExtra("item_prices");
itemquantity = i.getStringExtra("item_quantity");
ordertype = i.getStringExtra("ordertype");
address = i.getStringExtra("address");
city = i.getStringExtra("city");
contactno = i.getStringExtra("phone");
pincode = i.getStringExtra("pin");
deliverttime = i.getStringExtra("delivery_time");
orderid = randomorderid.getAlphaNumeric(5);
Toast.makeText(
getApplicationContext(),
orderid + "\n" + resname + "\n" + resid + "\n" + userid + "\n"
+ ordertype + "\n" + address + "\n" + city + "\n"
+ pincode + "\n" + contactno + "\n" + deliverttime
+ "\n" + menunames + "\n" + itemnames + "\n"
+ itemquantity + "\n" + total, Toast.LENGTH_SHORT)
.show();
/*
* Intent intent=getIntent(); String []
* arrayList=intent.getStringArrayExtra("payment_item"); // int l_itr =
* arrayList.length; // while(l_itr.hasNext()) { for(int
* i=0;i<=arrayList.length-1;i++){
*
* #SuppressWarnings("rawtypes") //HashMap l_map = (HashMap)
* l_itr.next(); String item=arrayList[i]; Log.v(item, "item"); String
* item =(String)i.get(DatabaseHandler.KEY_ITEM); Log.v(item, "item");
* String unicost= (String)l_map.get(DatabaseHandler.KEY_UNITCOST);
* Log.v(unicost, "unicost"); String l_res_name = (String)
* l_map.get(DatabaseHandler.KEY_QUANTITY); Log.v(l_res_name,
* "quantity"); String l_street = (String)
* l_map.get(DatabaseHandler.KEY_TOTAL); Log.v(l_street, "total"); }
*/
paymentWindow = (DibsPayment) findViewById(R.id.DibsPayment);
// Set your listener implementation, to get callbacks in the life-cycle
// of a payment processing
paymentWindow
.setPaymentResultListener(new MyPaymentResultListener(this));
// Load the payment window with the payment data that suits the payment
// flow you need
// Please be patient, when loading on the emulator
paymentWindow.loadPaymentWindow(constructPaymentData());
}
/**
* Shows a "cancel" action in the options menu on the phone, which shows how
* to call cancel functionality into the payment window to cancel ongoing
* payment processing.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.payment_window_menu, menu);
return true;
}
/**
* If user chose "cancel" in options menu, we call "cancel" into payment
* window.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem_payment_window_cancel:
//
// Calling cancel into payment window cancels the ongoing payment
// processing.
// Because cancelling is an asynchronous process, you will need to
// wait for a callback
// to paymentCancelled on your PaymentResultListener listener,
// before being positive that
// payment window is done cancelling.
//
paymentWindow.cancelPayment();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* #return the payment data instance that is needed as input to
* {#link DibsPayment#loadPaymentWindow(dk.dibs.android.library.PaymentData)}
*/
private PaymentData constructPaymentData() {
// IMPORTANT: This needs to be set to YOUR merchant number, that you
// have obtained through an
// agreement with DIBS.
// you can use the merchant "demo" for a demorun through the payment
// window // read information about demo mode in the documentation
String merchantId = "******";
//String merchantId = "demo";
// The currency the payment is to be processed in
String currencyCode = "DKK";
// You set this to your own orderId value
String yourOrderId = orderid;
// The amount to be paid, given in "least possible unit" (aka: "oerer")
long amount = (new Double(total)).longValue();
// The cards that is allowed to be used in payment window
List<String> payTypes = new ArrayList<String>();
payTypes.add("MC");
payTypes.add("MTRO");
payTypes.add("VISA");
// this will add fee to the payment window.
boolean calcfee = true;
// In this example, we simply use "PurchasePaymentData", which is a
// simple "buy-with-credit-card" flow,
// where no pre-authorization is performed.
//
// Look to other subclasses of PaymentData for the other supported
// flows.
//
PurchasePaymentData paymentData = new PurchasePaymentData(merchantId,
currencyCode, yourOrderId, amount, payTypes);
paymentData.setCalcfee(calcfee);
// Set this flag to "true", if you want to be able to use test cards.
// REMEMBER to reset this to false, in production !!!
paymentData.setTest(true);
// If you want checks (and payment failure) if the orderId you gave
// already have been payed.
paymentData.setUseUniqueOrderIdCheck(false);
// If you want MAC security calculations, you will need to pre-calculate
// a MAC value on your server,
// based on the values you give to this payment window, and set this
// pre-calculated MAC value like this.
//
paymentData.setCalculatedMAC("");
// Payment window supports loading cancel or callback URLs based on
// payment outcome.
// Another, and maybe better, way to do this in an app, is to listen for
// the proper callbacks
// on the listener you set on the payment window, and then do your own
// cancel or payment success
// handling against your own servers.
//
try {
paymentData.setCallbackUrl(new URL(
"http://****.demoprojects.in/accept.php"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
paymentData.setCancelUrl(new URL("http://****.demoprojects.in/accept.php"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
paymentData.setLanguage("en_UK");
paymentData.setTheme(Theme.ANDROID_DIBS);
// If you need to, you can pass custom options to the payment window,
// which will be posted back again.
//
// Map<String, String> yourCustomOptions = new HashMap<String,
// String>();
// yourCustomOptions.put("foo", "bar");
// paymentData.setCustomOptions(yourCustomOptions);
return paymentData;
}
/*
* public void delete() { DatabaseHandler readDatabase = new
* DatabaseHandler( getApplicationContext()); readDatabase.deleteAll(); }
*/
}
This is the first time i am working on payment. Please help me out as security is the main concern here.
Thanks in advance :)
Dibs allow MAC to be calculated by two algorithms The choice of algorithm is up to you. It currently handles MD5 and SHA-1. SHA-1 is recommended by Dibs as it provides better security.
SHA-1(data&currency&method&SecretKey&)
or
MD5(data&currency&method&SecretKey&)
data here is the string containing information regarding the amount and quantity of purchase.
Security > DebiTech DefenderTM > MAC Configuration, here you will find the secret key in dibs dashboard.
Click here for further reference:

Monodroid ListView get selected item typecast error

I have this problem with listview item and hoping that you guys can help me fix this.
My goal is to fill listview with list and when user touches one these items, i want to have another view loaded. Adding items works fine, but when i get the value from selected item and typecast it to the correct object, it comes with " ‘invalid cast’ cannot cast..." and crashes.
FYI, I use the Android 4.0 sim, and these are part of the code:
SetContentView(Resource.Layout.ArchiveList);
ListView lstArchiveList = FindViewById<ListView>(Resource.Id.lstArchive);
if (lstArchiveList != null) {
ArrayAdapter<MobileContracts.Archive> archivesAdapter = new
ArrayAdapter<MobileContracts.Archive>(this, Resource.Layout.ListItem, sessionData.Archives.Archive);
lstArchiveList.Adapter = archivesAdapter;
lstArchiveList.TextFilterEnabled = true;
lstArchiveList.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(lstArchiveList_ItemClick);
archivesAdapter.NotifyDataSetChanged();
}
OnClick event handler:
void lstArchiveList_ItemClick(object sender, AdapterView.ItemClickEventArgs e) {
SetContentView(Resource.Layout.SearchDocuments);
ListView lstEditableIndexList = FindViewById<ListView>(Resource.Id.lstEditableIndexList);
if (lstEditableIndexList != null) {
Console.WriteLine("sender type: {0}", sender.GetType().FullName);
Object currentItem = e.Parent.GetItemAtPosition(e.Position);
MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?
Toast.MakeText(Application, selectedArchive.Name + " => " + selectedArchive.Id, ToastLength.Short).Show();
}
Any help appreciated. Thank's a lot in advance.
Cheers, Inoel
Never mind, I figure this out.
Replace this:
MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?
with this:
System.Reflection.PropertyInfo propertyInfo = currentItem.GetType().GetProperty("Instance");
MobileContracts.Archive selectedArchive = propertyInfo.GetValue(currentItem, null) as MobileContracts.Archive;

How to replace a value from an array list dynamically when a user edits the array of values?

How do I replace a value from an array list dynamically when the user edits the array of values? I used arr_list.set(count,"replace value") inside button click.Action done by using the button click event. So I used count for index of arr_list. I have an issue as I click the button it replaces all the values in arr_list. I want to replace particular edit values done by user.
if (v == right) {
if (riskList.size() == 0) {
} else
{
try {
riskList.set(count2,key.getText().toString());
Log.i("dfDF", "" + count2);
key.setText(riskList.get(count2).toString());
toGetIndex = key.toString();
int indexPlus = riskList.indexOf(toGetIndex);
risk.setText(descList.get(count2).toString());
totalRiskin.setText(count2 + 1 + "/" + totalRisks);
} catch (IndexOutOfBoundsException ex) {
Toast.makeText(SalesEditActivity.this,
"There is no next element", Toast.LENGTH_SHORT)
.show();
}
count2 = count2 + 1;
}
}
I have used previous and next button to display array list values according to index.ie count. I also want edit array list values,it will be replace the current index value.
Try declaring your array list as static.

Categories

Resources