Error notifyDataSetChanged() in RecyclerView when its scroll to last position - java

I am using RecyclerView to display the list of rows, each row has a buy button. when the user buys an element, the method notifydatasetchanged() is called and the buy button has to change the background color for example to red.
Important, The user have to buys only one element, and I have a thread that runs every 5 seconds looking for new answers, if there is a new answer, it is added to the list and scroll to last position.
My problem is when I have the list of buttons and only one is red and I have a new answer, I add it to the list but the button of some rows change to red.
this is my code:
private void responses() {
fin_thread = true;
thread = new Thread() {
#Override
public void run() {
while (fin_thread) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
JsonObjectRequest service_call = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
try {
boolean status = response.getBoolean("value_status_response");
if (status) {
if (response.getInt("counter") > 0 && obj_response.size() > 0) {
JSONArray answer = response.getJSONArray("answer");
if (answer.length() != obj_response.size()) {
for (int i = 0; i < answer.length(); i++) {
boolean coincidence = false;;
JSONObject item = answer.getJSONObject(i);
for (int j = 0; j < obj_response.size(); j++) {
if (item.getId("id") == obj_response.get(j).getId()) {
coincidence = true;
break;
}
}
if (!coincidence) {
CResponse cr = new CResponse();
cr.setName(item.getString("name"));
cr.setPrice(item.getString("price"));
cr.setId(item.getInt("id"));
cr.setState(item.getInt("state"));
obj_response.add(cr);
sectionAdapter.notifyDataSetChanged();
scroll_to_last();
}
}
}
} else {
if (response.getInt("counter") > 0 && obj_response.size() == 0) {
JSONArray answer = response.getJSONArray("answer");
for (int i = 0; i < answer.length(); i++) {
JSONObject item = answer.getJSONObject(i);
CResponse cr = new CResponse();
cr.setName(item.getString("name"));
cr.setPrice(item.getString("price"));
cr.setId(item.getInt("id"));
cr.setState(item.getInt("state"));
obj_response.add(cr);
sectionAdapter.notifyDataSetChanged();
rv.setVisibility(View.VISIBLE);
progress_bar.setVisibility(View.GONE);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
//ERROR
}
}
}
) {
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map < String, String > params = new HashMap < String, String > ();
params.put("Authorization", "Basic " + auth);
return params;
}
};
Helpers.queue(Class.this).add(service_call);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
}
private void scroll_to_last() {
lm.scrollToPosition(sectionAdapter.getItemCount() - 1);
}
My Adapter
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, final int position) {
final MyViewPedidoDesc itemHolder = (MyViewPedidoDesc) holder;
control_btn_background(itemHolder, position);
}
private void control_btn_background(MyViewPedidoDesc itemHolder, int position) {
if (mData.get(position).getState() == 1) {
itemHolder.buy_btn.setBackgroundResource(R.drawable.red);
} else {
itemHolder.buy_btn.setBackgroundResource(R.drawable.blue);
}
}
I think the error appears is when I call scroll_to_last() method because if I don't call that the background color is only in one button.
Thanks in advace

Related

Infinite Scroll is loading the same last value always

I managed to retrieve the data from firebase, implementing an infinite scroll... is working right but when i scroll till end, is loading the same last values always..
Tried to change the .limitToLast to .startAt but there is no difference.
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
/** To do code here*/
oldestPostId = oldDummy;
Query query = SearchRef.orderByKey();
if (oldestPostId != null) {
query = query.limitToLast(limitToLast).endAt(oldestPostId);
}
dataList.clear();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Query ordenar = mDatabase.child("Off-Topic").orderByChild("countthreads");
for (DataSnapshot child : dataSnapshot.getChildren()) {
MessageThread messageThread = child.getValue(MessageThread.class);
if (messageThread != null) {
oldestPostId = child.getKey();
oldestPostidScrollList.add(child.getKey());
if (oldestPostidScrollList.size() > m) {
String myIdss = oldestPostidScrollList.get(m);
oldDummy = myIdss;
}
messageThread.thread_id = child.getKey();
}
dataList.add(messageThread);
if (dataList.size() == 5) {
Collections.reverse(dataList);
for (int j = 0; j < dataList.size(); j++) {
threadsList.add(dataList.get(j));
}
threadsAdapter = new ThreadsAdapter(ThreadsActivity.this, R.layout.threads_listview,
threadsList, tryList, ThreadsActivity.this, ordenar);
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
}
}, 1000);
threadsListView.setSelection(scrollTO);
} else {
if (lastValueCalled) {
lastValueCalled = true;
for (int j = 0; j < dataList.size(); j++) {
threadsList.add(dataList.get(j));
}
scrollMyListViewToBottom();
}
}
}
scrollTO = scrollTO + 10;
int x = tryList.size();
int temp = x - m;
int count = temp - 10;
if (count > 10 && temp > 10) {
m = m + 10;
} else if (nCalled) {
Log.e("called", "data is over");
} else {
lastValueCalled = true;
if (lastValueCalled) {
nCalled = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Also checked the log and is giving the result "data is over" but continues doing the same thing always. Any clue?

How to update TextView dynamically

I'm trying to create a small service that connects to a site does the operations and during the process updates the textview present. Nothing wrong until I enter a for loop, because the activity stops, it becomes completely white until when it does not end.
I would like to update the text step by step.
I created an async task, but it gives me the error '
failed to load window.
Below is my code, I state that I put all the permissions.
public class GameTask extends AsyncTask<String, Integer, Long> {
private ProgressBar progressBar;
private TextView text;
public GameTask(ProgressBar progressBar, TextView text) {
this.progressBar = progressBar;
this.text = text;
}
#Override
protected Long doInBackground(String... strings) {
startGameThread(progressBar, text);
return null;
}
private void startGameThread (final ProgressBar progressBar, final TextView text) {
final Handler mHandler = new Handler();
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
try {
progressBar.setProgress(0);
text.setText("Thread Iniziato...");
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
text.setText("NUMBER " + i);
}
}
progressBar.setProgress(100);
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(mRunnable).start();
}
}
Try this method into AsyncTask
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
try {
progressBar.setProgress(0);
text.setText("Thread Iniziato...");
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
text.setText("NUMBER " + i);
}
}
progressBar.setProgress(100);
} catch (IOException e) {
e.printStackTrace();
}
}
You can take full advantage of AsyncTask to perform tasks in background and UI thread without a Handler:
public class GameTask extends AsyncTask<String, Integer, Long> {
private ProgressBar progressBar;
private TextView text;
public GameTask(ProgressBar progressBar, TextView text) {
this.progressBar = progressBar;
this.text = text;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// UI thread
text.setText("Thread Iniziato...");
}
#Override
protected Long doInBackground(String... strings) {
// Non-UI thread
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
publishProgress(i/100, i);
} else {
publishProgress(i/100);
}
try {
Thread.sleep(100); // Backpressure if needed for your sample
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// UI thread
progressBar.setProgress(values[0]);
if (values.length > 1) {
text.setText("NUMBER " + values[1]);
}
}
}
As this Process is Running Inside AsyncTask, You need to Use runOnUiThread method to update the TextView. UI can only be Upated on MainThread.
private void startGameThread () {
// final Handler mHandler = new Handler();
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
final int finalI = i;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(String.valueOf(finalI));
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(mRunnable).start();
}

duplicate actions in android application when going to home screen

Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases:
In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.
I'm simply recreating the main activity on home button press with recreate();
I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.
If I need to show code tell me which part?
Edit:
inside onCreateView of fragment Cart Detail
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.
Edit 2: MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.utils = new Utils(this);
utils.changeLanguage("en");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
this.context = this;
setupToolbar(this);
utils.switchFragment(new MainFrag());
setOnClickListener();
initRightMenuData();
initLeftMenuData();
listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
false, loggedInIconList);
listViewExpLeft.setAdapter(listAdapter);
if (isLoggedIn()) {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
loggedInIconList);
} else {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
NotLoggedInIconList);
}
listViewExpRight.setAdapter(listAdapterRight);
enableSingleSelection();
setExpandableListViewClickListener();
setExpandableListViewChildClickListener();
}
private void setOnClickListener() {
myAccountTV.setOnClickListener(this);
checkoutTV.setOnClickListener(this);
discountTV.setOnClickListener(this);
homeTV.setOnClickListener(this);
searchIcon.setOnClickListener(this);
cartLayout.setOnClickListener(this);
}
private void setExpandableListViewClickListener() {
listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
utils.printLog("GroupClicked", " Id = " + id);
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (!isLoggedIn()) {
if (childCount < 1) {
if (groupPosition == 0) {
utils.switchFragment(new FragLogin());
} else if (groupPosition == 1) {
utils.switchFragment(new FragRegister());
} else if (groupPosition == 2) {
utils.switchFragment(new FragContactUs());
} else {
recreate();
}
drawer.closeDrawer(GravityCompat.END);
}
} else {
if (childCount < 1) {
changeFragment(103 + groupPosition);
drawer.closeDrawer(GravityCompat.END);
}
}
return false;
}
});
listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount < 1) {
MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
.getGroup(groupPosition);
moveToProductFragment(textChild.getMenuCategoryId());
utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
}
return false;
}
});
}
private void setExpandableListViewChildClickListener() {
listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
moveToProductFragment(subCategory.getMenuSubCategoryId());
utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
return true;
}
});
listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
if (str.contains("Information") || str.contains("معلومات")) {
Bundle bundle = new Bundle();
bundle.putString("id", userSubMenu.getUserSubMenuCode());
utils.switchFragment(new FragShowText(), bundle);
} else if (str.contains("اللغة") || str.contains("Language")) {
recreate();
} else if (str.contains("دقة") || str.contains("Currency")) {
makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
}
utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
drawer.closeDrawer(GravityCompat.END);
return false;
}
});
}
private void setupToolbar(Context context) {
ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
String imgPath = Preferences
.getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
utils.printLog("Product Image = " + imgPath);
if (!imgPath.isEmpty()) {
Picasso.with(getApplicationContext()).load(imgPath)
.into(logoIcon);
}
logoIcon.setOnClickListener(this);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
actionbarToggle();
drawer.addDrawerListener(mDrawerToggle);
drawerIconLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
drawerIconLeft.setScaleX(1);
drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
}
}
});
drawerIconRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
});
}
private void initViews() {
drawerIconLeft = findViewById(R.id.drawer_icon_left);
drawerIconRight = findViewById(R.id.drawer_icon_right);
logoIcon = findViewById(R.id.logo_icon);
searchIcon = findViewById(R.id.search_icon);
cartLayout = findViewById(R.id.cart_layout);
counterTV = findViewById(R.id.actionbar_notification_tv);
drawer = findViewById(R.id.drawer_layout);
listViewExpLeft = findViewById(R.id.expandable_lv_left);
listViewExpRight = findViewById(R.id.expandable_lv_right);
appbarBottom = findViewById(R.id.appbar_bottom);
appbarTop = findViewById(R.id.appbar_top);
myAccountTV = findViewById(R.id.my_account_tv);
discountTV = findViewById(R.id.disc_tv);
checkoutTV = findViewById(R.id.checkout_tv);
homeTV = findViewById(R.id.home_tv);
searchView = findViewById(R.id.search_view);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
private void initRightMenuData() {
headerListRight = new ArrayList<>();
hashMapRight = new HashMap<>();
String[] notLoggedInMenu = {findStringByName("login_text"),
findStringByName("action_register_text"),
findStringByName("contact_us_text")};
String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
findStringByName("action_change_pass_text"),
findStringByName("order_history_text"),
findStringByName("logout"), findStringByName("contact_us_text")};
List<UserSubMenu> userSubMenusList = new ArrayList<>();
if (isLoggedIn()) {
for (int i = 0; i < loggedInMenu.length; i++) {
headerListRight.add(loggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
} else {
for (int i = 0; i < notLoggedInMenu.length; i++) {
headerListRight.add(notLoggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
}
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInInitData", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray slideshow = homeObject.optJSONArray("slideshow");
AppConstants.setSlideshowExtra(slideshow.toString());
JSONArray menuRight = homeObject.optJSONArray("usermenu");
for (int z = 0; z < menuRight.length(); z++) {
List<UserSubMenu> userSubMenuList = new ArrayList<>();
JSONObject object = menuRight.getJSONObject(z);
headerListRight.add(object.optString("name"));
JSONArray childArray = object.optJSONArray("children");
for (int y = 0; y < childArray.length(); y++) {
JSONObject obj = childArray.optJSONObject(y);
userSubMenuList.add(new UserSubMenu(obj.optString("code"),
obj.optString("title"), obj.optString("symbol_left"),
obj.optString("symbol_right")));
}
hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
utils.printLog("AfterHashMap", "" + hashMapRight.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.showErrorDialog("Error Getting Data From Server");
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONObjEx_MainAct", responseStr);
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void initLeftMenuData() {
headerListLeft = new ArrayList<>();
hashMapLeft = new HashMap<>();
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInMainActivity", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
utils.printLog("Categories", menuCategories.toString());
for (int i = 0; i < menuCategories.length(); i++) {
JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
"children");
List<MenuSubCategory> childMenuList = new ArrayList<>();
for (int j = 0; j < menuSubCategoryArray.length(); j++) {
JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
MenuSubCategory menuSubCategory = new MenuSubCategory(
menuSubCategoryObj.optString("child_id"),
menuSubCategoryObj.optString("name"));
childMenuList.add(menuSubCategory);
}
MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
"category_id"), menuCategoryObj.optString("name"),
menuCategoryObj.optString("icon"), childMenuList);
headerListLeft.add(menuCategory);
hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void actionbarToggle() {
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
drawerIconLeft.setImageResource(R.drawable.ic_list_black);
drawerIconLeft.setScaleX(-1);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.logo_icon) {
recreate();
} else if (id == R.id.my_account_tv) {
utils.switchFragment(new Dashboard());
} else if (id == R.id.disc_tv) {
utils.printLog("From = Main Act");
Bundle bundle = new Bundle();
bundle.putString("from", "mainActivity");
utils.switchFragment(new FragProduct(), bundle);
} else if (id == R.id.checkout_tv) {
if (isLoggedIn()) {
utils.switchFragment(new FragCheckout());
} else {
AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
"Select the appropriate option");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"As Guest", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragCheckout());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragLogin());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
"Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragRegister());
}
});
alertDialog.show();
}
} else if (id == R.id.home_tv) {
recreate();
} else if (id == R.id.search_icon) {
startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
} else if (id == R.id.cart_layout) {
Bundle bundle = new Bundle();
bundle.putString("midFix", "cartProducts");
utils.switchFragment(new FragCartDetail(), bundle);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
|| requestCode == LANGUAGE_REQUEST_CODE) {
if (data != null) {
String responseStr = data.getStringExtra("result");
utils.printLog("ResponseIs = " + responseStr);
if (responseStr != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject response;
if (!isJSONString(responseStr)) {
try {
response = new JSONObject(responseStr);
if (requestCode == CURRENCY_REQUEST_CODE) {
JSONObject object = response.optJSONObject("currency");
Preferences.setSharedPreferenceString(appContext
, CURRENCY_SYMBOL_KEY
, object.optString("symbol_left")
+ object.optString("symbol_right")
);
recreate();
} else if (requestCode == LANGUAGE_REQUEST_CODE) {
JSONObject object = response.optJSONObject("language");
Preferences.setSharedPreferenceString(appContext
, LANGUAGE_KEY
, object.optString("code")
);
recreate();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (requestCode == SEARCH_REQUEST_CODE) {
if (responseStr.isEmpty())
return;
Bundle bundle = new Bundle();
bundle.putString("id", responseStr);
bundle.putString("from", "fromSearch");
utils.switchFragment(new FragProduct(), bundle);
} else {
utils.showAlertDialog("Alert", responseStr);
}
}
} else if (resultCode == FORCED_CANCEL) {
utils.printLog("WithinSearchResult", "If Success False" + responseStr);
} else if (resultCode == Activity.RESULT_CANCELED) {
utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
}
}
}
}
}
}
MainFragment
public class MainFrag extends MyBaseFragment {
public MainFrag() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_main, container, false);
initUtils();
initViews(view);
utils.setupSlider(mPager, indicator, pb, true, true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(getActivity()
, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> keysList = prepareData();
if (keysList.size() > 0 && !keysList.isEmpty()) {
mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
}
return view;
}
private void initViews(View view) {
mRecyclerView = view.findViewById(R.id.parent_recycler_view);
mPager = view.findViewById(R.id.pager);
indicator = view.findViewById(R.id.indicator);
pb = view.findViewById(R.id.loading);
}
private List<String> prepareData() {
String responseStr = getHomeExtra();
List<String> keysStr = new ArrayList<>();
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
JSONObject homeObject = responseObject.optJSONObject("home");
JSONObject modules = homeObject.optJSONObject("modules");
Iterator<?> keys = modules.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysStr.add(key);
utils.printLog("KeyStr", key);
}
utils.printLog("ModuleSize", modules.toString());
} else {
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONEx_MainFragTest", responseStr);
}
return keysStr;
}
}
I removed global variables and some method because of length.
You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.
From the hint of #Akash Khatri I use to switch to mainFragment and its fine now. Actually #Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.
I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.

Synchronizing of threading

I have a fragment class that describes RecyclerView. It takes array for creating elements. The array is forming by parsing JSON. When I use good internet connection everything is OK, and I can see desirable list of items. But using low-speed connection my UI is empty.
I realize that there are some problems with threads, but I haven't enough knowledge to fix my problem.
Here is a code:
public class ListVideo extends Fragment {
private int loadLimit = 9;
private RecyclerView recyclerView;
private RecyclerAdapter adapter;
private LinearLayoutManager linearLayoutManager;
final OkHttpClient client = new OkHttpClient();
List<VideoData> videoList;
List<String> videoDataList;
JSONArray json_array_list_of_videos;
int counter = 0;
int offset;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.listvideofragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoList = new ArrayList<>();
videoDataList = new ArrayList<>();
recyclerView = (RecyclerView) view.findViewById(R.id.list);
loadData(offset);
createRecycleView();
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(
linearLayoutManager) {
#Override
public void onLoadMore(int offset) {
// do somthing...
loadMoreData(offset);
}
});
}
private void loadMoreData(int offset) {
loadLimit += 10;
loadData(offset);
adapter.notifyDataSetChanged();
}
private void loadData(final int offset) {
try {
Request request = new Request.Builder()
.url("http://video.motti.be/api/video.getVideoList?offset=" +
offset
+ "&limit=20")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
try {
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
String json_string_obj = response.body().string();
JSONObject url = new JSONObject(json_string_obj);
json_array_list_of_videos = url.getJSONArray("data");
System.out.println(json_array_list_of_videos.toString());
for (int y = 0; y <= 9; y++) {
if (json_array_list_of_videos.get(y).toString().equals("A9knX0GXrg")) {
videoDataList.add("6kS9Tt1e47g");
} else {
videoDataList.add(json_array_list_of_videos.get(y).toString());
System.out.println("++++++" + json_array_list_of_videos.get(y).toString());
}
}
for (int i = counter; i <= loadLimit; i++) {
if (videoDataList == null) {
return;
} else {
VideoData next_queue_id = new VideoData(videoDataList.get(i));
videoList.add(next_queue_id);
counter++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public void createRecycleView() {
adapter = new RecyclerAdapter(videoList, getContext());
linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
I understand, that I get Response later then new adapter creates.For the lack of knowledge, as I sad, I have no idea how to make thread with onResponse method to wait.
Hope that you won't find this question as dull or stupid and will help me.
Thank you in advance!
You need to notify the adapter after you modify its list (videoList).
Currently the loadMoreData(int offset) method doesn't guaranty that because the loadData(offset); method can return before the list is modified (the request is processed asynchronously).
What you could do is this:
Remove the adapter.notifyDataSetChanged(); statement from the loadMoreData(int offset) method and add it to the onResponse(Response response) method.
Example:
#Override
public void onResponse(Response response) throws IOException {
try {
...
for (int i = counter; i <= loadLimit; i++) {
if (videoDataList == null) {
return;
} else {
VideoData next_queue_id = new VideoData(videoDataList.get(i));
videoList.add(next_queue_id);
counter++;
}
}
ListVideo.this.runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
This approach can create other problems because the videoList can be modified by multiple threads at the same time. You need to find a way to synchronize the access to this list or use a thread safe list.

Disable Checkbox click in multiselectListPreference in android

I am using mutliselectlistpreference that extends DialogPreference in my application. And i have not use any adapter for building the UI. Please find the below image.
The issue here is I am able to persist the CheckBox checked for Monday and Tuesday but i am not able to make the items read only wherein user will not able to unchecked the items. I want to make both items grey out. could you please help me out on this ?
#Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
if (entries == null || entryValues == null) {
throw new IllegalStateException(
"MultiSelectListPreference requires an entries array and an entryValues array.");
}
checked = new boolean[entryValues.length];
List<CharSequence> entryValuesList = Arrays.asList(entryValues);
List<CharSequence> entriesList = Arrays.asList(entries);
for (int i = 0; i < entryValues.length; ++i) {
if("Monday".equals(entriesList.get(i).toString())){
checked[i]=true;
}
}
if (values != null) {
for (String value : values) {
int index = entryValuesList.indexOf(value);
if (index != -1) {
checked[index] = true;
}
}
}
builder.setMultiChoiceItems(entries, checked,
new OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
checked[which] = isChecked;
}
});
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && entryValues != null) {
for (int i = 0; i < entryValues.length; ++i) {
if (checked[i]) {
newValues.add(entryValues[i].toString());
}
}
if (callChangeListener(newValues)) {
setValues(newValues);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
CharSequence[] array = a.getTextArray(index);
Set<String> set = new HashSet<String>();
for (CharSequence item : array) {
set.add(item.toString());
}
return set;
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
#SuppressWarnings("unchecked")
Set<String> defaultValues = (Set<String>) defaultValue;
setValues((restorePersistedValue ? getPersistedStringSet(values)
: defaultValues));
}
private Set<String> getPersistedStringSet(Set<String> defaultReturnValue) {
String key = getKey();
//String value = getSharedPreferences().getString("4", "Generic");
return getSharedPreferences().getStringSet(key, defaultReturnValue);
}
private boolean persistStringSet(Set<String> values) {
if (shouldPersist()) {
// Shouldn't store null
if (values == getPersistedStringSet(null)) {
return true;
}
}
SharedPreferences.Editor editor = getEditor();
editor.putStringSet(getKey(), values);
editor.apply();
return true;
}
#Override
protected Parcelable onSaveInstanceState() {
if (isPersistent()) {
return super.onSaveInstanceState();
} else {
throw new IllegalStateException("Must always be persistent");
}
}
You can use them;
checkBox.setEnabled(true); // enable checkbox
checkBox.setEnabled(false); // disable checkbox
Also you can disable them after check the checkBox with this code:
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked){
checkBox.setEnabled(false); // disable checkbox
}
}
});

Categories