found index 0, size is 0 in android - android

"There i found index out of bound exception how can i solve???"
public static void addToCart() {
ArrayList<ItemData> iArr;
if (holdSelection != null) {
String categoryID = holdSelection.getCategoryID();
int position = categoriesAddedd.indexOf(holdSelection.getCategoryID());
int itemPosition =categoriesitemAddedd.indexOf(holdSelection.getItemData().get(0).getItemID());
if (!categoriesAddedd.contains(categoryID)) {
CategoryData data = new CategoryData();
data.setCategoryID(categoryID);
data.setCategoryName(holdSelection.getCategoryName());
data.setItemData(holdSelection.getItemData());
mAddedToCart.add(data);
categoriesAddedd.add(categoryID); categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext,R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
} else {
if (position>=0) {
if(itemPosition>=0){
if(holdSelection.getItemData().get(0).getScaled()){
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}
}else{
try{
CategoryData data = mAddedToCart.get(position);
iArr = data.getItemData();
iArr.add(holdSelection.getItemData().get(0));
categoriesAddedd.add(categoryID);
categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext, R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(mContext, "There is " +e,Toast.LENGTH_SHORT).show();
System.out.println("Exception : "+ e.getMessage());
e.printStackTrace();
}
}
}
}
}
}

It's impossible to help without a minimum of (structured) information (and also without a Hello, please, tank you, polite words if you prefer).
First of all, you have to use the brackets to display code when you post, so your clean code should appear as follow :
public static void addToCart() {
ArrayList iArr;
if (holdSelection != null) {
String categoryID = holdSelection.getCategoryID();
int position = categoriesAddedd.indexOf(holdSelection.getCategoryID());
int itemPosition =categoriesitemAddedd.indexOf(holdSelection.getItemData().get(0).getItemID());
if (!categoriesAddedd.contains(categoryID)) {
CategoryData data = new CategoryData();
data.setCategoryID(categoryID);
data.setCategoryName(holdSelection.getCategoryName());
data.setItemData(holdSelection.getItemData());
mAddedToCart.add(data);
categoriesAddedd.add(categoryID);
categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext,R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
} else {
if (position>=0) {
if(itemPosition>=0){
if(holdSelection.getItemData().get(0).getScaled()){
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}
}else{
try{
CategoryData data = mAddedToCart.get(position);
iArr = data.getItemData(); iArr.add(holdSelection.getItemData().get(0));
categoriesAddedd.add(categoryID);
categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext, R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{ // TODO: handle exception Toast.makeText(mContext, "There is " +e,Toast.LENGTH_SHORT).show();
System.out.println("Exception : "+ e.getMessage()); e.printStackTrace();
}
}
}
}
}
}
then my first question will be : what is holdSelection related to?
Please add more parts of your code as your log (asked by Remees).
Alex.

Related

Sendbird group channel

Currently i have 2 users:
Tester1 and AnotherTester
I've been trying to create a public group channel using my Tester1
but whenever i try to create one.
It's not showing in my list using AnotherTester
Here is my code in creating public group channel
GroupChannelParams params = new GroupChannelParams()
.setPublic(true)
.setDiscoverable(true)
.setEphemeral(false)
// .addUserIds(users)
.setDistinct(false)
.setName(channelName);
GroupChannel.createChannel(params, new GroupChannel.GroupChannelCreateHandler() {
#Override
public void onResult(GroupChannel groupChannel, SendBirdException e) {
if (e != null) { // Error.
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
Logs.logError(e.getMessage());
retrySendConnection(context, String.valueOf(e.getCode()), e.getMessage());
return;
} else {
// inviteUser(groupChannel);
Logs.logData(groupChannel.getUrl());
Intent i = new Intent(MainActivity.this, channelChatActivity.class);
i.putExtra("channelUrl", groupChannel.getUrl());
startActivity(i);
}
}
});
So Tester1 is the one that created a public group channel
but when i switch to AnotherTester, it doesn't show the public group channel.
Here is my code in retrieving AnotherTester channels
GroupChannelListQuery channelListQuery1 = GroupChannel.createMyGroupChannelListQuery();
channelListQuery1.setIncludeEmpty(true);
channelListQuery1.next(new GroupChannelListQuery.GroupChannelListQueryResultHandler() {
#Override
public void onResult(List<GroupChannel> list, SendBirdException e) {
if (e != null) {
Logs.logError(e.getMessage());// Error.
return;
} else {
groupChannelList.addAll(list);
groupChannelAdapter = new groupChannelAdapter(context, groupChannelList);
initializeRecyclerView(channelAdapter);
}
}
});
i hope you can help me.
You need to do atleast one message in that , then it will show to another user. Please try once to send one message.
Please try this code :-
private void createGroupChannel(List<String> userIds, boolean distinct, final String toID) {
GroupChannel.createChannelWithUserIds(userIds, distinct, "tsg-chat-" + SessionUtils.getCurrentMemberId(this) + "-" + toID, "", "", new GroupChannel.GroupChannelCreateHandler() {
#Override
public void onResult(GroupChannel groupChannel, SendBirdException e) {
if (e != null) {
// Error!
return;
}
}
});
}

Android: How to maintain user online/offline status using quickblox?

I had integrated quickblox chat in my application and want to maintain user online and offline status and tried following options.
1) as described in doc i had followed this link https://quickblox.com/developers/SimpleSample-users-android#Online.5COffline_status but one issue is there that it not give clarity about user online status
2) used Ping Manager: https://quickblox.com/developers/Android_XMPP_Chat_Sample#Ping_a_user
but it always give QBResponseException
3) QBRoaster: this option is not suitable as requirement.
[note : I am using quickblox version 3.3.1]
I have implemented QBPingManager as following
public void checkUserOnlineStatus(String mOpponentName) {
QBChatService.getInstance().getPingManager().setPingInterval(1);
Performer<QBUser> qbUser = QBUsers.getUserByLogin(mOpponentName);
qbUser.performAsync(new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser qbUser, Bundle bundle) {
final int mOpponentUserId = qbUser.getId();
final QBPingManager pingManager = QBChatService.getInstance().getPingManager();
pingManager.pingServer(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
pingManager.pingUser(mOpponentUserId, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
Timber.tag(TAG).w("Opponent User is online ");
}
#Override
public void onError(QBResponseException e) {
Timber.tag(TAG).e("message(ping user): " + e.getMessage() + "\n localized message: " + e.getLocalizedMessage());
e.printStackTrace();
}
});
}
#Override
public void onError(QBResponseException e) {
Timber.tag(TAG).e("message (ping server): " + e.getMessage() + "\n localized message: " + e.getLocalizedMessage());
}
});
}
#Override
public void onError(QBResponseException e) {
Timber.tag(TAG).e("Error : " + e.getMessage() + "\n Message : " + e.getLocalizedMessage());
}
});
}
any help is appreciated thank you.
Here we will find online/offline status with last seen time/date :-
To get online/offline status of user you need to send and has to confirm subscription request
// to confirm subscription request
QBSubscriptionListener subscriptionListener = new QBSubscriptionListener() {
#Override
public void subscriptionRequested(int userId) {
try {
if (chatRoster != null)
chatRoster.confirmSubscription(userId);
} catch (SmackException.NotConnectedException e) {
} catch (SmackException.NotLoggedInException e) {
} catch (XMPPException e) {
} catch (SmackException.NoResponseException e) {
}
}
};
chatRoster = QBChatService.getInstance().getRoster(QBRoster.SubscriptionMode.mutual, subscriptionListener);
// to send subscription request
try {
chatRoster.subscribe(qbChatDialog.getRecipientId()); //getRecipientId is Opponent UserID
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
Send presence whenever user comes online/offline
QBPresence presence = new QBPresence(QBPresence.Type.online, "I am now available", 1, QBPresence.Mode.available);
try {
chatRoster.sendPresence(presence);
} catch (SmackException.NotConnectedException e) {
} catch (Exception e) {
e.printStackTrace();
}
Get Presence of opponent user
QBPresence presence = chatRoster.getPresence(qbChatDialog.getRecipientId());
if (presence.getType() == QBPresence.Type.online) {
//online
}else{
//offline
}
Identify when user's online status has been changed
QBRosterListener rosterListener = new QBRosterListener() {
#Override
public void entriesDeleted(Collection<Integer> userIds) {
}
#Override
public void entriesAdded(Collection<Integer> userIds) {
}
#Override
public void entriesUpdated(Collection<Integer> userIds) {
}
#Override
public void presenceChanged(QBPresence presence1) {
try {
int userid = presence1.getUserId();
int recid = qbChatDialog.getRecipientId();//opponent user id
if (userid == recid) {
if (presence1.getType() == QBPresence.Type.online)
status.setText(getResources().getString(R.string.online));
else {
status.setText("");
String lastseen = getlastseen();
if (lastseen.length() > 0) {
status.setText(lastseen);
}
}
} else {
}
} catch (Exception e) {
}
}
};
To get Last Seen of offline user
private String getlastseen() {
String lastseen = "";
String appendstring = "";
try {
long lastUserActivity = QBChatService.getInstance().getLastUserActivity(qbChatDialog.getRecipientId()); //returns last activity in seconds or error
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, -(int) lastUserActivity);
String format = "dd MMM yyyy hh:mm a";
if (DateUtils.isToday(calendar.getTimeInMillis())) {
format = "hh:mm a";
appendstring = ChatActivity.this.getResources().getString(R.string.today) + ",";
} else if (isyesterday(calendar.getTimeInMillis())) {
format = "hh:mm a";
appendstring = ChatActivity.this.getResources().getString(R.string.yesterday) + ",";
} else if (Calendar.YEAR == Calendar.getInstance().YEAR)
format = "dd MMM hh:mm aa";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
lastseen = simpleDateFormat.format(calendar.getTime());
} catch (XMPPException.XMPPErrorException | SmackException.NotConnectedException e) {
} catch (Exception e) {
e.printStackTrace();
}
return appendstring + lastseen;
}
You can use new feature of QuickBlox Android SDK since version 3.3.3 which called 'last activity'. You can call QBChatService.getInstance().getLastUserActivity(userId); As result you will get:
- 0 if opponent online or
- seconds ago opponent was online or
- error if user newer logged to chat.

How to wait first for the retrofit response before returning the boolean

always returning the wrong value, before the request has been finish. The validation will already return the value without waiting for the response. I'am using retrofit for request then i put it on listener.
Thankyou for the help, suggestion is much accepted!.
this is my code, i have validation for the screen when it's true it will goes to another screen.
#Override
public boolean isValid() {
if (NetworkUtils.isConnected(getActivity())) {
final AtomicBoolean pass = new AtomicBoolean(false);
Thread simpleThread = new Thread() {
public void run() {
new ReprintOnlineHelper(rType, receiptNoEditText.getText().toString(), issuedDate, etTotalAmtPaid.getText().toString(), new ReprintOnlineHelper.ReceiptNoSearchListener() {
#Override
public boolean onServiceResponse(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.get(0).getTPAYRECEIPTNO());
if (receiptNumbers.isEmpty()) {
returnValue = "eReceipt Number not found!";
val = true;
} else {
String pdates = null, ddates;
try {
if (!receiptNumbers.get(0).getTPAYISSUEDDATE().isEmpty()) {
Date periodFormat = df.parse(receiptNumbers.get(0).getTPAYISSUEDDATE());
pdates = sdf.format(periodFormat);
}
} catch (ParseException e) {
e.printStackTrace();
Log.e("ddd", "" + e.getMessage());
}
String tinNo = receiptNumbers.get(0).getTPTIN();
if (tinNo.contains("-")) {
tinNo = receiptNumbers.get(0).getTPTIN().replace("-", "");
}
Log.e("JAC", "" + receiptNumbers.get(0).getTPAYRECEIPTNO() + "---" + AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)) + "---" + MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) + "--" + AlfonzoUtils.formatDate(issuedDate) + "--" + receiptNoEditText.getText().toString() + "--" + tinNo + "--"+revenueCollection.getTpTin().replace("-", ""));
if (receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString()) &&
AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))
&& MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) == MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) && tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
pass.set(true);
returnValue = "success";
val = true;
showMessagePrompt(rType,returnValue);
return true;
} else if (!tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
returnValue = "eReceipt Number was not issued to this TIN " + revenueCollection.getTpTin();
val = false;
} else if (!AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))) {
returnValue = "Issued date is not valid";
val = false;
} else if (MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) != MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString())) {
returnValue = "Total amount paid is not valid";
val = false;
} else if (!receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString())) {
returnValue = "ReceiptNo is not valid";
val = false;
}
}
return false;
}
#Override
public void onErrorResponse(int err) {
}
}).reprintReceiptNo();
}
};
if (!receiptNoEditText.getText().toString().isEmpty() && issuedDate != 0 /*&& MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) > 0*/) {
try {
simpleThread.start();
simpleThread.join();
pass.get();
Log.e("pass", "" + pass + "-" + pass.get() + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
return pass.get();
}
}
return false;
}
this is my request in retrofit:
public void reprintReceiptNo() {
JSONObject jO = new JSONObject();
JSONObject result = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jO.put("xReceipt", receiptTypeNo);
jO.put("xType", receipttype);
jsonArray.put(jO);
result.put("dataArray", jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("dataArray", "----- " + result.toString());
ServiceInterface si = BaseRestClient.getClient();
Observable<List<ReceiptNumber>> call = si.getreprintReceiptNumber(result.toString());
call.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ReceiptNumber>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.toString());
onReceiptNoSearchListener.onServiceResponse(receiptNumbers);
}
});
}
Its not possible for the isValid() method to wait for the service reponse if you have code outside the Thread you've created.
The method will execute the Thread, but while that Thread is executing, the rest of the code will be read, meaning the return pass.get(); or the return false; statments will be read, causing the the method to return before the server response.
The solution its to change the way this was done. You should check if you can call the server and then created your logic in the methods onServiceResponse() and onErrorResponse() based on how you want to proceed.

Why do i have a null pointer exception on database calls and what can i do to solve?

new AsyncTask<Ticket, Void, List<TPVLine>>() {
#Override
protected List<TPVLine> doInBackground(Ticket... params) {
List<TPVLine> lines;
while (true){
Log.d(TAG, "Waiting for data base response");
try {
lines = params[0].getLines();
Log.d(TAG, "Data base response completed");
break;
}catch (SQLiteException | NullPointerException ex){
ActiveAndroid.clearCache();
Log.d(TAG, "Cleaning cache");
Log.wtf(TAG, ex.toString());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return lines;
}
#Override
protected void onPostExecute(List<TPVLine> aVoid) {
super.onPostExecute(aVoid);
linesTPV = new ArrayList<TPVLine>();
if (aVoid != null){
linesTPV = aVoid;
}
linesTPV.addAll(noSavedLines);
mainActivity.getTpvFragment().resetPrice();
notifyDataSetChanged();
if (linesTPV.size() == 0){
mainActivity.getTpvFragment().getListContainer().setVisibility(View.INVISIBLE);
mainActivity.getTpvFragment().getMessageContainer().setVisibility(View.VISIBLE);
}else {
mainActivity.getTpvFragment().getListContainer().setVisibility(View.VISIBLE);
mainActivity.getTpvFragment().getMessageContainer().setVisibility(View.INVISIBLE);
}
notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mainActivity.getCurrentTicket());
This are the calls, first in Ticket.java
public List<TPVLine> getLines() {
return new Select().from(TPVLine.class).where("Ticket = ?", this.getId()).execute();
}
The second is in TPVLine.java
public static List<TPVLine> getLines(Ticket ticket){
return new Select().from(TPVLine.class).where("Ticket = ?", ticket.getId()).orderBy("Id ASC").execute();
}
The issue is caused when i call TPVLine.class, i make sure first that Ticket != null. I'm using ActiveAndroid to manage the database
you are returning null instead of lines in your asynctask doInBackground event.
return lines;

Azure mobile service for android query table

I'm using azure sdk for android and follow the tutorial https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-data/.
When I'm trying to connect and insert data to mobile service table all is ok, but when I query the table in activity my app gets stuck, though there are only several entries in the table and execute method successfully returns Future.
public static MobileServiceClient mClient;
public static void connect(Context context) {
try {
mClient = new MobileServiceClient(storageLink, key, context);
} catch (MalformedURLException e) {
Log.e("AzureService.connect", "Storage access failed" + storageLink);
}
}
public static InstallationData get(final String deviceId) {
MobileServiceTable<InstallationData> table= mClient.getTable(InstallationData.class);
final MobileServiceList<InstallationData> result;
try {
result = table.where().field("deviceid").eq(deviceId).execute().get();
for (InstallationData item : result) {
return item;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
public static void store(final InstallationData item) {
mClient.getTable(InstallationData.class).insert(item, new TableOperationCallback<InstallationData>() {
public void onCompleted(InstallationData entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
Log.d("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is successfully updated");
} else {
exception.printStackTrace();
Log.e("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is failed to update");
}
}
});
}
Thank you in advance!

Categories

Resources