Volley Request Finish error - android

i am working in application in which i use volley for making call to web-services the scenario is like that when i pressed back button i m calling finish() and then when i try to open app from recent apps section request is made for login (the app get minimized before request is made) and Log cat is saying Request.finish below is line for retry policy stringRequest.setRetryPolicy(new DefaultRetryPolicy(40000 *2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); if still other code is required i will post ...any help is appriciated
Here is the Code for Volleyrequest.java
public class VolleyRequest {
private static VolleyRequest instance;
private ProgressDialog progressDialog;
private Gson gson;
private Map<String, Integer> urlWiseResponseCheck = null;
// host address url
public static final String HOST_URL = "Host Url";
private static final String HOST_ADDRESS_PRIVATE = HOST_URL + "private/mobile/v1/";
private static final String HOST_ADDRESS_PUBLIC = HOST_URL + "public/mobile/v1/";
/**
* 1 == loginAuthentication
*/
public static final String CHECK_LOGIN_AUTH = HOST_ADDRESS_PUBLIC + "check-login-authentication/";
/**
* 2 == add user
*/
public static final String ADD_USER = HOST_ADDRESS_PUBLIC + "add-user/";
/**
* 3 == add user with picture
*/
public static final String ADD_USER_WITH_PIC = HOST_ADDRESS_PUBLIC + "add-user-with-pic/";
/**
* 4 == get workout calorie map
*/
public static final String GET_WORKOUT_CALORIE = HOST_ADDRESS_PUBLIC + "get-workout-calorie-map/";
/**
* 5 == add activity record
*/
public static final String ADD_ACTIVITY_RECORD = HOST_ADDRESS_PRIVATE + "add-activity-record/";
/**
* 6 == add history pictures
*/
public static final String ADD_HISTORY_PICTURE = HOST_ADDRESS_PRIVATE + "add-history-picture/";
/**
* 7 == update logout flag
*/
public static final String SET_LOGOUT_FLAG = HOST_ADDRESS_PRIVATE + "set-logout-flag/";
/**
* 8 == get history by history id
*/
public static final String GET_HISTORY = HOST_ADDRESS_PRIVATE + "get-history/";
/**
* 9 == get history by user id
*/
public static final String GET_HISTORY_BY_ID = HOST_ADDRESS_PRIVATE + "get-user-history/";
// friend request
/**
* 10 == add friend request
*/
public static final String ADD_FRIEND_REQUEST = HOST_ADDRESS_PRIVATE + "add-friend-request-record/";
/**
* 11 == change friend status
*/
public static final String CHANGE_STATUS = HOST_ADDRESS_PRIVATE + "change-friend-req-status/";
/**
* 12 == change trace status
*/
public static final String CHANGE_TRACE_STATUS = HOST_ADDRESS_PRIVATE + "change-trace-status/";
/**
* 13 == get friend with trace status
*/
public static final String GET_FRIEND_WITH_TRACE_STATUS = HOST_ADDRESS_PRIVATE + "get-friend-with-trace-status";
/**
* 14 == get user with friend status
*/
public static final String GET_ALL_USER_WITH_STATUS = HOST_ADDRESS_PRIVATE + "get-all-friend-with-status/";
/**
* 15 == get tracer user list
*/
public static final String GET_TRACED_USER_LIST = HOST_ADDRESS_PRIVATE + "get-all-trace-user/";
/**
* 16 == send invitation mail
*/
public static final String SEND_MAIL = HOST_ADDRESS_PRIVATE + "send-mail/";
/**
* 17 == add user log
*/
public static final String ADD_USER_LOG = HOST_ADDRESS_PUBLIC + "add-log-file";
/**
* 18 == delete history
*/
public static final String DELETE_USER_HISTORY = HOST_ADDRESS_PRIVATE + "delete-user-history/";
public static final String AUTH_TOKEN_REQUEST = HOST_URL + "oauth/token";
public static final String SET_SHARE_FLAG = HOST_ADDRESS_PRIVATE + "share-user-history/";
/**
* 20 == Get last activity
*/
public static final String GET_LAST_ACTIVITY = HOST_ADDRESS_PRIVATE + "get-last-activity/";
public static final String GET_CHALLENGE = HOST_ADDRESS_PRIVATE + "get-challenges/";
public static final String SUSPEND_CHALLENGE = HOST_ADDRESS_PRIVATE + "suspend-challenge/";
public static final String INVITE_PARTICIPANTS = HOST_ADDRESS_PRIVATE + "invite-participants/";
public static final String SAVE_CHALLENGE = HOST_ADDRESS_PRIVATE + "save-challenge/";
public static final String JOIN_CHALLENGE = HOST_ADDRESS_PRIVATE + "join-challenge/";
public static final String GET_CHALLENGE_PARTICIPANT = HOST_ADDRESS_PRIVATE + "get-challenge-participant/";
public static final String GET_PARTICIPANTS = HOST_ADDRESS_PRIVATE + "get-participants/";
public static final String REMOVE_PARTICIPANT = HOST_ADDRESS_PRIVATE + "remove-participant/";
public static final String JOIN_OPEN_CHALLENGE = HOST_ADDRESS_PRIVATE + "join-open-challenge/";
/**
* define final constant
*/
private final int CHECK_LOGIN_AUTH_VALUE = 1;
private final int ADD_USER_VALUE = 2;
private final int ADD_USER_WITH_PIC_VALUE = 3;
private final int GET_WORKOUT_CALORIE_VALUE = 4;
private final int ADD_ACTIVITY_RECORD_VALUE = 5;
private final int ADD_HISTORY_PICTURE_VALUE = 6;
private final int SET_LOGOUT_FLAG_VALUE = 7;
private final int GET_HISTORY_VALUE = 8;
private final int GET_HISTORY_BY_ID_VALUE = 9;
private final int ADD_FRIEND_REQUEST_VALUE = 10;
private final int CHANGE_STATUS_VALUE = 11;
private final int CHANGE_TRACE_STATUS_VALUE = 12;
private final int GET_FRIEND_WITH_TRACE_STATUS_VALUE = 13;
private final int GET_ALL_USER_WITH_STATUS_VALUE = 14;
private final int GET_TRACED_USER_LIST_VALUE = 15;
private final int SEND_MAIL_VALUE = 16;
private final int ADD_USER_LOG_VALUE = 17;
private final int DELETE_USER_HISTORY_VALUE = 18;
private final int SET_SHARE_FLAG_VALUE = 19;
private final int GET_LAST_ACTIVITY_VALUE = 20;
public static final int GET_CHALLENGE_VALUE = 21;
private final int SUSPEND_CHALLENGE_VALUE = 22;
private final int INVITE_PARTICIPANTS_VALUE = 23;
public static final int JOIN_CHALLENGE_VALUE = 24;
public static final int GET_CHALLENGE_PARTICIPANT_VALUE = 25;
public static final int GET_PARTICIPANTS_VALUE = 26;
public static final int REMOVE_PARTICIPANT_VALUE = 27;
public static final int JOIN_OPEN_CHALLENGE_VALUE = 28;
private VolleyRequest() {
}
public static VolleyRequest getInstance() {
if (instance == null) {
instance = new VolleyRequest();
}
return instance;
}
/**
* initialization Url with Map
*/
public void initializationUrlMap() {
gson = CommonUtil.getGson();
if (urlWiseResponseCheck == null) {
urlWiseResponseCheck = new HashMap<String, Integer>();
urlWiseResponseCheck.put(CHECK_LOGIN_AUTH, CHECK_LOGIN_AUTH_VALUE);
urlWiseResponseCheck.put(ADD_USER, ADD_USER_VALUE);
urlWiseResponseCheck.put(ADD_USER_WITH_PIC, ADD_USER_WITH_PIC_VALUE);
urlWiseResponseCheck.put(GET_WORKOUT_CALORIE, GET_WORKOUT_CALORIE_VALUE);
urlWiseResponseCheck.put(ADD_ACTIVITY_RECORD, ADD_ACTIVITY_RECORD_VALUE);
urlWiseResponseCheck.put(ADD_HISTORY_PICTURE, ADD_HISTORY_PICTURE_VALUE);
urlWiseResponseCheck.put(SET_LOGOUT_FLAG, SET_LOGOUT_FLAG_VALUE);
urlWiseResponseCheck.put(GET_HISTORY, GET_HISTORY_VALUE);
urlWiseResponseCheck.put(GET_HISTORY_BY_ID, GET_HISTORY_BY_ID_VALUE);
urlWiseResponseCheck.put(ADD_FRIEND_REQUEST, ADD_FRIEND_REQUEST_VALUE);
urlWiseResponseCheck.put(CHANGE_STATUS, CHANGE_STATUS_VALUE);
urlWiseResponseCheck.put(CHANGE_TRACE_STATUS, CHANGE_TRACE_STATUS_VALUE);
urlWiseResponseCheck.put(GET_FRIEND_WITH_TRACE_STATUS, GET_FRIEND_WITH_TRACE_STATUS_VALUE);
urlWiseResponseCheck.put(GET_ALL_USER_WITH_STATUS, GET_ALL_USER_WITH_STATUS_VALUE);
urlWiseResponseCheck.put(GET_TRACED_USER_LIST, GET_TRACED_USER_LIST_VALUE);
urlWiseResponseCheck.put(SEND_MAIL, SEND_MAIL_VALUE);
urlWiseResponseCheck.put(ADD_USER_LOG, ADD_USER_LOG_VALUE);
urlWiseResponseCheck.put(DELETE_USER_HISTORY, DELETE_USER_HISTORY_VALUE);
urlWiseResponseCheck.put(SET_SHARE_FLAG, SET_SHARE_FLAG_VALUE);
urlWiseResponseCheck.put(GET_LAST_ACTIVITY, GET_LAST_ACTIVITY_VALUE);
urlWiseResponseCheck.put(GET_CHALLENGE, GET_CHALLENGE_VALUE);
urlWiseResponseCheck.put(SUSPEND_CHALLENGE, SUSPEND_CHALLENGE_VALUE);
urlWiseResponseCheck.put(INVITE_PARTICIPANTS, INVITE_PARTICIPANTS_VALUE);
urlWiseResponseCheck.put(JOIN_CHALLENGE, JOIN_CHALLENGE_VALUE);
urlWiseResponseCheck.put(GET_CHALLENGE_PARTICIPANT, GET_CHALLENGE_PARTICIPANT_VALUE);
urlWiseResponseCheck.put(GET_PARTICIPANTS, GET_PARTICIPANTS_VALUE);
urlWiseResponseCheck.put(REMOVE_PARTICIPANT, REMOVE_PARTICIPANT_VALUE);
urlWiseResponseCheck.put(JOIN_OPEN_CHALLENGE, JOIN_OPEN_CHALLENGE_VALUE);
}
}
/**
* send server request using volley
*
* #param url
* #param parameterJson
* #param object object[0] == context variable object[1] == Object variable
*/
public void sendRequest(final String url, final String parameterJson, final Object... object) {
if (!CommonUtil.TRY_OUT_USER || url.equals(VolleyRequest.GET_WORKOUT_CALORIE)) {
if (CommonUtil.isNetworkAvailable((Context) object[0])) {
if (!url.equals(VolleyRequest.GET_TRACED_USER_LIST) && !url.equals(VolleyRequest.GET_WORKOUT_CALORIE) && !url.equals(VolleyRequest.GET_LAST_ACTIVITY) && !url.equals(VolleyRequest.GET_FRIEND_WITH_TRACE_STATUS)) {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = null;
}
progressDialog = new ProgressDialog((Context) object[0], R.style.CustomProgressDialog);
startProgressDialog();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Listener<String>() {
#Override
public void onResponse(String response) {
getResponse(response, url, parameterJson, object);
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onError(error, url, parameterJson, object);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return getParameter(url, parameterJson, object);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
if (url.equals(CHECK_LOGIN_AUTH) || url.equals(ADD_USER) || url.equals(ADD_USER_WITH_PIC) || url.equals(ADD_USER_LOG)) {
return CommonUtil.getHeaders((Context) object[0], false);
} else {// private request
return CommonUtil.getHeaders((Context) object[0], true);
}
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000 *2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance((Context) object[0]).addRequest(stringRequest);
} else {
AlertMsg.showToast((Context) object[0], "You do not have internet connection");
}
}
}
private void onError(VolleyError error, String url, String parameterJson, Object[] objects) {
if (error instanceof AuthFailureError) {
CommonUtil.EXPIRE_TIME = null;
sendRequest(url, parameterJson, objects);
} else {
dismissProgressDialog();
AlertMsg.networkAlertDialog((Context) objects[0]);
}
}
/**
* get response from server
*
* #param response
* #param url
* #param parameterJson
* #param object
*/
private void getResponse(String response, String url, String parameterJson, Object... object) {
dismissProgressDialog();
if (response != null) {
int value = urlWiseResponseCheck.get(url);
switch (value) {
case CHECK_LOGIN_AUTH_VALUE:
UserInfo userInfo = gson.fromJson(parameterJson, UserInfo.class);
if ((Context) object[0] instanceof SplashScreenActivity) {
CommonUtil.checkAuthentication((Context) object[0], response, true, userInfo.getPassword());
} else if ((Context) object[0] instanceof LoginActivity) {
CommonUtil.checkAuthentication((Context) object[0], response, false, userInfo.getPassword());
} else if ((Context) object[0] instanceof GetPushNotificarionFromParse) {
((GetPushNotificarionFromParse) object[0]).getResponse(response);
} else if ((Context) object[0] instanceof TraceUserActivity) {
((TraceUserActivity) object[0]).getLoginResponse(response);
}
break;
case ADD_USER_VALUE:
UserInfo userInfo2 = gson.fromJson(parameterJson, UserInfo.class);
if (object.length > 1 && object[1] instanceof AccountDetailFragment) {
((AccountDetailFragment) object[1]).getResponse(userInfo2);
} else if (object.length > 1 && object[1] instanceof SettingMenuActivity) {
((SettingMenuActivity) object[1]).getResponse();
} else {
if (userInfo2.isFirstTime()) {
CommonUtil.setSubscriptionFlag((Context) object[0], true);
}
CommonUtil.showMainActivity((Context) object[0], response, userInfo2.getPassword());
}
break;
case GET_WORKOUT_CALORIE_VALUE:
Type type = new TypeToken<Map<String, Map<Double, Double>>>() {
}.getType();
Map<String, Map<Double, Double>> workoutCalorieMap = gson.fromJson(response, type);
CommonUtil.setWorkoutCalorieMap(workoutCalorieMap);
break;
case ADD_ACTIVITY_RECORD_VALUE:
if (object[0] instanceof AddWorkoutDetails) {
((AddWorkoutDetails) object[0]).finish();
} else if (object[1] instanceof SaveActivityRecord) {
((SaveActivityRecord) object[1]).getResponse(response);
} else if (object[1] instanceof MainFragment) {
CommonUtil.getUserHistory().setId(response);
}
break;
case SET_LOGOUT_FLAG_VALUE:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences((Context) object[0]);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(ActivityConstant.EMAIL, null);
editor.putString(ActivityConstant.USER_PASSWORD, null);
editor.commit();
Intent intent = new Intent((Context) object[0], LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
((Activity) object[0]).startActivity(intent);
((Activity) object[0]).finish();
break;
case GET_HISTORY_VALUE:
if (object[1] instanceof HistoryFragment) {
((HistoryFragment) object[1]).getResponse(response);
} else if (object[1] instanceof TotalWorkoutDetailFragment) {
((TotalWorkoutDetailFragment) object[1]).getResponse(response);
}
break;
case GET_HISTORY_BY_ID_VALUE:
if ((Context) object[0] instanceof TraceUserActivity) {
((TraceUserActivity) (Context) object[0]).getResponse(response);
} else if (object.length > 1 && object[1] instanceof HistoryFragment) {
((HistoryFragment) object[1]).getHistoryItem(response);
}
break;
case CHANGE_STATUS_VALUE:
if ((Context) object[0] instanceof GetPushNotificarionFromParse) {
((GetPushNotificarionFromParse) object[0]).getResponse();
} else if ((Context) object[0] instanceof PendingUserList) {
((PendingUserList) object[0]).finish();
}
break;
case CHANGE_TRACE_STATUS_VALUE:
if ((Context) object[0] instanceof GetPushNotificarionFromParse) {
((GetPushNotificarionFromParse) object[0]).getResponse();
}
break;
case GET_FRIEND_WITH_TRACE_STATUS_VALUE:
if (object[1] instanceof FriendFragment) {
((FriendFragment) object[1]).getResponse(response);
} else if (object[1] instanceof ShowTraceFriendActivity) {
((ShowTraceFriendActivity) object[1]).getResponse(response);
}
break;
case GET_ALL_USER_WITH_STATUS_VALUE:
Type collectionType = new TypeToken<Collection<UserWithFriendStatus>>() {
}.getType();
List<UserWithFriendStatus> allRecordList = gson.fromJson(response, collectionType);
if (object[0] instanceof AddFriendFromContact) {
((AddFriendFromContact) object[0]).getRecordFromServer(allRecordList);
} else if (object[0] instanceof AddFriendFromHealthWel) {
((AddFriendFromHealthWel) object[0]).getRecordFromServer(allRecordList);
} else if (object[0] instanceof PendingUserList) {
((PendingUserList) object[0]).getRecordFromServer(allRecordList);
} else if (object[0] instanceof ParticipantHw) {
((ParticipantHw) object[0]).getRecordFromServer(allRecordList);
}
break;
case GET_TRACED_USER_LIST_VALUE:
if (object[1] instanceof MainFragment) {
((MainFragment) object[1]).getTraceUserResponse(response);
}
break;
case ADD_USER_LOG_VALUE:
if (object[1] instanceof SplashScreenActivity) {
((SplashScreenActivity) object[1]).getResponse();
}
// ((MainActivity) (Context) object[0]).finish();
break;
case DELETE_USER_HISTORY_VALUE:
if ((Context) object[0] instanceof OverViewActivity) {
((OverViewActivity) object[0]).getResponse();
}
break;
case SET_SHARE_FLAG_VALUE:
if ((Context) object[0] instanceof FacebookIntegration) {
((FacebookIntegration) object[0]).getResponse();
} else if ((Context) object[0] instanceof GooglePlusIntegration) {
((GooglePlusIntegration) object[0]).getResponse();
}
break;
case GET_LAST_ACTIVITY_VALUE:
if ((Context) object[0] instanceof MainActivity) {
((MainActivity) object[0]).getLastActivityResponse(response);
}
break;
case GET_CHALLENGE_VALUE:
case SUSPEND_CHALLENGE_VALUE:
case INVITE_PARTICIPANTS_VALUE:
case JOIN_CHALLENGE_VALUE:
case GET_CHALLENGE_PARTICIPANT_VALUE:
case GET_PARTICIPANTS_VALUE:
case REMOVE_PARTICIPANT_VALUE:
case JOIN_OPEN_CHALLENGE_VALUE:
if (object[1] instanceof ResponseListener) {
((ResponseListener) object[1]).onResponse(response, value);
}
break;
}
}
}
/**
* getParameter VolleyRequest
*
* #param url
* #param parameters
* #param object
* #return Map<String,String>
*/
private Map<String, String> getParameter(String url, String parameters, Object[] object) {
Map<String, String> params = new HashMap<String, String>();
int value = urlWiseResponseCheck.get(url);
if (value == CHECK_LOGIN_AUTH_VALUE || value == ADD_USER_VALUE) {
params.put(ActivityConstant.USER_JSON, parameters);
} else if (value == SET_LOGOUT_FLAG_VALUE || value == GET_HISTORY_VALUE || value == GET_FRIEND_WITH_TRACE_STATUS_VALUE || value == GET_ALL_USER_WITH_STATUS_VALUE
|| value == GET_TRACED_USER_LIST_VALUE || value == GET_LAST_ACTIVITY_VALUE || value == GET_CHALLENGE_VALUE) {
params.put(ActivityConstant.USER_ID, CommonUtil.getUserInfo().getId());
} else if (value == CHANGE_STATUS_VALUE || value == CHANGE_TRACE_STATUS_VALUE) {
params.put(ActivityConstant.FRIEND_JSON, parameters);
} else if (value == GET_HISTORY_BY_ID_VALUE || value == DELETE_USER_HISTORY_VALUE) {
params.put(ActivityConstant.HISTORY_ID, parameters);
} else if (value == SET_SHARE_FLAG_VALUE) {
params.put(ActivityConstant.HISTORY_ID, parameters);
if ((Context) object[0] instanceof FacebookIntegration) {
params.put(ActivityConstant.FACEBOOK_SHARE, ActivityConstant.FACEBOOK_SHARE);
} else {
params.put(ActivityConstant.FACEBOOK_SHARE, ActivityConstant.GOOGLE_SHARE);
}
} else if (value == ADD_FRIEND_REQUEST_VALUE) {
params.put(ActivityConstant.ADD_FRIEND, parameters);
} else if (value == ADD_USER_LOG_VALUE) {
params.put(ActivityConstant.ADD_LOG_FILE, parameters);
} else if (value == SEND_MAIL_VALUE) {
if ((object[0] instanceof AddFriendFromHealthWel) || object[0] instanceof ParticipantHw) {
UserInfo receiverUser = (UserInfo) object[1];
String subject = ActivityConstant.FRIEND_REQUEST_SUBJECT.replace("{SENDER_NAME}", CommonUtil.getUserInfo().getFirstName());
String body = ActivityConstant.FRIEND_REQUEST_BODY.replace("{RECEIVER_NAME}", receiverUser.getFirstName()).replace("{SENDER_NAME}", CommonUtil.getUserInfo().getFirstName());
params.put(ActivityConstant.MAIL_TO, parameters);
params.put(ActivityConstant.MAIL_SUBJECT, subject);
params.put(ActivityConstant.MAIL_BODY, body);
} else if (object[0] instanceof AddFriendFromContact) {
if (object[1] != null) {
UserInfo receiverUser = (UserInfo) object[1];
String subject = ActivityConstant.FRIEND_INVITATION_SUBJECT.replace("{SENDER_NAME}", CommonUtil.getUserInfo().getFirstName());
String body = ActivityConstant.FRIEND_REQUEST_BODY.replace("{RECEIVER_NAME}", receiverUser.getFirstName()).replace("{SENDER_NAME}", CommonUtil.getUserInfo().getFirstName());
params.put(ActivityConstant.MAIL_TO, parameters);
params.put(ActivityConstant.MAIL_SUBJECT, subject);
params.put(ActivityConstant.MAIL_BODY, body);
} else {
UserInfo receiverUser = (UserInfo) object[1];
String subject = ActivityConstant.FRIEND_REQUEST_SUBJECT.replace("{SENDER_NAME}", CommonUtil.getUserInfo().getFirstName());
String body = ActivityConstant.FRIEND_REQUEST_BODY.replace("{RECEIVER_NAME}", receiverUser.getFirstName()).replace("{SENDER_NAME}", CommonUtil.getUserInfo().getFirstName());
params.put(ActivityConstant.MAIL_TO, parameters);
params.put(ActivityConstant.MAIL_SUBJECT, subject);
params.put(ActivityConstant.MAIL_BODY, body);
// TODO : friend request.
}
} else if (object[0] instanceof MainActivity) {
params.put(ActivityConstant.MAIL_TO, parameters);
String subject = ActivityConstant.ERROR_LOG_TEMPLATE.replace("{USER_ID}", CommonUtil.getUserInfo().getId());
params.put(ActivityConstant.MAIL_SUBJECT, subject);
params.put(ActivityConstant.MAIL_BODY, ActivityConstant.log);
}
dismissProgressDialog();
} else if (value == ADD_ACTIVITY_RECORD_VALUE) {
params.put(ActivityConstant.ACTIVITY_RECORD_JSON, parameters);
} else if (value == SUSPEND_CHALLENGE_VALUE || value == GET_PARTICIPANTS_VALUE) {
params.put(ActivityConstant.CHALLENGE_ID_JSON, parameters);
} else if (value == INVITE_PARTICIPANTS_VALUE) {
params.put(ActivityConstant.INVITE_PARTICIPANT_JSON, parameters);
} else if (value == JOIN_CHALLENGE_VALUE) {
params.put(ActivityConstant.CODE_JSON, (String) object[2]);
params.put(ActivityConstant.USER_ID, CommonUtil.getUserInfo().getId());
if (CommonUtil.isNotNull(parameters)) {
params.put(ActivityConstant.PAYMENT_JSON, parameters);
}
} else if (value == GET_CHALLENGE_PARTICIPANT_VALUE) {
params.put(ActivityConstant.CODE_JSON, parameters);
} else if (value == REMOVE_PARTICIPANT_VALUE) {
params.put(ActivityConstant.CHALLENGE_ID_JSON, parameters);
params.put(ActivityConstant.PARTICIPANT_ID, (String) object[2]);
} else if (value == JOIN_OPEN_CHALLENGE_VALUE) {
params.put(ActivityConstant.CHALLENGE_ID_JSON, parameters);
params.put(ActivityConstant.USER_ID, (String) object[2]);
}
return params;
}
/**
* start Progress Dialog
*/
public void startProgressDialog() {
if (progressDialog != null && !progressDialog.isShowing()) {
progressDialog.show();
progressDialog.setCancelable(false);
}
}
/**
* dismiss Progress Dialog
*/
public void dismissProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}

Related

Recyclerview Inconsistency detected. Invalid view holder adapter positionViewHolder

In my app right now I am working with two lists. One is a List of an Object and the other the a List of Lists of the same object. I have a method in my Activity that transforms a list of Object into a List of Lists of object. And to my adapter I am passing the list of lists through this call:
mAdapter.swap(transformList(pipe.mList));
The method swap is responsible for passing the transformed list to my Adapter:
public void swap(List<List<Feed>> feedList) {
if (finallist == null) {
finallist = new ArrayList<>();
}
finallist.clear();
finallist.addAll(feedList);
}
The transformation checks if there are images in a row and puts all of them inside a single list (I am trying to implement something similar to WhatsApp image grouping). So I have a bunch of messages, they can be text messages, files, images, etc. In case of the last one, I group them in a single list.
Let me give a scenario as an example:
I have four images and 1 text message in my original array. The transformation puts all the four images into a single List of objects and de text message in another list of objects (both of them are inserted in my list of lists).
I thought about two ways to handle this transformation: 1 - do it inside the Adapter and 2 - do it in my Activity and pass the modified list to the Adapter. Each one of this solutions generated a different problem.
By following the steps in 1, I was able to display all of the content almost in the way I wanted. The grouping was working just fine! The problem is that if the original array had a length equals to 30, and the transformed array's length was decreased to 12. The RecyclerView would show all of the remaining 18 items as empty states (so after the transformation it wasn't handling the removing items properly).
By following the steps in 2, I was not able to display all of the content. Just the first element of my array. And I would get a IndexOutOfBoundsException in RecyclerView happens java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder error message. But I was not able to identify the problem. I checked many questions here and none of them helped me.
This is my Adapter class:
public class FeedAdapter extends BaseSkeletonAdapter<Feed> implements FeedHolder.FeedHolderListener{
private static final int HOLDER_COMMENT = 1;
private static final int HOLDER_IMAGE = 2;
private static final int HOLDER_FILE = 3;
private static final int HOLDER_AUDIO = 4;
private static final int HOLDER_MARKER = 5;
private static final int HOLDER_EMPTY = 6;
private static final int HOLDER_GROUP = 7;
private final FeedItemListener mListener;
private final int mAvatarSize;
private final String mUserId;
private final int mPictureSize;
private final int mSkeletonColor;
public static List<List<Feed>> finallist;
public FeedAdapter(FeedItemListener listener, String userId, int avatarSize, int pictureSize, int skeletonColor) {
super(2);
mListener = listener;
mUserId = userId;
mAvatarSize = avatarSize;
mPictureSize = pictureSize;
mSkeletonColor = skeletonColor;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case HOLDER_COMMENT:
case HOLDER_IMAGE:
case HOLDER_FILE:
case HOLDER_MARKER:
case HOLDER_AUDIO:
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_feed, parent, false);
return new FeedHolder(view, this, mPictureSize);
case HOLDER_GROUP:
System.out.println("É um grupo!!!");
View viewGroup = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_feed_group,parent,false);
return new FeedHolder(viewGroup, this, mPictureSize);
case HOLDER_EMPTY:
default:
View empty = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_empty, parent, false);
return new EmptyPlaceholderViewHolder(empty, R.string.placeholder_feed_empty_title, R.string.placeholder_feed_empty_description, R.drawable.ic_feed_placeholder);
}
}
#Override
protected void onBind(RecyclerView.ViewHolder holder, int position) {
if(!(holder instanceof EmptyPlaceholderViewHolder)){
//Feed feed = finallist.get(position).get(0);
if (holder instanceof FeedHolder) {
if (position < finallist.size()) {
if (mUserId.equals(finallist.get(position).get(0).getCreatedById())) {
((FeedHolder) holder).onBind(finallist.get(position), mUserId, mAvatarSize);
} else {
((FeedHolder) holder).onBind(finallist.get(position), mUserId, mAvatarSize);
}
}
}
}
}
#Override
protected void onBind(RecyclerView.ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
onBindViewHolder(holder, position);
}else {
if (holder instanceof FeedHolder) {
((FeedHolder) holder).onBind(finallist.get(position), payloads, mUserId, mAvatarSize);
}
}
}
#Override
protected void setHolderSkeleton(RecyclerView.ViewHolder holder) {
if (holder instanceof FeedHolder) {
((FeedHolder) holder).setHolderSkeleton(R.drawable.rounded_skeleton, mSkeletonColor);
}
}
#Override
protected void clearHolderSkeleton(RecyclerView.ViewHolder holder) {
if (holder instanceof FeedHolder) {
((FeedHolder) holder).clearHolderSkeleton();
}
}
#Override
public int getItemViewType(int position) {
if(mSkeletonMode){
return HOLDER_COMMENT;
} if (finallist != null && finallist.size() > 0 && position >= 0 && position < finallist.size()) {
System.out.println("Tamanho total: " + finallist.size());
if (finallist.get(position).size() > 1) {
System.out.println("Tamanho do grupo: " + finallist.get(position).size());
return HOLDER_GROUP;
} else {
Feed feed = finallist.get(position).get(0);
if (feed != null) {
String type = feed.getFeedType();
if (type != null) {
switch (type) {
case FEED_IMAGE:
return HOLDER_IMAGE;
case FEED_AUDIO:
return HOLDER_AUDIO;
case FEED_FILE:
return HOLDER_FILE;
case FEED_MARKER:
return HOLDER_MARKER;
case FEED_COMMENT:
default:
return HOLDER_COMMENT;
}
}
}
}
return HOLDER_COMMENT;
}else {
System.out.println("Tá vazia!");
return HOLDER_EMPTY;
}
}
public List<Feed> getItems() {
return returnList(finallist);
}
public List<List<Feed>> getListItems() {
return finallist;
}
public void swap(List<List<Feed>> feedList) {
if (finallist == null) {
finallist = new ArrayList<>();
}
finallist.clear();
finallist.addAll(feedList);
}
#Override
public void toggleLike(final int pos){
if(mListener != null && pos >= 0 && pos < finallist.size()){
mListener.toggleLike(finallist.get(pos).get(0));
}
}
#Override
public void onLongClick(final int pos, final View v) {
if (mListener != null && pos >= 0 && pos < finallist.size()) {
mListener.onLongClick(finallist.get(pos).get(0), v);
}
}
#Override
public int onAudioActionClicked(final int pos, final int progress) {
if (mListener != null) {
return mListener.onAudioActionClicked(pos, finallist.get(pos).get(0), progress);
}else {
return 0;
}
}
#Override
public void onClick(int pos) {
if (finallist!=null && pos >= 0 && pos<finallist.size()) {
Feed feed = finallist.get(pos).get(0);
if (feed != null && mListener != null) {
mListener.onClick(feed);
}
}
}
public interface FeedItemListener {
void toggleLike(#NonNull Feed feed);
void onLongClick(#NonNull Feed feed, #NonNull View v);
void onClick(#NonNull Feed feed);
int onAudioActionClicked(int pos, #NonNull Feed feed, final int progress);
}
private void transformList(List<Feed> mItems) {
finallist = new ArrayList<>();
for (int i = 0; i< mItems.size();i++) {
List<Feed> feed = new ArrayList<>();
feed.add(mItems.get(i));
finallist.add(feed);
}
int j = 0;
List<String> list = new ArrayList<>();
List<Integer> indexList = new ArrayList<>();
//System.out.println("Tamanho: " + mItems.size());
for (int i = 0; i < mItems.size(); i++) {
if (!mItems.get(i).getFeedType().equals("filePicture")) {
if (j >= 4) {
String temp = "";
for (int k = 0; k < j; k++) {
temp = temp + "->" + Integer.toString(i - (k+1));
if (k != 0) {
finallist.get(i - 1).add(finallist.get(i - (k + 1)).get(0));
indexList.add(i - (k+1));
}
}
list.add(temp);
}
j = 0;
} else {
j = j + 1;
}
if (i == mItems.size()-1) {
//System.out.println("Imagem por ultimo!");
if (j >= 4) {
//System.out.println("Grupo vem por ultimo!");
String temp = "";
for (int k = 0; k < j; k++) {
temp = temp + "->" + Integer.toString(i - (k));
if (k != 0) {
finallist.get(i).add(finallist.get(i - (k)).get(0));
indexList.add(i - (k));
}
}
list.add(temp);
}
}
}
Collections.sort(indexList);
int aux = 0;
for (int i = 0; i < indexList.size();i++) {
//System.out.println("Valor da posição: " + indexList.get(i)+ "\nTipo: "+ finallist.get((indexList.get(i).intValue())+aux).get(0).getFeedType()
// +"\nValor da posição + i: " + (indexList.get(i)+aux) + "\nAux: " + aux);
finallist.remove((indexList.get(i).intValue())+aux);
//notifyItemRangeRemoved(0, finallist.size());
//notifyDataSetChanged();
aux = aux - 1;
}
/*for (int i = 0; i< finallist.size(); i++){
if (finallist.get(i).size() > 1) {
System.out.println("groupImage: " + finallist.get(i).size());
} else {
System.out.println(finallist.get(i).get(0).getFeedType());
}
}*/
//returnList(finallist);
notifyItemRangeRemoved(0, returnList(finallist).size() - finallist.size() - 1);
//notifyItemRangeInserted(0, finallist.size());
}
public List<Feed> returnList(List<List<Feed>> lists) {
List<Feed> list = new ArrayList<>();
if (lists != null) {
for (int i = 0; i < lists.size(); i++) {
if (lists.get(i).size() > 1) {
for (int j = 0; j < lists.get(i).size(); j++) {
list.add(lists.get(i).get(j));
}
} else {
list.add(lists.get(i).get(0));
}
}
System.out.println("Tamanho de list: " + list.size());
}
return list;
}
}
And this is my Activity:
public abstract class FeedActivity extends UltraBaseActivity implements FeedAdapter.FeedItemListener, AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
private static final String EXTRA_PROJECT_ID = "extra_project_id";
private static final String EXTRA_PROJECT_NAME = "extra_project_name";
private static final String EXTRA_RESOURCE_ID = "extra_resource_id";
private static final String EXTRA_RESOURCE_NAME = "extra_resource_name";
private static final String EXTRA_RESOURCE_KIND = "extra_resource_kind";
#BindView(R.id.swipeLayout) SwipeRefreshLayout mRefreshLayout;
#BindView(R.id.recyclerView) RecyclerView mRecyclerView;
#BindView(R.id.feedCreateFragment) View mFeedCreateLayout;
#BindView(R.id.mic) ImageView mMicView;
private WeakReference<FeedCreateFragment> mFeedCreateFragment;
protected FeedViewModel mViewModel;
protected FeedAdapter mAdapter;
private Feed mLongClick;
private Toolbar mToolbar;
protected int mScrollTo = -1;
protected WrapContentLinearLayoutManager mLayoutManager;
private String mPlayingFeedId;
private int mPlayingPos;
private int mActionResourcePause = R.drawable.ic_pause_black_24dp;
private int mActionResourcePlay = R.drawable.ic_play_black_24dp;
private MediaPlayer mPlayer;
private AudioManager mAudioManager;
protected Handler mAudioHandler;
protected Runnable mUpdateAudioHolderRunnable = new Runnable() {
#Override
public void run() {
try {
if (mPlayer != null && mPlayer.isPlaying()) {
notifyAdapterAudioUpdate(mPlayer.getCurrentPosition(), mActionResourcePause);
mAudioHandler.postDelayed(this, 100);
} else {
mAudioHandler.removeCallbacks(mUpdateAudioHolderRunnable);
}
} catch (IllegalStateException e){
MyLog.e(TAG, "Error while updating seed bar", e);
mAudioHandler.removeCallbacks(mUpdateAudioHolderRunnable);
}
}
};
public static void start(#NonNull Context context, #NonNull String projectId, #NonNull String projectName, #NonNull String resourceId, #NonNull String resourceName, #NonNull String resourceKind){
Intent intent = setIntent(context, projectId, projectName, resourceId, resourceName, resourceKind);
if (intent == null) return;
context.startActivity(intent);
}
public static void startForResult(#NonNull Fragment fragment, #NonNull String projectId, #NonNull String projectName, #NonNull String resourceId, #NonNull String resourceName, #NonNull String resourceKind){
Intent intent = setIntent(fragment.getContext(), projectId, projectName, resourceId, resourceName, resourceKind);
if (intent == null) return;
fragment.startActivityForResult(intent, Constants.Intents.INTENT_REQUEST_VIEW_FEED);
}
#Nullable
protected static Intent setIntent(#NonNull Context context, #NonNull String projectId, #NonNull String projectName, #NonNull String resourceId, #NonNull String resourceName, #NonNull String resourceKind) {
Intent intent;
if (resourceKind.equals(Task.ROUTE)) {
intent = new Intent(context, FeedTaskActivity.class);
}else if(resourceKind.equals(Chat.ROUTE)){
intent = new Intent(context, FeedChatActivity.class);
} else {
MyLog.e(TAG, "Error invalid resource Kind - " + resourceKind);
return null;
}
intent.putExtra(EXTRA_PROJECT_ID, projectId);
intent.putExtra(EXTRA_PROJECT_NAME, projectName);
intent.putExtra(EXTRA_RESOURCE_ID, resourceId);
intent.putExtra(EXTRA_RESOURCE_NAME, resourceName);
intent.putExtra(EXTRA_RESOURCE_KIND, resourceKind);
return intent;
}
public FeedActivity() {
super(R.layout.activity_feed);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
isLogged();
init(getIntent(), savedInstanceState);
super.onCreate(savedInstanceState);
initAdapter();
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mAudioHandler = new Handler();
mViewModel.subscribe()
.compose(this.<Resource<List<Feed>>>bindUntilEvent(ActivityEvent.DESTROY))
.flatMap(flatMapDiffUtils())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onNext(), onError(), onCompleted());
}
#NonNull
private Func1<Resource<List<Feed>>, Observable<FeedViewModel.Pipe>> flatMapDiffUtils() {
return new Func1<Resource<List<Feed>>, Observable<FeedViewModel.Pipe>>() {
#Override
public Observable<FeedViewModel.Pipe> call(Resource<List<Feed>> r) {
if (mViewModel.hasResource()) {
List<Feed> old = mAdapter.getItems();
MyLog.i(TAG, "New length: " + (r.data != null ? r.data.size() : 0) + " - Old: " + old.size());
final FeedDiffCallback cb = new FeedDiffCallback(old, r.data, mUser.getId());
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(cb);
return Observable.just(new FeedViewModel.Pipe(r.data, result, r.status == Status.LOADING && (r.data ==null || r.data.size() == 0)));
} else {
MyLog.i(TAG, "Loading resource from server");
return Observable.empty();
}
}
};
}
private Action1<? super FeedViewModel.Pipe> onNext() {
return new Action1<FeedViewModel.Pipe>() {
#Override
public void call(FeedViewModel.Pipe pipe) {
if (pipe != null) {
initFeedFragment();
mRefreshLayout.setRefreshing(false);
pipe.mDiffResult.dispatchUpdatesTo(mAdapter);
mAdapter.setSkeletonMode(pipe.mSkeletonMode);
//List<List<Feed>> list = new ArrayList<>();
//list = tranformList(pipe.mList);
mAdapter.swap(transformList(pipe.mList));
System.out.println("Tamanho desse troço: " + transformList(pipe.mList).size());
//mAdapter.notifyDataSetChanged();
//mAdapter.notifyItemRangeRemoved(0, pipe.mList.size());
if (mScrollTo == -1) {
mRecyclerView.scrollToPosition(mAdapter.getItemCount()-1);
}else {
mRecyclerView.scrollToPosition(mScrollTo);
}
updateMenuOptions();
showLoading(false);
}
}
};
}
protected Action0 onCompleted() {
return new Action0() {
#Override
public void call() {
MyLog.i(TAG, "Finishing feed activity");
finish();
}
};
}
protected Action1<Throwable> onError() {
return new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
MyLog.e(TAG, "Error", throwable);
}
};
}
#Override
protected void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if(mToolbar !=null) {
if (mViewModel != null) {
mToolbar.setTitle(mViewModel.getProjectName());
mToolbar.setSubtitle(mViewModel.getResourceName());
}
mToolbar.setSubtitleTextColor(ContextCompat.getColor(this, R.color.palette_black));
mToolbar.setNavigationIcon(R.drawable.ic_action_back_black);
}
setSupportActionBar(mToolbar);
if (mToolbar != null) {
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
protected void updateTitle(){
if(mToolbar !=null && mViewModel != null) {
mToolbar.setTitle(mViewModel.getProjectName());
mToolbar.setSubtitle(mViewModel.getResourceName());
}
}
#Override
protected void userUpdated(User user) { }
private void init(Intent i, Bundle b){
if (i != null) {
initViewModel(
i.getStringExtra(EXTRA_PROJECT_ID),
i.getStringExtra(EXTRA_PROJECT_NAME),
i.getStringExtra(EXTRA_RESOURCE_ID),
i.getStringExtra(EXTRA_RESOURCE_NAME),
i.getStringExtra(EXTRA_RESOURCE_KIND));
}else if(b != null){
initViewModel(
b.getString(EXTRA_PROJECT_ID),
b.getString(EXTRA_PROJECT_NAME),
b.getString(EXTRA_RESOURCE_ID),
b.getString(EXTRA_RESOURCE_NAME),
b.getString(EXTRA_RESOURCE_KIND));
}else {
MyLog.i(TAG, "Error while initializing view model");
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_PROJECT_ID, mViewModel.getProjectId());
outState.putString(EXTRA_PROJECT_NAME, mViewModel.getProjectName());
outState.putString(EXTRA_RESOURCE_ID, mViewModel.getResourceId());
outState.putString(EXTRA_RESOURCE_NAME, mViewModel.getResourceName());
outState.putString(EXTRA_RESOURCE_KIND, mViewModel.getResourceKind());
}
private void initAdapter(){
mAdapter = new FeedAdapter(
this,
mUser.getId(),
getResources().getDimensionPixelSize(R.dimen.task_avatar_size),
(int) (AndroidUtils.getScreenWidth(this) * 0.6),
ContextCompat.getColor(this, R.color.bg_skeleton)
);
mRefreshLayout.setColorSchemeResources(R.color.yellow, android.R.color.darker_gray, R.color.yellow_edit_note, android.R.color.background_dark);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mScrollTo = -1;
mViewModel.reload();
}
});
mLayoutManager = new WrapContentLinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
private void initFeedFragment(){
if(!(mFeedCreateFragment != null && mFeedCreateFragment.get() != null && getSupportFragmentManager().findFragmentById(R.id.feedCreateFragment) instanceof FeedCreateFragment)){
mFeedCreateFragment = new WeakReference<>(FeedCreateFragment.newInstance(mViewModel.getProjectId(), mViewModel.getResourceId(), mViewModel.getResourceKind(), mViewModel.getResourceUsers()));
getSupportFragmentManager()
.beginTransaction()
.add(R.id.feedCreateFragment, mFeedCreateFragment.get())
.commitAllowingStateLoss();
if (mViewModel.canCreateFeed()) {
mFeedCreateLayout.setVisibility(View.VISIBLE);
}else {
mFeedCreateLayout.setVisibility(View.GONE);
}
}
}
protected abstract void initViewModel(String projectId, String projectName, String resourceId, String resourceName, String resourceKind);
protected abstract void updateMenuOptions();
}
This is part of the Error (the text reached the maximum size):
10-18 17:29:14.702 23722-23722/com.construct.test E/WrapContentLinearLayoutManager: IndexOutOfBoundsException in RecyclerView happens
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{615b449 position=3 id=-1, oldPos=0, pLpos:0 scrap [attachedScrap] tmpDetached no parent}
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5297)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5479)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595)
at com.construct.v2.adapters.WrapContentLinearLayoutManager.onLayoutChildren(WrapContentLinearLayoutManager.java:20)
My problem was caused by the BaseSkeletonAdapter<Feed> that my FeedAdapter was extending. BaseSkeletonAdapter was using the original list and not the List of Lists I had to use. So I created a new class SkeletonAdapterFeed that is basically equal to the previous one, but the new one is receiving a List of Lists instead of just the List.
I know that it sounds a little confusing. I don't have full understanding of the project I am working right now so that's why I don't know everything about the classes, etc.

How to do Filter listview in android?

How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.

Android ExoPlayer not resuming after network is connected

Im using Exoplayer for HLS Streaming in my App. Its playing nicely but when i disconnect the internet connection and enable it again,Exo player does not resume the video play.
Exoplayer is handling this by default or do i need to manually handle this?
here is my code..`
public class PlayerActivity extends Activity implements SurfaceHolder.Callback, OnClickListener,
DemoPlayer.Listener, DemoPlayer.CaptionListener, DemoPlayer.Id3MetadataListener,
AudioCapabilitiesReceiver.Listener { public class PlayerActivity extends Activity implements SurfaceHolder.Callback, OnClickListener,
DemoPlayer.Listener, DemoPlayer.CaptionListener, DemoPlayer.Id3MetadataListener,
AudioCapabilitiesReceiver.Listener {
// For use within demo app code.
public static final String CONTENT_ID_EXTRA = "content_id";
public static final String CONTENT_TYPE_EXTRA = "content_type";
public static final String PROVIDER_EXTRA = "provider";
// For use when launching the demo app using adb.
private static final String CONTENT_EXT_EXTRA = "type";
private static final String TAG = "PlayerActivity";
private static final int MENU_GROUP_TRACKS = 1;
private static final int ID_OFFSET = 2;
private static final CookieManager defaultCookieManager;
static {
defaultCookieManager = new CookieManager();
defaultCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
}
private EventLogger eventLogger;
private MediaController mediaController;
private View debugRootView;
private View shutterView;
private AspectRatioFrameLayout videoFrame;
private SurfaceView surfaceView;
private TextView debugTextView;
private TextView playerStateTextView;
private SubtitleLayout subtitleLayout;
private Button videoButton;
private Button audioButton;
private Button textButton;
private Button retryButton;
static TextView bitrateTextView;
private static DemoPlayer player;
private DebugTextViewHelper debugViewHelper;
private boolean playerNeedsPrepare;
private long playerPosition;
private boolean enableBackgroundAudio;
private Uri contentUri;
private int contentType;
private String contentId;
private String provider;
RotateAnimation rotate;
ImageView rotateLoad=null;
ImageView loadMid=null;
FrameLayout videoLoad;
private String vidLink ="";
private String title =""; private TextView vodTitle;
private String description =""; private TextView vodDesc;
private String vodimage =""; private ImageView vodThumb;
private String chimage =""; private ImageView chLogo;
private String datetitle =""; private TextView vodTimeDesc, videoCurrentTime, videoTimeEnd;
private Bitmap vodImgThumb, chImgLogo;
private static FrameLayout guideInfo;
private FrameLayout seekBar;
private FrameLayout playPause;
private int rewindRate = 1;
private int forwardRate = 1, stopPosition ;
private SeekBar sb;
CountDownTimer ct;
int infoFade = 0 , seekFade =0 , height, width;
private boolean isPlaying = false;
static long storeBitRate;
private AudioCapabilitiesReceiver audioCapabilitiesReceiver;
// Activity lifecycle
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_activity);
View root = findViewById(R.id.root);
shutterView = findViewById(R.id.shutter);
debugRootView = findViewById(R.id.controls_root);
videoFrame = (AspectRatioFrameLayout) findViewById(R.id.video_frame);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceView.getHolder().addCallback(this);
debugTextView = (TextView) findViewById(R.id.debug_text_view);
playerStateTextView = (TextView) findViewById(R.id.player_state_view);
subtitleLayout = (SubtitleLayout) findViewById(R.id.subtitles);
mediaController = new KeyCompatibleMediaController(this);
mediaController.setAnchorView(root);
// retryButton = (Button) findViewById(R.id.retry_button);
// retryButton.setOnClickListener(this);
videoButton = (Button) findViewById(R.id.video_controls);
audioButton = (Button) findViewById(R.id.audio_controls);
textButton = (Button) findViewById(R.id.text_controls);
playPause = (FrameLayout)findViewById(R.id.videoPlayPause);
videoLoad = (FrameLayout) findViewById(R.id.videoLoad);
sb = (SeekBar)findViewById(R.id.seekBar1);
// Guide Info Animator
guideInfo = (FrameLayout)findViewById(R.id.guide_info);
seekBar = (FrameLayout)findViewById(R.id.video_seek);
playPause = (FrameLayout)findViewById(R.id.videoPlayPause);
videoCurrentTime = (TextView)findViewById(R.id.video_timestart);
bitrateTextView=(TextView)findViewById(R.id.bitratetext);
videoTimeEnd = (TextView)findViewById(R.id.video_timeend);
seekBar.setVisibility(View.GONE);
playPause.setVisibility(View.GONE);
root.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE
|| keyCode == KeyEvent.KEYCODE_MENU) {
return false;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
}
return mediaController.dispatchKeyEvent(event);
}
});
CookieHandler currentHandler = CookieHandler.getDefault();
if (currentHandler != defaultCookieManager) {
CookieHandler.setDefault(defaultCookieManager);
}
audioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this, this);
audioCapabilitiesReceiver.register();
}
#Override
public void onNewIntent(Intent intent) {
releasePlayer();
playerPosition = 0;
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Bundle extras = getIntent().getExtras();
contentUri = intent.getData();
contentType = Util.TYPE_HLS;
title = extras.getString("title", title);
description = extras.getString("description", description);
vodimage = extras.getString("vodimage", vodimage);
chimage = extras.getString("chimage", chimage);
datetitle = extras.getString("datetitle", datetitle);
// Set Data
vodTitle = (TextView)findViewById(R.id.vodTitle);
vodTitle.setText(title);
vodDesc = (TextView)findViewById(R.id.vodDesc);
/* DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(player.getMainHandler(), null);
String dfg=bandwidthMeter.getBitrateEstimate()+"";*/
vodDesc.setText(description);
vodThumb = (ImageView)findViewById(R.id.vodThumb);
chLogo = (ImageView)findViewById(R.id.chLogo);
vodTimeDesc = (TextView)findViewById(R.id.vodTimeDesc);
vodTimeDesc.setText(datetitle);
rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(2000);
rotate.setRepeatCount(Animation.INFINITE);
rotate.setInterpolator(new LinearInterpolator());
rotateLoad= (ImageView) findViewById(R.id.lycaLoadMid_rotate);
loadMid = (ImageView) findViewById(R.id.lycaLoadMid);
rotateLoad.startAnimation(rotate);
videoLoad = (FrameLayout) findViewById(R.id.videoLoad);
//Gathering images
LoadImages loadImage= new LoadImages ();
loadImage.execute(vodimage,chimage);
if (player == null) {
// if (!maybeRequestPermission()) {
preparePlayer(true);
//}
} else {
player.setBackgrounded(false);
}
}
#Override
public void onPause() {
super.onPause();
if (!enableBackgroundAudio) {
releasePlayer();
} else {
player.setBackgrounded(true);
}
shutterView.setVisibility(View.VISIBLE);
}
#Override
public void onDestroy() {
super.onDestroy();
audioCapabilitiesReceiver.unregister();
releasePlayer();
}
// OnClickListener methods
#Override
public void onClick(View view) {
if (view == retryButton) {
preparePlayer(true);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
// AudioCapabilitiesReceiver.Listener methods
#Override
public void onAudioCapabilitiesChanged(AudioCapabilities audioCapabilities) {
if (player == null) {
return;
}
boolean backgrounded = player.getBackgrounded();
boolean playWhenReady = player.getPlayWhenReady();
releasePlayer();
preparePlayer(playWhenReady);
player.setBackgrounded(backgrounded);
}
// Permission request listener method
// Internal methods
private RendererBuilder getRendererBuilder() {
String userAgent = Util.getUserAgent(this, "ExoPlayerDemo");
switch (contentType) {
case Util.TYPE_SS:
return new SmoothStreamingRendererBuilder(this, userAgent, contentUri.toString(),
new SmoothStreamingTestMediaDrmCallback());
case Util.TYPE_DASH:
return new DashRendererBuilder(this, userAgent, contentUri.toString(),
new WidevineTestMediaDrmCallback(contentId, provider));
case Util.TYPE_HLS:
return new HlsRendererBuilder(this, userAgent, contentUri.toString());
case Util.TYPE_OTHER:
return new ExtractorRendererBuilder(this, userAgent, contentUri);
default:
throw new IllegalStateException("Unsupported type: " + contentType);
}
}
private void preparePlayer(boolean playWhenReady) {
if (player == null) {
player = new DemoPlayer(getRendererBuilder());
player.addListener(this);
player.setCaptionListener(this);
player.setMetadataListener(this);
player.seekTo(playerPosition);
playerNeedsPrepare = true;
mediaController.setMediaPlayer(player.getPlayerControl());
mediaController.setEnabled(true);
eventLogger = new EventLogger();
eventLogger.startSession();
player.addListener(eventLogger);
player.setInfoListener(eventLogger);
player.setInternalErrorListener(eventLogger);
//debugViewHelper = new DebugTextViewHelper(player, debugTextView);
// debugViewHelper.start();
}
if (playerNeedsPrepare) {
player.prepare();
playerNeedsPrepare = false;
updateButtonVisibilities();
}
player.setSurface(surfaceView.getHolder().getSurface());
player.setPlayWhenReady(playWhenReady);
guideInfo.setVisibility(View.VISIBLE);
guideInfo.postDelayed(new Runnable() { public void run() { guideInfo.setVisibility(View.GONE); } }, 5000);
}
private void releasePlayer() {
if (player != null) {
debugViewHelper.stop();
debugViewHelper = null;
playerPosition = player.getCurrentPosition();
player.release();
player = null;
eventLogger.endSession();
eventLogger = null;
}
}
// DemoPlayer.Listener implementation
#Override
public void onStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
showControls();
}
if (playbackState == ExoPlayer.STATE_BUFFERING) {
if(videoLoad.getVisibility()==View.GONE){
videoLoad.setVisibility(View.VISIBLE);
}
}
if (playbackState == ExoPlayer.STATE_READY) {
videoLoad.setVisibility(View.GONE);
}
if (playbackState == ExoPlayer.STATE_ENDED) {
videoLoad.setVisibility(View.GONE);
finish();
}
if(playWhenReady){
}
String text = "playWhenReady=" + playWhenReady + ", playbackState=";
switch(playbackState) {
case ExoPlayer.STATE_BUFFERING:
text += "buffering";
break;
case ExoPlayer.STATE_ENDED:
text += "ended";
break;
case ExoPlayer.STATE_IDLE:
text += "idle";
break;
case ExoPlayer.STATE_PREPARING:
text += "preparing";
break;
case ExoPlayer.STATE_READY:
text += "ready";
break;
default:
text += "unknown";
break;
}
// playerStateTextView.setText(text);
updateButtonVisibilities();
}
#Override
public void onError(Exception e) {
String errorString = null;
if (e instanceof UnsupportedDrmException) {
// Special case DRM failures.
UnsupportedDrmException unsupportedDrmException = (UnsupportedDrmException) e;
errorString = getString(Util.SDK_INT < 18 ? R.string.error_drm_not_supported
: unsupportedDrmException.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown);
} else if (e instanceof ExoPlaybackException
&& e.getCause() instanceof DecoderInitializationException) {
// Special case for decoder initialization failures.
DecoderInitializationException decoderInitializationException =
(DecoderInitializationException) e.getCause();
if (decoderInitializationException.decoderName == null) {
if (decoderInitializationException.getCause() instanceof DecoderQueryException) {
errorString = getString(R.string.error_querying_decoders);
} else if (decoderInitializationException.secureDecoderRequired) {
errorString = getString(R.string.error_no_secure_decoder,
decoderInitializationException.mimeType);
} else {
errorString = getString(R.string.error_no_decoder,
decoderInitializationException.mimeType);
}
}
else {
errorString = getString(R.string.error_instantiating_decoder,
decoderInitializationException.decoderName);
}
}
if (errorString != null) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_LONG).show();
}
playerNeedsPrepare = true;
updateButtonVisibilities();
showControls();
}
#Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,
float pixelWidthAspectRatio) {
shutterView.setVisibility(View.GONE);
videoFrame.setAspectRatio(
height == 0 ? 1 : (width * pixelWidthAspectRatio) / height);
}
// User controls
private void updateButtonVisibilities() {
// retryButton.setVisibility(playerNeedsPrepare ? View.VISIBLE : View.GONE);
videoButton.setVisibility(haveTracks(DemoPlayer.TYPE_VIDEO) ? View.VISIBLE : View.GONE);
audioButton.setVisibility(haveTracks(DemoPlayer.TYPE_AUDIO) ? View.VISIBLE : View.GONE);
textButton.setVisibility(haveTracks(DemoPlayer.TYPE_TEXT) ? View.VISIBLE : View.GONE);
}
private boolean haveTracks(int type) {
return player != null && player.getTrackCount(type) > 0;
}
public void showVideoPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
configurePopupWithTracks(popup, null, DemoPlayer.TYPE_VIDEO);
popup.show();
}
public void showAudioPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
Menu menu = popup.getMenu();
menu.add(Menu.NONE, Menu.NONE, Menu.NONE, R.string.enable_background_audio);
final MenuItem backgroundAudioItem = menu.findItem(0);
backgroundAudioItem.setCheckable(true);
backgroundAudioItem.setChecked(enableBackgroundAudio);
OnMenuItemClickListener clickListener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item == backgroundAudioItem) {
enableBackgroundAudio = !item.isChecked();
return true;
}
return false;
}
};
configurePopupWithTracks(popup, clickListener, DemoPlayer.TYPE_AUDIO);
popup.show();
}
public void showTextPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
configurePopupWithTracks(popup, null, DemoPlayer.TYPE_TEXT);
popup.show();
}
public void showVerboseLogPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
Menu menu = popup.getMenu();
menu.add(Menu.NONE, 0, Menu.NONE, R.string.logging_normal);
menu.add(Menu.NONE, 1, Menu.NONE, R.string.logging_verbose);
menu.setGroupCheckable(Menu.NONE, true, true);
menu.findItem((VerboseLogUtil.areAllTagsEnabled()) ? 1 : 0).setChecked(true);
popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == 0) {
VerboseLogUtil.setEnableAllTags(false);
} else {
VerboseLogUtil.setEnableAllTags(true);
}
return true;
}
});
popup.show();
}
private void configurePopupWithTracks(PopupMenu popup,
final OnMenuItemClickListener customActionClickListener,
final int trackType) {
if (player == null) {
return;
}
int trackCount = player.getTrackCount(trackType);
if (trackCount == 0) {
return;
}
popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return (customActionClickListener != null
&& customActionClickListener.onMenuItemClick(item))
|| onTrackItemClick(item, trackType);
}
});
Menu menu = popup.getMenu();
// ID_OFFSET ensures we avoid clashing with Menu.NONE (which equals 0).
menu.add(MENU_GROUP_TRACKS, DemoPlayer.TRACK_DISABLED + ID_OFFSET, Menu.NONE, R.string.off);
for (int i = 0; i < trackCount; i++) {
menu.add(MENU_GROUP_TRACKS, i + ID_OFFSET, Menu.NONE,
buildTrackName(player.getTrackFormat(trackType, i)));
}
menu.setGroupCheckable(MENU_GROUP_TRACKS, true, true);
menu.findItem(player.getSelectedTrack(trackType) + ID_OFFSET).setChecked(true);
}
private static String buildTrackName(MediaFormat format) {
if (format.adaptive) {
return "auto";
}
String trackName;
if (MimeTypes.isVideo(format.mimeType)) {
trackName = joinWithSeparator(joinWithSeparator(buildResolutionString(format),
buildBitrateString(format)), buildTrackIdString(format));
} else if (MimeTypes.isAudio(format.mimeType)) {
trackName = joinWithSeparator(joinWithSeparator(joinWithSeparator(buildLanguageString(format),
buildAudioPropertyString(format)), buildBitrateString(format)),
buildTrackIdString(format));
} else {
trackName = joinWithSeparator(joinWithSeparator(buildLanguageString(format),
buildBitrateString(format)), buildTrackIdString(format));
}
return trackName.length() == 0 ? "unknown" : trackName;
}
private static String buildResolutionString(MediaFormat format) {
return format.width == MediaFormat.NO_VALUE || format.height == MediaFormat.NO_VALUE
? "" : format.width + "x" + format.height;
}
private static String buildAudioPropertyString(MediaFormat format) {
return format.channelCount == MediaFormat.NO_VALUE || format.sampleRate == MediaFormat.NO_VALUE
? "" : format.channelCount + "ch, " + format.sampleRate + "Hz";
}
private static String buildLanguageString(MediaFormat format) {
return TextUtils.isEmpty(format.language) || "und".equals(format.language) ? ""
: format.language;
}
private static String buildBitrateString(MediaFormat format) {
String s=format.bitrate == MediaFormat.NO_VALUE ? ""
: String.format(Locale.US, "%.2fMbit", format.bitrate / 1000000f);
// Toast.makeText(con, s, Toast.LENGTH_LONG).show();
return s;
}
private static String joinWithSeparator(String first, String second) {
return first.length() == 0 ? second : (second.length() == 0 ? first : first + ", " + second);
}
private static String buildTrackIdString(MediaFormat format) {
return format.trackId == null ? "" : " (" + format.trackId + ")";
}
private boolean onTrackItemClick(MenuItem item, int type) {
if (player == null || item.getGroupId() != MENU_GROUP_TRACKS) {
return false;
}
player.setSelectedTrack(type, item.getItemId() - ID_OFFSET);
return true;
}
private void toggleControlsVisibility() { /*/////////////////////////////////// Showing defalut controllers */
if (mediaController.isShowing()) {
mediaController.hide();
debugRootView.setVisibility(View.GONE);
} else {
showControls();
}
}
private void showControls() {
mediaController.show(0);
debugRootView.setVisibility(View.VISIBLE);
}
// DemoPlayer.CaptionListener implementation
#Override
public void onCues(List<Cue> cues) {
subtitleLayout.setCues(cues);
}
// DemoPlayer.MetadataListener implementation
#Override
public void onId3Metadata(Map<String, Object> metadata) {
for (Map.Entry<String, Object> entry : metadata.entrySet()) {
if (TxxxMetadata.TYPE.equals(entry.getKey())) {
TxxxMetadata txxxMetadata = (TxxxMetadata) entry.getValue();
Log.i(TAG, String.format("ID3 TimedMetadata %s: description=%s, value=%s",
TxxxMetadata.TYPE, txxxMetadata.description, txxxMetadata.value));
} else if (PrivMetadata.TYPE.equals(entry.getKey())) {
PrivMetadata privMetadata = (PrivMetadata) entry.getValue();
Log.i(TAG, String.format("ID3 TimedMetadata %s: owner=%s",
PrivMetadata.TYPE, privMetadata.owner));
} else if (GeobMetadata.TYPE.equals(entry.getKey())) {
GeobMetadata geobMetadata = (GeobMetadata) entry.getValue();
Log.i(TAG, String.format("ID3 TimedMetadata %s: mimeType=%s, filename=%s, description=%s",
GeobMetadata.TYPE, geobMetadata.mimeType, geobMetadata.filename,
geobMetadata.description));
} else {
Log.i(TAG, String.format("ID3 TimedMetadata %s", entry.getKey()));
}
}
}
// SurfaceHolder.Callback implementation
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (player != null) {
player.setSurface(holder.getSurface());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Do nothing.
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (player != null) {
player.blockingClearSurface();
}
}
private void configureSubtitleView() {
CaptionStyleCompat style;
float fontScale;
if (Util.SDK_INT >= 19) {
style = getUserCaptionStyleV19();
fontScale = getUserCaptionFontScaleV19();
} else {
style = CaptionStyleCompat.DEFAULT;
fontScale = 1.0f;
}
subtitleLayout.setStyle(style);
subtitleLayout.setFractionalTextSize(SubtitleLayout.DEFAULT_TEXT_SIZE_FRACTION * fontScale);
}
#TargetApi(19)
private float getUserCaptionFontScaleV19() {
CaptioningManager captioningManager =
(CaptioningManager) getSystemService(Context.CAPTIONING_SERVICE);
return captioningManager.getFontScale();
}
#TargetApi(19)
private CaptionStyleCompat getUserCaptionStyleV19() {
CaptioningManager captioningManager =
(CaptioningManager) getSystemService(Context.CAPTIONING_SERVICE);
return CaptionStyleCompat.createFromCaptionStyle(captioningManager.getUserStyle());
}
/**
* Makes a best guess to infer the type from a media {#link Uri} and an optional overriding file
* extension.
*
* #param uri The {#link Uri} of the media.
* #param fileExtension An overriding file extension.
* #return The inferred type.
*/
private static int inferContentType(Uri uri, String fileExtension) {
String lastPathSegment = !TextUtils.isEmpty(fileExtension) ? "." + fileExtension
: uri.getLastPathSegment();
return Util.inferContentType(lastPathSegment);
}
private static final class KeyCompatibleMediaController extends MediaController {
private MediaController.MediaPlayerControl playerControl;
public KeyCompatibleMediaController(Context context) {
super(context);
}
#Override
public void setMediaPlayer(MediaController.MediaPlayerControl playerControl) {
super.setMediaPlayer(playerControl);
this.playerControl = playerControl;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (playerControl.canSeekForward() && keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
playerControl.seekTo(playerControl.getCurrentPosition() + 15000); // milliseconds
BandwidthMeter bm=player.getBandwidthMeter();
Long l=bm.getBitrateEstimate();
storeBitRate=l;
bitrateTextView.setText(storeBitRate+" bits/sec");
show();
}
return true;
} else if (playerControl.canSeekBackward() && keyCode == KeyEvent.KEYCODE_MEDIA_REWIND) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
playerControl.seekTo(playerControl.getCurrentPosition() - 15000); // milliseconds
show();
}
return true;
}
return super.dispatchKeyEvent(event);
}
}
private class LoadImages extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog.setVisibility(View.VISIBLE);
}
protected Void doInBackground(String... args) {
try {
vodImgThumb = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
chImgLogo = BitmapFactory.decodeStream((InputStream)new URL(args[1]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
vodThumb.setImageBitmap(vodImgThumb);
chLogo.setImageBitmap(chImgLogo);
}
}
}
`
In demo of ExoPlayer this issue handle with retry button see how implemented here.
First of all set an ErrorListener to determined some error happened then just call following piece of code fix the issue:
if (playerNeedsPrepare) {
player.prepare();
playerNeedsPrepare = false;
updateButtonVisibilities();
}
player.setSurface(surfaceView.getHolder().getSurface());
player.setPlayWhenReady(playWhenReady);
ExoPlayer version 2.9 provides error handling customization via LoadErrorHandlingPolicy.
public final class CustomPolicy
extends DefaultLoadErrorHandlingPolicy {
#Override
public long getRetryDelayMsFor(
int dataType,
long loadDurationMs,
IOException exception,
int errorCount) {
// Replace NoConnectivityException with the corresponding
// exception for the used DataSource.
if (exception instanceof NoConnectivityException) {
return 5000; // Retry every 5 seconds.
} else {
return C.TIME_UNSET; // Anything else is surfaced.
}
}
#Override
public int getMinimumLoadableRetryCount(int dataType) {
return Integer.MAX_VALUE;
}
}
More https://medium.com/google-exoplayer/load-error-handling-in-exoplayer-488ab6908137
playbackPreparer will be called when playButton clicked while player.getPlaybackState() == Player.STATE_IDLE
PlayerControlView.java#L1111
playerView.setPlaybackPreparer {
simpleExoPlayer.prepare(
ExtractorMediaSource.Factory(source).createMediaSource(video),
false,
true
)
}
Create resume fun and do something like this:
player = [your exoPlayer]
fun resumeTrack() {
if (player.playbackError != null) {
player.retry();
}
setPlayWhenReady(true);
exoPlayer.playWhenReady = true
}
You can also do something like :
protected void play() {
if (null != getPlaybackError()) {
retry();
}
setPlayWhenReady(true);
}
Before you call player.play() in your onClick() method, just check if the player has a sourceException in playerError and call player.prepare() before calling play() like this in Kotlin:
player.playerError.takeIf { it?.sourceException is IOException }?.run {
player.prepare()
}

Barcode scanning issue

I am working on barcode scanning on button click to increment the quantity counted field by one of a table when the scanning result matches with the item number field of the table. If the scan result matches item number it should update the quantity counted of that row. I am unable to get the scan result itself. Getting NullPointerException.
This is my code.
These are two Java files from zxing.
IntentIntegrator.java
package com.example.mis;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16
// bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE = "This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A",
"UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES = list("UPC_A",
"UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections
.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections
.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections
.singletonList(BS_PACKAGE);
public static final List<String> TARGET_ALL_KNOWN = list(BSPLUS_PACKAGE, // Barcode
// Scanner+
BSPLUS_PACKAGE + ".simple", // Barcode Scanner+ Simple
BS_PACKAGE // Barcode Scanner
// What else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String, Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
moreExtras = new HashMap<String, Object>(3);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public final void setTargetApplications(List<String> targetApplications) {
if (targetApplications.isEmpty()) {
throw new IllegalArgumentException("No target applications");
}
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singletonList(targetApplication);
}
public Map<String, ?> getMoreExtras() {
return moreExtras;
}
public final void addExtra(String key, Object value) {
moreExtras.put(key, value);
}
/**
* Initiates a scan for all known barcode types.
*/
public final AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
/**
* Initiates a scan only for a certain set of barcode types, given as
* strings corresponding to their names in ZXing's {#code BarcodeFormat}
* class like "UPC_A". You can supply constants like
* {#link #PRODUCT_CODE_TYPES} for example.
*
* #return the {#link AlertDialog} that was shown to the user prompting them
* to download the app if a prompt was needed, or null otherwise
*/
public final AlertDialog initiateScan(
Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
/**
* Start an activity. This method is defined to allow different methods of
* activity starting for newer versions of Android and for compatibility
* library.
*
* #param intent
* Intent to start.
* #param code
* Request code for the activity
* #see android.app.Activity#startActivityForResult(Intent, int)
* #see android.app.Fragment#startActivityForResult(Intent, int)
*/
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (String targetApp : targetApplications) {
if (contains(availableApps, targetApp)) {
return targetApp;
}
}
}
return null;
}
private static boolean contains(Iterable<ResolveInfo> availableApps,
String targetApp) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApp.equals(packageName)) {
return true;
}
}
return false;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String packageName = targetApplications.get(0);
Uri uri = Uri.parse("market://details?id="
+ packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG,
"Google Play is not installed; cannot install "
+ packageName);
}
}
});
downloadDialog.setNegativeButton(buttonNo,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
/**
* <p>
* Call this from your {#link Activity}'s
* {#link Activity#onActivityResult(int, int, Intent)} method.
* </p>
*
* #return null if the event handled here was not related to this class, or
* else an {#link IntentResult} containing the result of the scan.
* If the user cancelled scanning, the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode,
int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra(
"SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null
: intentOrientation;
String errorCorrectionLevel = intent
.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents, formatName, rawBytes,
orientation, errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Defaults to type "TEXT_TYPE".
*
* #see #shareText(CharSequence, CharSequence)
*/
public final AlertDialog shareText(CharSequence text) {
return shareText(text, "TEXT_TYPE");
}
/**
* Shares the given text by encoding it as a barcode, such that another user
* can scan the text off the screen of the device.
*
* #param text
* the text string to encode as a barcode
* #param type
* type of data to encode. See
* {#code com.google.zxing.client.android.Contents.Type}
* constants.
* #return the {#link AlertDialog} that was shown to the user prompting them
* to download the app if a prompt was needed, or null otherwise
*/
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
activity.startActivity(intent);
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String, Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Kind of hacky
if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else if (value instanceof Long) {
intent.putExtra(key, (Long) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Float) {
intent.putExtra(key, (Float) value);
} else if (value instanceof Bundle) {
intent.putExtra(key, (Bundle) value);
} else {
intent.putExtra(key, value.toString());
}
}
}
}
IntentResult.java
package com.example.mis;
public class IntentResult {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResult() {
this(null, null, null, null, null);
}
IntentResult(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
/**
* #return raw content of barcode
*/
public String getContents() {
return contents;
}
/**
* #return name of format, like "QR_CODE", "UPC_A". See {#code BarcodeFormat} for more format names.
*/
public String getFormatName() {
return formatName;
}
/**
* #return raw bytes of the barcode content, if applicable, or null otherwise
*/
public byte[] getRawBytes() {
return rawBytes;
}
/**
* #return rotation of the image, in degrees, which resulted in a successful scan. May be null.
*/
public Integer getOrientation() {
return orientation;
}
/**
* #return name of the error correction level used in the barcode, if applicable
*/
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
#Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
This is the activity in which i am implementing barcode scanning
public class InventoryCount extends Activity {
private Button mbtn_scan;
mbtn_scan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
IntentIntegrator integrator = new IntentIntegrator(
InventoryCount.this);
integrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
// check we have a valid result
try {
if (resultCode == RESULT_OK) {
Log.i("Scanning Result ", "" + scanningResult);
Toast.makeText(
InventoryCount.this,
"Scanning success the content is : "
+ scanningResult.getContents(),
Toast.LENGTH_SHORT).show();
String sr = scanningResult.getContents();
getBarCodeData(sr);
} else if (resultCode == RESULT_CANCELED) {
Toast toast = Toast.makeText(InventoryCount.this,
"Scanning Cancelled!", Toast.LENGTH_SHORT);
toast.show();
}
} catch (Exception e) {
System.out.println("Error on scanning: "+e);
}
}
public void getBarCodeData(String itmNumber) {
Cursor c;
try {
String qtyCountQry = "SELECT " + DatabaseHandler.KEY_QTYCOUNTED
+ " FROM " + DatabaseHandler.TABLE_MIC2 + " WHERE "
+ DatabaseHandler.KEY_ITEMNUMBER + "='" + itmNumber + "'";
SQLiteDatabase sq = db.getReadableDatabase();
c = sq.rawQuery(qtyCountQry, null);
c.moveToFirst();
String q2 = c.getString(c
.getColumnIndex(DatabaseHandler.KEY_QTYCOUNTED));
Toast.makeText(InventoryCount.this, "Quantity Count is " + q2,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(InventoryCount.this, "Exception " + e,
Toast.LENGTH_SHORT).show();
}
}
I have just tried to display scan result and if it matches itemnumber it will display the corresponding quantity in that row as shown in code above. But as of now not even scan result is displaying. Help me.. Also say how to increment the quantity by one and update it in db.
Try to use the zxing library by extending the CaptureActivity Class.
public class ScannerData extends CaptureActivity {
Handler handler = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_scanner);
}
#Override
public void handleDecode(final Result rawResult, Bitmap barcode,
float scaleFactor) {
// TODO Auto-generated method stub
handler = getHandler();
handler.sendEmptyMessageDelayed(R.id.restart_preview,
CaptureActivity.BULK_MODE_SCAN_DELAY_MS);
String mQrcode = rawResult.getText().toString();
}
}
Use the code like this.
You can get the qr-code here
String mQrcode = rawResult.getText().toString();
In Xml you need to include capture.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/frameLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:layout_marginRight="25dp">
<FrameLayout
android:layout_width="510dp"
android:layout_height="310dp"
android:background="#drawable/scanner_box"
android:layout_gravity="center" >
<include
android:layout_width="750dp"
android:layout_height="450dp"
android:layout_gravity="center"
android:layout_marginBottom="50dp"
android:layout_marginRight="110dp"
layout="#layout/capture" />
</FrameLayout>
</RelativeLayout>
</RelativeLayout>

asmak packet listener and custom IQProvider not triggering / called

I'm using asmack the latest version (asmack-android-8-source-0.8.3) in a android project and I'm trying to communicate with the server by sending multiple IQs and receiving responses.
I receive the response and it's parsed correctly but the package listener it's not triggering.
I have the following code:
vCard_IQProvider.java
public class vCard_IQProvider implements IQProvider
{
public static final String NAMESPACE = "vcard-temp";
public static final String ELEMENT_NAME = "vCard";
public static final String LAST_STATUS = "LAST_STATUS";
public static final String LAST_STATUS_DESCRIPTION = "LAST_STATUS_DESCRIPTION";
public static final String WORK_TIME_RANGE = "WORK_TIME_RANGE";
public static final String SOUND_SETTINGS = "SOUND_SETTINGS";
public static final String AUTO_LOCATION_MACHINE_DATA = "AUTO_LOCATION_MACHINE_DATA";
public static final String AUTO_LOCATION = "AUTO_LOCATION";
public static final String AUTO_LOCATION_ENABLED = "AUTO_LOCATION_ENABLED";
public static final String AUTO_ONLINE = "AUTO_ONLINE";
public static final String HIDEACTIONNOTIFICATIONS = "HideActionNotifications";
public static final String AUTO_CONNECT = "AUTO_CONNECT";
public static final String AUTO_OFFLINE_WORK_TIME = "AUTO_OFFLINE_WORK_TIME";
public static final String AUTO_RELOGIN = "AUTO_RELOGIN";
public static final String CONNECTED_VIA_INTERNET = "CONNECTED_VIA_INTERNET";
public static final String MINIMIZE_CHAT = "MINIMIZE_CHAT";
public static final String PROMPT_PROJECT_SWITCH = "PROMPT_PROJECT_SWITCH";
public static final String MACHINE_NAME = "MACHINE_NAME";
public static final String MROFFICE_VER = "MROFFICE_VER";
public static final String WORK = "WORK";
public static final String LOCALITY = "LOCALITY";
public static final String TIMESTAMP = "timestamp";
public static final String REGION = "REGION";
public static final String EXT = "EXT";
public static final String LAST_ACTIVITY_TS = "LAST_ACTIVITY_TS";
public static final String FUTURE_STATUS = "FUTURE_STATUS";
public static final String FUTURE_STATUS_DESCRIPTION = "FUTURE_STATUS_DESCRIPTION";
public static final String FUTURE_STATUS_TS = "FUTURE_STATUS_TS";
public static final String CUSTOM = "CUSTOM";
public static final String PREF = "PREF";
private Map<String, String> list = new HashMap<String, String>();
#Override
public IQ parseIQ(XmlPullParser parser) throws Exception
{
String name;
boolean isEmpty;
boolean done = false;
while(parser.next() != XmlPullParser.END_DOCUMENT && false == done)
{
name = parser.getName();
switch (parser.getEventType())
{
case XmlPullParser.START_TAG:
{
isEmpty = parser.isEmptyElementTag();
if(name.equalsIgnoreCase(LAST_STATUS) && false == isEmpty)
{
list.put(LAST_STATUS, parser.nextText());
}
else if(name.equalsIgnoreCase(LAST_STATUS_DESCRIPTION) && false == isEmpty)
{
list.put(LAST_STATUS_DESCRIPTION , parser.nextText());
}
else if(name.equalsIgnoreCase(WORK_TIME_RANGE) && false == isEmpty)
{
list.put(WORK_TIME_RANGE, parser.nextText());
}
else if(name.equalsIgnoreCase(SOUND_SETTINGS) && false == isEmpty)
{
list.put(SOUND_SETTINGS, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_LOCATION_MACHINE_DATA) && false == isEmpty)
{
list.put(AUTO_LOCATION_MACHINE_DATA, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_LOCATION) && false == isEmpty)
{
list.put(AUTO_LOCATION, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_LOCATION_ENABLED) && false == isEmpty)
{
list.put(AUTO_LOCATION_ENABLED, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_ONLINE) && false == isEmpty)
{
list.put(AUTO_ONLINE, parser.nextText());
}
else if(name.equalsIgnoreCase(HIDEACTIONNOTIFICATIONS) && false == isEmpty)
{
list.put(HIDEACTIONNOTIFICATIONS, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_CONNECT) && false == isEmpty)
{
list.put(AUTO_CONNECT, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_OFFLINE_WORK_TIME) && false == isEmpty)
{
list.put(AUTO_OFFLINE_WORK_TIME, parser.nextText());
}
else if(name.equalsIgnoreCase(AUTO_RELOGIN) && false == isEmpty)
{
list.put(AUTO_RELOGIN, parser.nextText());
}
else if(name.equalsIgnoreCase(CONNECTED_VIA_INTERNET) && false == isEmpty)
{
list.put(CONNECTED_VIA_INTERNET, parser.nextText());
}
else if(name.equalsIgnoreCase(MINIMIZE_CHAT) && false == isEmpty)
{
list.put(MINIMIZE_CHAT, parser.nextText());
}
else if(name.equalsIgnoreCase(PROMPT_PROJECT_SWITCH) && false == isEmpty)
{
list.put(PROMPT_PROJECT_SWITCH, parser.nextText());
}
else if(name.equalsIgnoreCase(MACHINE_NAME) && false == isEmpty)
{
list.put(MACHINE_NAME, parser.nextText());
}
else if(name.equalsIgnoreCase(MROFFICE_VER) && false == isEmpty)
{
list.put(MROFFICE_VER, parser.nextText());
}
else if(name.equalsIgnoreCase(WORK) && false == isEmpty)
{
list.put(WORK, parser.nextText());
}
else if(name.equalsIgnoreCase(LOCALITY) && false == isEmpty)
{
list.put(LOCALITY, parser.nextText());
}
else if(name.equalsIgnoreCase(TIMESTAMP) && false == isEmpty)
{
list.put(TIMESTAMP, parser.nextText());
}
else if(name.equalsIgnoreCase(REGION) && false == isEmpty)
{
list.put(REGION, parser.nextText());
}
else if(name.equalsIgnoreCase(EXT) && false == isEmpty)
{
list.put(EXT, parser.nextText());
}
else if(name.equalsIgnoreCase(LAST_ACTIVITY_TS) && false == isEmpty)
{
list.put(LAST_ACTIVITY_TS, parser.nextText());
}
else if(name.equalsIgnoreCase(FUTURE_STATUS) && false == isEmpty)
{
list.put(FUTURE_STATUS, parser.nextText());
}
else if(name.equalsIgnoreCase(FUTURE_STATUS_DESCRIPTION) && false == isEmpty)
{
list.put(FUTURE_STATUS_DESCRIPTION, parser.nextText());
}
else if(name.equalsIgnoreCase(FUTURE_STATUS_TS) && false == isEmpty)
{
list.put(FUTURE_STATUS_TS, parser.nextText());
}
else if(name.equalsIgnoreCase(CUSTOM) && false == isEmpty)
{
list.put(CUSTOM, parser.nextText());
}
else if(name.equalsIgnoreCase(PREF) && false == isEmpty)
{
list.put(PREF, parser.nextText());
}
break;
}
case XmlPullParser.END_TAG:
{
done = ELEMENT_NAME.equalsIgnoreCase(name);
break;
}
}
}
name = null;
return new vCard_IQ(list);
}
}
vCard_IQ.java
public class vCard_IQ extends IQ
{
public static final String ID = "vcard";
private static Map<String, String> list;
private static boolean finishedParsing = false;
public vCard_IQ(Map<String, String> l)
{
if(null == list)
{
list = new HashMap<String, String>();
}
list.clear();
list.putAll(l);
finishedParsing = true;
}
#Override
public String getChildElementXML()
{
return null;
}
public static final Map<String, String> getData()
{
return list;
}
public static void setFinishedParsingToFalse()
{
finishedParsing = false;
}
public static final boolean finishedParsing()
{
return finishedParsing;
}
}
I add the provider:
ProviderManager.getInstance().addIQProvider(vCard_IQProvider.ELEMENT_NAME, vCard_IQProvider.NAMESPACE, new vCard_IQProvider());
and the package listener:
connection.addPacketListener(new PacketListener()
{
#Override
public void processPacket(Packet p)
{
if(p.getPacketID().equals(vCard_IQ.ID))
{
vCard_IQ pp = (vCard_IQ)p;
//access the parsed data
//vCard_IQ.getData().get.......
pp = null;
}
}
},
new PacketFilter()
{
#Override
public boolean accept(Packet arg0)
{
return true;
}
});
The packet filter is set to accept all packets, the listner is not triggering for some reason. I can see in the debugger that the server is sending the responses.
I even tried to bypass the listener by creating an asynk task an waiting in the background thread until the response is parsed and than I access it. Now it works only for the first iq sent - I receive a response and it's parsed correctly, but for the rest I can see in the debugger that the server it's sending responses but it never reaches the parser. The parser it's never called.
Asynk<Void, Void, Void> asynk = new Asynk<Void, Void, Void>()
{
Packet iq_vcard;
#Override
protected Void doInBackground(Void... params)
{
for(String s : names_list)
{
final String name = s;
iq_vcard = new Packet()
{
#Override
public String toXML()
{
String str = String.format("<iq from='%s' to='%s' type='get' id='" + vCard_IQ.ID + "'><vCard xmlns='vcard-temp'/></iq>",
sharedPrefs.getString(LogIn.USERNAME, "") + "#" + sharedPrefs.getString(Settings_LogIn.DOMAIN, Settings_LogIn.ERROR) + "/iOffice",
name + "#" + sharedPrefs.getString(Settings_LogIn.DOMAIN, Settings_LogIn.ERROR));
Log.e("iq_vcard", str);
return str;
}
};
connection().sendPacket(iq_vcard);
iq_vcard = null;
while(false == vCard_IQ.finishedParsing())
{
try
{
Thread.sleep(1000);
Log.e("TAG", "waiting to finish parsing...");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
//access the parsed data
//vCard_IQ.getData().get.......
vCard_IQ.setFinishedParsingToFalse();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
}
};
asynk.execute();
Any suggestions on what's wrong?
This is a bug in aSmack and after numerous attempts at fixing this issue, failed attempts of compiling aSmack myself following this tutorial and trying anything that I could think of, I did the following: I created a new package in my android project and dumped all of the aSmack's java classes there. This way I let eclipse compile aSmack and I got a better control over it's code.
The problem was that every time I would receive an custom iq response from server, in PacketParserUtils.java aSmack would return a wrong elementName and namespace, thus choosing a wrong iq provider to parse the response.
From documentation:
http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smack/provider/IQProvider.html
At the end of the method call, the parser must be positioned on
the closing tag of the child element.
Just if somebody is trying to do the same, I found what was the problem.
The while condition on the vCard_IQProvider class is wrong, it should be:
while(!done && parser.next() != XmlPullParser.END_DOCUMENT)
Otherwise when done is set to true, the while will check again the condition and move the parser to the next element (with the call parser.next()).

Categories

Resources