[android studio]having problem with handler.postdelayed [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
hope you doing great.i'm very new to android programming and i have source of an app which i intend to modify and add PatternLockView library to it . i watched a youtube video tutorial but i can't use handler.postdelay option in the code (android studio returns with : Cannot resolve symbol 'postdelayed').the coder who made the tutorial didn't got any errors or so but android studio gives me lots of them . any help or hint is appreciated.
here is the code :
Handler handler = new Handler ();
handler.postdelayed {
#Override
public void run() {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String password = preferences.getString("password","0");
if (password.equals("0")) {
Intent intent = new Intent (getApplicationContext(),CreatePasswordActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent (getApplicationContext(),InputPasswordActivity.class);
startActivity(intent);
finish();
}
}
}2000
/*#######################################################
*
* Maintained by Gregor Santner, 2017-
* https://gsantner.net/
*
* License of this file: Apache 2.0 (Commercial upon request)
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.markor.activity;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import com.pixplicity.generate.Rate;
import net.gsantner.markor.BuildConfig;
import net.gsantner.markor.R;
import net.gsantner.markor.format.TextFormat;
import net.gsantner.markor.ui.FilesystemViewerCreator;
import net.gsantner.markor.ui.NewFileDialog;
import net.gsantner.markor.util.ActivityUtils;
import net.gsantner.markor.util.AppSettings;
import net.gsantner.markor.util.PermissionChecker;
import net.gsantner.markor.util.ShareUtil;
import net.gsantner.opoc.activity.GsFragmentBase;
import net.gsantner.opoc.format.markdown.SimpleMarkdownParser;
import net.gsantner.opoc.ui.FilesystemViewerAdapter;
import net.gsantner.opoc.ui.FilesystemViewerData;
import net.gsantner.opoc.ui.FilesystemViewerFragment;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import butterknife.OnPageChange;
public class MainActivity extends AppActivityBase implements FilesystemViewerFragment.FilesystemFragmentOptionsListener, BottomNavigationView.OnNavigationItemSelectedListener {
//START
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed( () -> {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String password = preferences.getString("password","0");
if (password.equals("0")) {
Intent intent = new Intent (getApplicationContext(),CreatePasswordActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent (getApplicationContext(),InputPasswordActivity.class);
startActivity(intent);
finish();
}
}, 2000);
// END
public static boolean IS_DEBUG_ENABLED = false;
#BindView(R.id.toolbar)
public Toolbar _toolbar;
#BindView(R.id.bottom_navigation_bar)
BottomNavigationView _bottomNav;
#BindView(R.id.fab_add_new_item)
FloatingActionButton _fab;
#BindView(R.id.main__view_pager_container)
ViewPager _viewPager;
private SectionsPagerAdapter _viewPagerAdapter;
private boolean _doubleBackToExitPressedOnce;
private MenuItem _lastBottomMenuItem;
private AppSettings _appSettings;
private ActivityUtils _contextUtils;
private ShareUtil _shareUtil;
#SuppressLint("SdCardPath")
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setExitTransition(null);
}
_appSettings = new AppSettings(this);
_contextUtils = new ActivityUtils(this);
_shareUtil = new ShareUtil(this);
_contextUtils.setAppLanguage(_appSettings.getLanguage());
if (_appSettings.isOverviewStatusBarHidden()) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setTheme(_appSettings.isDarkThemeEnabled() ? R.style.AppTheme_Dark : R.style.AppTheme_Light);
super.onCreate(savedInstanceState);
setContentView(R.layout.main__activity);
ButterKnife.bind(this);
setSupportActionBar(_toolbar);
_toolbar.setOnClickListener(this::onToolbarTitleClicked);
optShowRate();
try {
if (_appSettings.isAppCurrentVersionFirstStart(true)) {
SimpleMarkdownParser smp = SimpleMarkdownParser.get().setDefaultSmpFilter(SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);
String html = "";
html += smp.parse(getString(R.string.copyright_license_text_official).replace("\n", " \n"), "").getHtml();
html += "<br/><br/><br/><big><big>" + getString(R.string.changelog) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.changelog), "", SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);
html += "<br/><br/><br/><big><big>" + getString(R.string.licenses) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.licenses_3rd_party), "").getHtml();
ActivityUtils _au = new ActivityUtils(this);
_au.showDialogWithHtmlTextView(0, html);
}
} catch (IOException e) {
e.printStackTrace();
}
IntroActivity.optStart(this);
// Setup viewpager
_viewPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
_viewPager.setAdapter(_viewPagerAdapter);
_viewPager.setOffscreenPageLimit(4);
_bottomNav.setOnNavigationItemSelectedListener(this);
// noinspection PointlessBooleanExpression - Send Test intent
if (BuildConfig.IS_TEST_BUILD && false) {
DocumentActivity.launch(this, new File("/sdcard/Documents/mordor/aa-beamer.md"), false, true, null, null);
}
(new ActivityUtils(this)).applySpecialLaunchersVisibility(_appSettings.isSpecialFileLaunchersEnabled());
_bottomNav.postDelayed(() -> {
if (_appSettings.getAppStartupTab() != R.id.nav_notebook) {
_bottomNav.setSelectedItemId(_appSettings.getAppStartupTab());
}
}, 1);
}
private void optShowRate() {
new Rate.Builder(this)
.setTriggerCount(4)
.setMinimumInstallTime((int) TimeUnit.MINUTES.toMillis(30))
.setFeedbackAction(() -> new ActivityUtils(this).showGooglePlayEntryForThisApp())
.build().count().showRequest();
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionChecker permc = new PermissionChecker(this);
permc.checkPermissionResult(requestCode, permissions, grantResults);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
AppSettings as = new AppSettings(this);
switch (item.getItemId()) {
case R.id.action_preview: {
File f = _bottomNav.getSelectedItemId() == R.id.nav_quicknote ? as.getQuickNoteFile() : as.getTodoFile();
DocumentActivity.launch(MainActivity.this, f, false, true, null, null);
return true;
}
case R.id.action_settings: {
new ActivityUtils(this).animateToActivity(SettingsActivity.class, false, null);
return true;
}
}
return false;
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main__menu, menu);
menu.findItem(R.id.action_settings).setVisible(_appSettings.isShowSettingsOptionInMainToolbar());
_contextUtils.tintMenuItems(menu, true, Color.WHITE);
_contextUtils.setSubMenuIconsVisiblity(menu, true);
return true;
}
#Override
protected void onResume() {
//new AndroidSupportMeWrapper(this).mainOnResume();
super.onResume();
IS_DEBUG_ENABLED = BuildConfig.IS_TEST_BUILD;
if (_appSettings.isRecreateMainRequired()) {
// recreate(); // does not remake fragments
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && _appSettings.isMultiWindowEnabled()) {
setTaskDescription(new ActivityManager.TaskDescription(getString(R.string.app_name)));
}
int color = ContextCompat.getColor(this, _appSettings.isDarkThemeEnabled()
? R.color.dark__background : R.color.light__background);
_viewPager.getRootView().setBackgroundColor(color);
if (_appSettings.isKeepScreenOn()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
#Override
#SuppressWarnings("unused")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Determine some results and forward using Local Broadcast
Object result = _shareUtil.extractResultFromActivityResult(requestCode, resultCode, data, this);
try {
FilesystemViewerFragment frag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
frag.getAdapter().reconfigure();
} catch (Exception ignored) {
recreate();
}
}
#OnLongClick({R.id.fab_add_new_item})
public boolean onLongClickFab(View view) {
PermissionChecker permc = new PermissionChecker(this);
FilesystemViewerFragment fsFrag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (fsFrag != null && permc.mkdirIfStoragePermissionGranted()) {
fsFrag.getAdapter().setCurrentFolder(fsFrag.getCurrentFolder().equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_RECENTS)
? FilesystemViewerAdapter.VIRTUAL_STORAGE_FAVOURITE : FilesystemViewerAdapter.VIRTUAL_STORAGE_RECENTS
, true);
}
return true;
}
#SuppressWarnings("SwitchStatementWithTooFewBranches")
#OnClick({R.id.fab_add_new_item})
public void onClickFab(View view) {
PermissionChecker permc = new PermissionChecker(this);
FilesystemViewerFragment fsFrag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (fsFrag == null) {
return;
}
if (fsFrag.getAdapter().isCurrentFolderVirtual()) {
fsFrag.getAdapter().loadFolder(_appSettings.getNotebookDirectory());
return;
}
if (permc.mkdirIfStoragePermissionGranted()) {
switch (view.getId()) {
case R.id.fab_add_new_item: {
if (_shareUtil.isUnderStorageAccessFolder(fsFrag.getCurrentFolder()) && _shareUtil.getStorageAccessFrameworkTreeUri() == null) {
_shareUtil.showMountSdDialog(this);
return;
}
if (!fsFrag.getAdapter().isCurrentFolderWriteable()) {
return;
}
NewFileDialog dialog = NewFileDialog.newInstance(fsFrag.getCurrentFolder(), true, (ok, f) -> {
if (ok) {
if (f.isFile()) {
DocumentActivity.launch(MainActivity.this, f, false, false, null, null);
} else if (f.isDirectory()) {
FilesystemViewerFragment wrFragment = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (wrFragment != null) {
wrFragment.reloadCurrentFolder();
}
}
}
});
dialog.show(getSupportFragmentManager(), NewFileDialog.FRAGMENT_TAG);
break;
}
}
}
}
#Override
public void onBackPressed() {
// Exit confirmed with 2xBack
if (_doubleBackToExitPressedOnce) {
super.onBackPressed();
_appSettings.setFileBrowserLastBrowsedFolder(_appSettings.getNotebookDirectory());
return;
}
// Check if fragment handled back press
GsFragmentBase frag = _viewPagerAdapter.getCachedFragments().get(_viewPager.getCurrentItem());
if (frag != null && frag.onBackPressed()) {
return;
}
// Confirm exit with back / snackbar
_doubleBackToExitPressedOnce = true;
new ActivityUtils(this).showSnackBar(R.string.press_back_again_to_exit, false, R.string.exit, view -> finish());
new Handler().postDelayed(() -> _doubleBackToExitPressedOnce = false, 2000);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
updateFabVisibility(item.getItemId() == R.id.nav_notebook);
PermissionChecker permc = new PermissionChecker(this);
switch (item.getItemId()) {
case R.id.nav_notebook: {
_viewPager.setCurrentItem(0);
_toolbar.setTitle(getFileBrowserTitle());
return true;
}
case R.id.nav_todo: {
permc.doIfExtStoragePermissionGranted(); // cannot prevent bottom tab selection
restoreDefaultToolbar();
_viewPager.setCurrentItem(1);
_toolbar.setTitle(R.string.todo);
return true;
}
case R.id.nav_quicknote: {
permc.doIfExtStoragePermissionGranted(); // cannot prevent bottom tab selection
restoreDefaultToolbar();
_viewPager.setCurrentItem(2);
_toolbar.setTitle(R.string.quicknote);
return true;
}
case R.id.nav_more: {
restoreDefaultToolbar();
_viewPager.setCurrentItem(3);
_toolbar.setTitle(R.string.more);
return true;
}
}
return false;
}
public void updateFabVisibility(boolean visible) {
if (visible) {
_fab.show();
} else {
_fab.hide();
}
}
public String getFileBrowserTitle() {
final File file = _appSettings.getFileBrowserLastBrowsedFolder();
String title = getString(R.string.app_name);
if (!_appSettings.getNotebookDirectory().getAbsolutePath().equals(file.getAbsolutePath())) {
title = "> " + file.getName();
}
return title;
}
#OnPageChange(value = R.id.main__view_pager_container, callback = OnPageChange.Callback.PAGE_SELECTED)
public void onViewPagerPageSelected(int pos) {
Menu menu = _bottomNav.getMenu();
PermissionChecker permc = new PermissionChecker(this);
(_lastBottomMenuItem != null ? _lastBottomMenuItem : menu.getItem(0)).setChecked(false);
_lastBottomMenuItem = menu.getItem(pos).setChecked(true);
updateFabVisibility(pos == 0);
_toolbar.setTitle(new String[]{getFileBrowserTitle(), getString(R.string.todo), getString(R.string.quicknote), getString(R.string.more)}[pos]);
if (pos > 0 && pos < 3) {
permc.doIfExtStoragePermissionGranted(); // cannot prevent bottom tab selection
}
}
private FilesystemViewerData.Options _filesystemDialogOptions = null;
#Override
public FilesystemViewerData.Options getFilesystemFragmentOptions(FilesystemViewerData.Options existingOptions) {
if (_filesystemDialogOptions == null) {
_filesystemDialogOptions = FilesystemViewerCreator.prepareFsViewerOpts(getApplicationContext(), false, new FilesystemViewerData.SelectionListenerAdapter() {
#Override
public void onFsViewerConfig(FilesystemViewerData.Options dopt) {
dopt.descModtimeInsteadOfParent = true;
//opt.rootFolder = _appSettings.getNotebookDirectory();
dopt.rootFolder = _appSettings.getFolderToLoadByMenuId(_appSettings.getAppStartupFolderMenuId());
dopt.folderFirst = _appSettings.isFilesystemListFolderFirst();
dopt.doSelectMultiple = dopt.doSelectFolder = dopt.doSelectFile = true;
dopt.mountedStorageFolder = _shareUtil.getStorageAccessFolder();
dopt.showDotFiles = _appSettings.isShowDotFiles();
dopt.fileComparable = FilesystemViewerFragment.sortFolder(null);
}
#Override
public void onFsViewerDoUiUpdate(FilesystemViewerAdapter adapter) {
if (adapter != null && adapter.getCurrentFolder() != null && !TextUtils.isEmpty(adapter.getCurrentFolder().getName())) {
_appSettings.setFileBrowserLastBrowsedFolder(adapter.getCurrentFolder());
_toolbar.setTitle(adapter.areItemsSelected() ? "" : getFileBrowserTitle());
invalidateOptionsMenu();
if (adapter.getCurrentFolder().equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_FAVOURITE)) {
adapter.getFsOptions().favouriteFiles = _appSettings.getFavouriteFiles();
}
}
}
#Override
public void onFsViewerSelected(String request, File file, final Integer lineNumber) {
if (TextFormat.isTextFile(file)) {
DocumentActivity.launch(MainActivity.this, file, false, null, null, lineNumber);
} else if (file.getName().toLowerCase().endsWith(".apk")) {
_shareUtil.requestApkInstallation(file);
} else {
DocumentActivity.askUserIfWantsToOpenFileInThisApp(MainActivity.this, file);
}
}
});
}
return _filesystemDialogOptions;
}
class SectionsPagerAdapter extends FragmentPagerAdapter {
private HashMap<Integer, GsFragmentBase> _fragCache = new LinkedHashMap<>();
SectionsPagerAdapter(FragmentManager fragMgr) {
super(fragMgr);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
GsFragmentBase fragment = (GsFragmentBase) super.instantiateItem(container, position);
_fragCache.put(position, fragment);
return fragment;
}
#Override
public Fragment getItem(int pos) {
final Fragment existing = _fragCache.get(pos);
if (existing != null) {
return existing;
}
switch (_bottomNav.getMenu().getItem(pos).getItemId()) {
default:
case R.id.nav_notebook: {
return FilesystemViewerFragment.newInstance(getFilesystemFragmentOptions(null));
}
case R.id.nav_quicknote: {
return DocumentEditFragment.newInstance(_appSettings.getQuickNoteFile(), false, -1);
}
case R.id.nav_todo: {
return DocumentEditFragment.newInstance(_appSettings.getTodoFile(), false, -1);
}
case R.id.nav_more: {
return MoreFragment.newInstance();
}
}
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
_fragCache.remove(position);
}
#Override
public int getCount() {
return _bottomNav.getMenu().size();
}
public GsFragmentBase getFragmentByTag(String fragmentTag) {
for (GsFragmentBase frag : _fragCache.values()) {
if (fragmentTag.equals(frag.getFragmentTag())) {
return frag;
}
}
return null;
}
public HashMap<Integer, GsFragmentBase> getCachedFragments() {
return _fragCache;
}
}
#Override
protected void onStop() {
super.onStop();
restoreDefaultToolbar();
}
/**
* Restores the default toolbar. Used when changing the tab or moving to another activity
* while {#link FilesystemViewerFragment} action mode is active (e.g. when renaming a file)
*/
private void restoreDefaultToolbar() {
FilesystemViewerFragment wrFragment = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (wrFragment != null) {
wrFragment.clearSelection();
}
}
private void onToolbarTitleClicked(View v) {
Fragment f = _viewPagerAdapter.getItem(_viewPager.getCurrentItem());
if (f instanceof DocumentEditFragment) {
DocumentEditFragment def = (DocumentEditFragment) f;
def.onToolbarTitleClicked(_toolbar);
}
}
}

Since the postDelayed is a method, you have to use () along with it. It takes 2 parameters, first one is a Runnable object and second one is a millisecond value to delay which is an int type. Also Handler() constructor is depracated, that's why you have to bind your handler to a looper object, commonly to the main looper. Here is the fixed code:
// Make sure you import the right Handler class
import android.os.Handler;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed( () -> {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String password = preferences.getString("password","0");
if (password.equals("0")) {
Intent intent = new Intent (getApplicationContext(),CreatePasswordActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent (getApplicationContext(),InputPasswordActivity.class);
startActivity(intent);
finish();
}
}, millisecondDelay);
UPDATE
I've noted that your postdelayed syntax isn't correct. It must be as postDelayed. I updated my answer chek the code out again.

Related

How to send data sent by BLE Device in a fragment to a new activity for display and plotting graph in app?

I am completely new to Android and just learned Object-oriented programming. My project requires me to build something on open-source code. I am really struggling with this special case. Two fragments are under activity_main, one of them is TerminalFragment. I added a menuItem (R.id.plot) in it and set if the user clicks this Item that will lead him from TerminalFragment to activity_main2. Due to receive(byte data) and TerminalFragment still on active, the data is still printing out by receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); in activity_main.
Now, I want to convert the data to String and send it to activity_main2 for display in recyclerview and plotting graph. I am trying to use putextra and getextra but not sure how to access data from getextra in activity_main2. In my testing, the recyclerview just showed "John". Is something missing in my method? Does anyone have a better idea? Much Appreciated.
TerminalFragment
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
private String output;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
//receive.;
return true;
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.toString(); // CharSequence to String
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); // send data to next activity, MainActivity2
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {// receive data
receive(data); // send data to printout
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
MainActivity2.java (new activity)
package de.kai_morich.simple_bluetooth_le_terminal;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
Fragment CustomFragment;
private ArrayList<Data> dataList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
if (savedInstanceState == null) {
Bundle extra = getIntent().getExtras();
if (extra == null) {
data = null;
receiveData(data);
} else {
data = extra.getString("output");
receiveData(data);
}
} else {
data = (String) savedInstanceState.getSerializable("output");
receiveData(data);
}
setAdapter();
}
private void receiveData(String data){
String Data = data;
dataList.add(new Data("John"));
dataList.add(new Data(Data));
}
private void setAdapter() {
recyclerAdapter adapter = new recyclerAdapter(dataList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_plot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.dataplot:
Toast.makeText(this, "dataplot", Toast.LENGTH_SHORT).show();
replaceFragment(new DataPlotFragment());
return true;
case R.id.fft:
Toast.makeText(this, "FFT", Toast.LENGTH_SHORT).show();
replaceFragment(new FftFragment());
return true;
case R.id.data:
Toast.makeText(this, "DATA", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.plotframelayout,fragment);
fragmentTransaction.commit();
}
}
I realized I also need to add getText() in receive(). However, the recycler view won't update itself, it just captures what it has in the recyclerview of activity_main with TerminalFragment when the user click the menuItem (id,plot). Either getextrastring() or using bundle able to pass the data to Mainactivity2.
I think I need to add something else to keep adding data to the recyclerview of activity_main2 from activity_main.
onOptionsItemSelected of TerminalFragment
if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); //output
startActivity(intent);
return true;
}
receive() of TerminalFragment
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.getText().toString(); // CharSequence to String
}
}
OnCreate of mainActivity2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
data = extras.getString("output");
receiveData(data);
}
setAdapter();
}

I need to perform add to cart functionality with the option of increment or decrement quantity of item

product quantity changes button but when I click the add to cart button and change the visibility to gone others + , - buttons visibility to visible show on the screen then I click any of this two-button and their listener didn't work and after restarting the app both + , - buttons start working correctly. One more thing, I need my notification badge value shouldn't be changed if one product is already in the cart then changing its quantity, but in my case value change if I increase the quantity or decrease the quantity of the product. Thanks in advance
HomeFragment
package colon.semi.com.dealMall.fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
import java.util.List;
import colon.semi.com.dealMall.R;
import colon.semi.com.dealMall.Utils.AppClass;
import colon.semi.com.dealMall.Utils.Constants;
import colon.semi.com.dealMall.adapters.DealsSliderAdapter;
import colon.semi.com.dealMall.adapters.DevicesParentRecyclerAdapter;
import colon.semi.com.dealMall.adapters.SliderAdapterExample;
import colon.semi.com.dealMall.adapters.TopSellingAdapter;
import colon.semi.com.dealMall.dataModels.CartDataTable;
import colon.semi.com.dealMall.dataModels.CartResponse;
import colon.semi.com.dealMall.dataModels.HomeDataModel;
import colon.semi.com.dealMall.dataModels.ImagesListDM;
import colon.semi.com.dealMall.dataModels.Points;
import colon.semi.com.dealMall.dataModels.Product;
import colon.semi.com.dealMall.dataModels.SliderImagesResponse;
import colon.semi.com.dealMall.dataModels.TopSellingResponse;
import colon.semi.com.dealMall.viewModels.CartViewModel;
import colon.semi.com.dealMall.viewModels.HomeFragmentViewModel;
import colon.semi.com.dealMall.viewModels.PointsViewModel;
public class HomeFragment extends Fragment {
HomeFragmentViewModel homeFragmentViewModel;
View view;
SliderView sliderView;
SliderView imageSliderDeals;
RecyclerView recyclerView;
private ArrayList<String> listTitleRecycler = new ArrayList<>();
DevicesParentRecyclerAdapter homeParentRecyclerAdapter;
boolean topSellingComplete = false;
boolean latestComplete = false;
boolean allproductsComplete = false;
HomeDataModel homeDataModel = new HomeDataModel();
CartViewModel cartViewModel;
ProgressDialog progressDialog;
RecyclerView recylerTimeDeal;
TopSellingAdapter timeDealAdapter;
int[] imgResLounge = {R.drawable.ic_get_free, R.drawable.ic_seasonal_deals,
R.drawable.ic_grocery_deals,
R.drawable.ic_stationary_deals};
//CategoryNames
String[] imgNamesLounge = {"Men\nLounge", "Women\nLounge", "Cosmetic\nLounge", "Garments\nLounge"};
//Liststudent ERP OBJECT
ArrayList<ImagesListDM> loungeList = new ArrayList<>();
SharedPreferences sharedPreferences;
private TextView totalPointsTextView;
private TextView totalPrice;
private PointsViewModel pointsViewModel;
private View viewParent;
private boolean isLogin;
private int userId;
private List<CartDataTable> cartDataTableList = new ArrayList<>();
private int pos;
private int pQun;
private int pId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
initViews();
initListeners();
getSliderImages();
// getCartItem();
isLogin = sharedPreferences.getBoolean(Constants.USER_IS_LOGIN, false);
if (Constants.topSellingProduct != null) {
if (!Constants.topSellingProduct.isEmpty()) {
recylerTimeDeal.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
timeDealAdapter = new TopSellingAdapter(Constants.topSellingProduct, cartDataTableList,
getActivity());
recylerTimeDeal.setAdapter(timeDealAdapter);
clickListner(view);
}
} else {
getTopSellingProducts(1);
}
if (Constants.latestProduct != null) {
if (!Constants.latestProduct.isEmpty()) {
homeDataModel.setLatestList(Constants.latestProduct);
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
getLatestProducts(1);
}
if (Constants.allProducts != null) {
if (!Constants.allProducts.isEmpty()) {
homeDataModel.setAllProductList(Constants.allProducts);
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
getAllProducts(1);
}
return view;
}
#Override
public void onResume() {
isLogin = sharedPreferences.getBoolean(Constants.USER_IS_LOGIN, false);
// if (isLogin) {
userId = sharedPreferences.getInt(Constants.USER_ID, 0);
cartViewModel.getCartDataTableLiveData(userId).observe(getActivity(), new
Observer<List<CartDataTable>>() {
#Override
public void onChanged(List<CartDataTable> cartDataTables) {
if (cartDataTables != null) {
cartDataTableList = cartDataTables;
}
});
//}
super.onResume();
}
private void clickListner(View view1) {
timeDealAdapter.setOnItemClickListener(new TopSellingAdapter.OnItemClickListener() {
#Override
public void onAddtoCartClick(View view, Product product) {
Log.e("onAddtoCartClick", "called");
userId = sharedPreferences.getInt(Constants.USER_ID, 0);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
viewParent = (View) view.getParent();
progressDialog.dismiss();
int quantity = 1;
cartViewModel.addProductToCart(userId, product.getProduct_id(),
quantity).observe(getActivity(), new Observer<CartResponse>() {
#Override
public void onChanged(CartResponse cartResponse) {
if (cartResponse != null) {
progressDialog.dismiss();
if (cartResponse.getMessage().equals("Product added successfully")) {
progressDialog.dismiss();
CartDataTable cartDataTable = new CartDataTable();
cartDataTable.setProductId(product.getProduct_id());
cartDataTable.setProductQuantity(1);
cartDataTable.setUserId(userId);
cartViewModel.insertCart(cartDataTable);
progressDialog.invalidateOptionsMenu();
} else {
Toast.makeText(getActivity(), cartResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void updateCartData(int productId, int quantity, int position, View view) {
pId = productId;
pQun = quantity;
pos = position;
viewParent = (View) view.getParent();
Log.d("updateCartData2", pId + " " + pQun);
CartDataTable cartDataTable = cartViewModel.getCart2(productId, userId);
userId = sharedPreferences.getInt(Constants.USER_ID, 0);
Log.d("userId2", String.valueOf(userId));
if (cartDataTable != null) {
if (pQun == 0) {
cartViewModel.deleteCart(cartDataTable);
} else {
CartDataTable cartDataTable1 = new CartDataTable();
cartDataTable1.setProductQuantity(pQun);
cartDataTable1.setProductId(pId);
cartDataTable1.setCartId(cartDataTable.getCartId());
cartDataTable1.setUserId(userId);
cartViewModel.updateCart(cartDataTable1);
Log.d("cart2", "updated");
}
}
}
});
}
private void getSliderImages() {
if (AppClass.isOnline(getActivity())) {
homeFragmentViewModel.getSliderImages().observe(getActivity(), new
Observer<SliderImagesResponse>() {
#Override
public void onChanged(SliderImagesResponse sliderImagesResponse) {
if (sliderImagesResponse.getStatus() == 1) {
SliderAdapterExample adapter = new SliderAdapterExample(getContext(),
sliderImagesResponse.getData());
sliderView.setSliderAdapter(adapter);
sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
sliderView.setIndicatorSelectedColor(Color.WHITE);
sliderView.setIndicatorUnselectedColor(Color.GRAY);
sliderView.setScrollTimeInSec(4); //set scroll delay in seconds :
sliderView.startAutoCycle();
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+sliderImagesResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getTopSellingProducts(int page) {
if (AppClass.isOnline(getActivity())) {
progressDialog.show();
homeFragmentViewModel.getTopSellingProducts(page).observe(getActivity(), new
Observer<TopSellingResponse>() {
#Override
public void onChanged(TopSellingResponse topSellingResponse) {
if (topSellingResponse.getStatus() == 1) {
progressDialog.dismiss();
topSellingComplete = true;
Constants.topSellingProduct = topSellingResponse.getData();
recylerTimeDeal.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
timeDealAdapter = new TopSellingAdapter(topSellingResponse.getData(),
cartDataTableList, getActivity());
recylerTimeDeal.setAdapter(timeDealAdapter);
clickListner(view);
if (latestComplete || allproductsComplete) {
homeParentRecyclerAdapter.notifyDataSetChanged();
} else {
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+topSellingResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getLatestProducts(int page) {
if (AppClass.isOnline(getActivity())) {
progressDialog.show();
homeFragmentViewModel.getLatestProducts(page).observe(getActivity(), new
Observer<TopSellingResponse>() {
#Override
public void onChanged(TopSellingResponse topSellingResponse) {
if (topSellingResponse.getStatus() == 1) {
progressDialog.dismiss();
latestComplete = true;
Constants.latestProduct = topSellingResponse.getData();
homeDataModel.setLatestList(topSellingResponse.getData());
if(topSellingComplete || allproductsComplete) {
homeParentRecyclerAdapter.notifyDataSetChanged();
} else {
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+topSellingResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getAllProducts(int page) {
if (AppClass.isOnline(getActivity())) {
progressDialog.show();
homeFragmentViewModel.getAllProducts(page).observe(getActivity(), new
Observer<TopSellingResponse>() {
#Override
public void onChanged(TopSellingResponse topSellingResponse) {
if (topSellingResponse.getStatus() == 1) {
progressDialog.dismiss();
allproductsComplete = true;
Constants.allProducts = topSellingResponse.getData();
homeDataModel.setAllProductList(topSellingResponse.getData());
if(topSellingComplete || latestComplete) {
homeParentRecyclerAdapter.notifyDataSetChanged();
} else {
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+topSellingResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getPoints(int userId) {
pointsViewModel.getUserPointsById(userId).observe(getActivity(), new Observer<Points>() {
#Override
public void onChanged(Points points) {
progressDialog.dismiss();
if (points.getStatus() == 1) {
progressDialog.dismiss();
if (points.getTotalPoints() != null && points.getTotalDiscount() != null) {
totalPointsTextView.setText(points.getTotalPoints() + "");
totalPrice.setText(points.getTotalDiscount() + "");
} else {
Toast.makeText(getActivity(), "No Data Found", Toast.LENGTH_SHORT).show();
}
} else {
progressDialog.dismiss();
Toast.makeText(getActivity(), points.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void initViews() {
homeFragmentViewModel = new ViewModelProvider(this).get(HomeFragmentViewModel.class);
cartViewModel = new ViewModelProvider(this).get(CartViewModel.class);
sliderView = view.findViewById(R.id.imageSlider);
imageSliderDeals = view.findViewById(R.id.imageSliderDeals);
recyclerView = view.findViewById(R.id.recyclerView);
recylerTimeDeal = view.findViewById(R.id.recy_timeDeal);
totalPointsTextView = view.findViewById(R.id.pointsTextView);
totalPrice = view.findViewById(R.id.totalPrice);
pointsViewModel = new ViewModelProvider(this).get(PointsViewModel.class);
sharedPreferences = getActivity().getSharedPreferences(Constants.LOGIN_PREFERENCE,
Context.MODE_PRIVATE);
int userId = sharedPreferences.getInt(Constants.USER_ID, 0);
listTitleRecycler.add(0, "Top Selling");
listTitleRecycler.add(1, "Latest Products");
listTitleRecycler.add(2, "All Products");
homeDataModel.setTitleList(listTitleRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
recyclerView.setHasFixedSize(true);
progressDialog = new ProgressDialog(getContext(), R.style.exitDialogTheme);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
getPoints(userId);
}
private void initListeners() {
addLoungeToList();
DealsSliderAdapter adapter = new DealsSliderAdapter(getContext(), loungeList);
imageSliderDeals.setSliderAdapter(adapter);
imageSliderDeals.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
imageSliderDeals.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
imageSliderDeals.setScrollTimeInSec(4); //set scroll delay in seconds :
imageSliderDeals.startAutoCycle();
}
public void addLoungeToList() {
int i = 0;
for (String name : imgNamesLounge) {
ImagesListDM imagesListDM = new ImagesListDM();
imagesListDM.setImg(imgResLounge[i]);
imagesListDM.setNameImg(name);
loungeList.add(imagesListDM);
i++;
}
}
}
TopSellingAdapter
package colon.semi.com.dealMall.adapters;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.List;
import colon.semi.com.dealMall.R;
import colon.semi.com.dealMall.Utils.Constants;
import colon.semi.com.dealMall.dataModels.CartDataTable;
import colon.semi.com.dealMall.dataModels.Product;
import colon.semi.com.dealMall.uiActivities.ProductDetailActivity;
public class
TopSellingAdapter extends RecyclerView.Adapter<TopSellingAdapter.SingleItemRowHolder> {
private static OnItemClickListener mlistener; //just a variable
private ArrayList<Product> topSellingList;
private Context context;
private List<CartDataTable> cartDataTables;
int[] quantity;int[] pid;
int size;
public TopSellingAdapter(ArrayList<Product> topSellingList, List<CartDataTable> cartDataTableList, Context context) {
this.topSellingList = topSellingList;
this.cartDataTables = cartDataTableList;
this.context = context;
}
#Override
public void onBindViewHolder(#NonNull SingleItemRowHolder holder, final int position) {
SingleItemRowHolder viewHolder = (SingleItemRowHolder) holder;
Product product = topSellingList.get(position);
RequestOptions options = new RequestOptions()
.centerInside()
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.priority(Priority.HIGH);
Glide
.with(context)
.load(topSellingList.get(position).getImage_name())
.apply(options)
.into(viewHolder.image);
viewHolder.name.setText(topSellingList.get(position).getProduct_title());
viewHolder.price.setText(topSellingList.get(position).getPrice());
viewHolder.linear_label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra(Constants.PRODUCT_OBJECT, product);
context.startActivity(intent);
}
});
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mlistener!=null && position != RecyclerView.NO_POSITION){
viewHolder.addtocart.setVisibility(View.GONE);
viewHolder.cartLayout.setVisibility(View.VISIBLE);
viewHolder.quanTv.setText("1");
mlistener.onAddtoCartClick(v, topSellingList.get(position));
}
}
});
if (cartDataTables != null && cartDataTables.size() > 0) {
for (int i = 0; i < cartDataTables.size(); i++) {
if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
viewHolder.addtocart.setVisibility(View.GONE);
viewHolder.cartLayout.setVisibility(View.VISIBLE);
viewHolder.quanTv.setText(String.valueOf(cartDataTables.get(i).getProductQuantity()));
}
}
size = cartDataTables.size();
quantity = new int[size];
pid = new int[size];
}
// if (cartDataTables != null && cartDataTables.size() > 0) {
// int size = cartDataTables.size();
// int[] quantity = new int[size];
// int[] pid = new int[size];
Log.d("CartDataSize", String.valueOf(size));
for (int i = 0; i < size; i++) {
quantity[i] = cartDataTables.get(i).getProductQuantity();
pid[i] = cartDataTables.get(i).getProductId();
Log.d("CartData1", quantity[i] + " " + pid[i]);
}
holder.addProdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < size; i++) {
quantity[i]++;
viewHolder.quanTv.setText(String.valueOf(quantity[i]));
}
// int id = pid[size - 1];
//int q1 = quantity[size - 1];
// Log.d("q1", String.valueOf(q1));
for (int i = 0; i < size; i++) {
if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
// q1 = q1 + 1;
//Log.d("q2", String.valueOf(q1));
//Toast.makeText(context, String.valueOf(q1), Toast.LENGTH_SHORT).show();
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
}
else {
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
}
}
}
});
holder.minusProdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < size; i++) {
if (quantity[i] < 1) {
holder.cartLayout.setVisibility(View.GONE);
holder.addtocart.setVisibility(View.VISIBLE);
} else {
quantity[i]--;
if (quantity[i] < 1) {
holder.cartLayout.setVisibility(View.GONE);
holder.addtocart.setVisibility(View.VISIBLE);
}
viewHolder.quanTv.setText(String.valueOf(quantity[i]));
}
}
Toast.makeText(context, "Already added", Toast.LENGTH_SHORT).show();
for (int i = 0; i < size; i++) {
if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(),
v);
}
else {
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
}
}
}
});
}
#NonNull
#Override
public SingleItemRowHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.temp_top_selling_products, viewGroup, false);
SingleItemRowHolder categoriesListVH = new SingleItemRowHolder(view);
return categoriesListVH;
}
#Override
public int getItemCount() {
return (null != topSellingList ? topSellingList.size() : 0);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mlistener = listener;
}
public interface OnItemClickListener {
void onAddtoCartClick(View view, Product product);
void updateCartData(int productId, int quantity, int position, View view);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView name;
TextView price;
LinearLayout linear_label;
Button addtocart;
Button addProdButton;
Button minusProdButton;
TextView quanTv;
RelativeLayout cartLayout;
public SingleItemRowHolder(View view) {
super(view);
image = view.findViewById(R.id.image);
name = view.findViewById(R.id.name);
price = view.findViewById(R.id.price);
linear_label = view.findViewById(R.id.linear_label);
addtocart = view.findViewById(R.id.addToCartButtonHome);
cartLayout = view.findViewById(R.id.rel_prodCart_home);
addProdButton = view.findViewById(R.id.prodAddButtonHome);
quanTv = view.findViewById(R.id.productQuanTextViewHome);
minusProdButton = view.findViewById(R.id.prodMinusButtonHome);
}
}
}
first time when adapter constructor called there is no data in the cartDataTables list and because of my condition if (cartDataTables != null && cartDataTables.size() > 0), when I click add to cart button they found no data in the cartDataTables list because I didn't call notifyDataSetChanged() method or call the adapter constructor again, and my addtocart click listener is inside this condition if (cartDataTables != null && cartDataTables.size() > 0) that's why add to cart button click listner didn't work.
solution: call the adapter constructor again.

Why android ViewPager OnTouchListener not called at all

Why my ViewPager OnTouchListener doesn't fire at all !!
Here is my code below:
I'm using ViewPager to automatically slide photos but when i tap on the ViewPager I need to stop the auto sliding but the problem is that my OnTouchListener doesn't fire at all.
JAVA
man_fragment.java
package com.techzone.yallaassouk;
/**
* Created by Yazan on 4/26/2016.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.techzone.yallaassouk.Adapters.Brands_View_Adapter;
import com.techzone.yallaassouk.Adapters.Categories_View_Adapter;
import com.techzone.yallaassouk.Adapters.ImageSlideAdapter;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.DataItems.Brand;
import com.techzone.yallaassouk.DataItems.Category;
import com.techzone.yallaassouk.Utils.CirclePageIndicator;
import com.techzone.yallaassouk.Utils.PageIndicator;
import com.techzone.yallaassouk.Utils.CheckNetworkConnection;
import com.techzone.yallaassouk.json.GetJSONObject;
import com.techzone.yallaassouk.json.JsonReader;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
public class man_fragment extends Fragment {
public static final String ARG_ITEM_ID = "man_fragment";
private static final long ANIM_VIEWPAGER_DELAY = 5000;
private static final long ANIM_VIEWPAGER_DELAY_USER_VIEW = 10000;
private static final int TabNo = 1;
// UI References
ViewPager BandsViewPager;
PageIndicator mIndicator;
RecyclerView brands_Rec_View;
RecyclerView categories_Rec_View;
//lists
List<Band> bands;
List<Brand> brands;
List<Category> categories;
//tasks
RequestBandsTask bands_task;
RequestBrandsTask brands_task;
RequestCategoriesTask categories_task;
AlertDialog alertDialog;
boolean stopSliding = false;
String message;
//lists adapters
Brands_View_Adapter brands_adapter;
Categories_View_Adapter categories_adapter;
//runnables and handlers
private Runnable animateViewPager;
private Handler handler;
//urls
String brandsurl = "http://yazanallahham-001-site1.ftempurl.com/Brands.svc/json/brands/"+TabNo;
String categoriesurl = "http://yazanallahham-001-site1.ftempurl.com/categories.svc/json/categories/"+TabNo+"/0";
String bandsurl = "http://yazanallahham-001-site1.ftempurl.com/bands.svc/json/bands/0";
//activity
FragmentActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.man_fragment, container, false);
findViewById(rootView);
mIndicator.setOnPageChangeListener(new PageChangeListener());
BandsViewPager.setOnPageChangeListener(new PageChangeListener());
BandsViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
stopSliding = true;
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
// calls when touch release on ViewPager
if (bands != null && bands.size() != 0) {
stopSliding = false;
runnable(bands.size());
handler.postDelayed(animateViewPager,
ANIM_VIEWPAGER_DELAY_USER_VIEW);
}
break;
case MotionEvent.ACTION_MOVE:
// calls when ViewPager touch
if (handler != null && stopSliding == false) {
stopSliding = true;
handler.removeCallbacks(animateViewPager);
}
break;
}
return false;
}
});
// sendRequest();
//init brands recyclerview
brands_Rec_View.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
brands_Rec_View.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
categories_fragment nextFrag= new categories_fragment();
Bundle args = new Bundle();
Brand clickedBrand = (Brand)brands.get(position);
args.putInt("BrandId", clickedBrand.getId());
args.putInt("TabId", TabNo);
args.putString("BrandName", clickedBrand.getEnName());
nextFrag.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.main_content, nextFrag, categories_fragment.ARG_ITEM_ID)
.addToBackStack(categories_fragment.ARG_ITEM_ID)
.commit();
}
})
);
//init categories recyclerview
GridLayoutManager LLM = new GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false){
#Override
public boolean canScrollVertically(){
return false;
}
};
categories_Rec_View.setLayoutManager(LLM);
categories_Rec_View.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
//Log.d("categories","test click" + position);
Items_fragment nextFrag= new Items_fragment();
Bundle args = new Bundle();
Category clickedCategory = (Category)categories.get(position);
args.putInt("CategoryId", clickedCategory.getId());
args.putString("CategoryName", clickedCategory.getEnName());
args.putInt("BrandId", 0);
args.putInt("TabId", TabNo);
nextFrag.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.main_content, nextFrag, Items_fragment.ARG_ITEM_ID)
.addToBackStack(Items_fragment.ARG_ITEM_ID)
.commit();
}
})
);
return rootView;
}
private void findViewById(View view) {
BandsViewPager = (ViewPager) view.findViewById(R.id.man_view_pager);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
brands_Rec_View = (RecyclerView) view.findViewById(R.id.brands_RView);
categories_Rec_View = (RecyclerView) view.findViewById(R.id.categories_RView);
}
public void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
public void run() {
if (!stopSliding) {
if (BandsViewPager.getCurrentItem() == size - 1) {
BandsViewPager.setCurrentItem(0);
} else {
BandsViewPager.setCurrentItem(
BandsViewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
}
};
}
#Override
public void onResume() {
if (bands == null) {
sendRequest();
} else {
BandsViewPager.setAdapter(new ImageSlideAdapter(activity, bands,
man_fragment.this));
mIndicator.setViewPager(BandsViewPager);
runnable(bands.size());
//Re-run callback
handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
super.onResume();
}
#Override
public void onPause() {
if (bands_task != null)
bands_task.cancel(true);
if (handler != null) {
//Remove callback
handler.removeCallbacks(animateViewPager);
}
super.onPause();
}
private void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
bands_task = new RequestBandsTask(activity);
bands_task.execute(bandsurl);
brands_task = new RequestBrandsTask(activity);
brands_task.execute(brandsurl);
categories_task = new RequestCategoriesTask(activity);
categories_task.execute(categoriesurl);
} else {
message = getResources().getString(R.string.no_internet_connection);
showAlertDialog(message, true);
}
}
public void showAlertDialog(String message, final boolean finish) {
alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (finish)
activity.finish();
}
});
alertDialog.show();
}
private class PageChangeListener implements ViewPager.OnPageChangeListener {
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (bands != null) {
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private class RequestBandsTask extends AsyncTask<String, Void, List<Band>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestBandsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Band> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
bands = JsonReader.getBands(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return bands;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Band> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
bands = result;
if (result != null) {
if (bands != null && bands.size() != 0) {
//for brands_adapter
BandsViewPager.setAdapter(new ImageSlideAdapter(
activity, bands, man_fragment.this));
mIndicator.setViewPager(BandsViewPager);
runnable(bands.size());
handler.postDelayed(animateViewPager,
ANIM_VIEWPAGER_DELAY);
} else {
}
} else {
}
}
}
}
}
private class RequestBrandsTask extends AsyncTask<String, Void, List<Brand>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestBrandsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Brand> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
brands = JsonReader.getBrands(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return brands;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Brand> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
brands = result;
if (result != null) {
if (brands != null && brands.size() != 0) {
//for brands_adapter
brands_adapter = new Brands_View_Adapter(brands);
brands_Rec_View.setAdapter(brands_adapter);// set adapter on recyclerview
} else {
}
} else {
}
}
}
}
}
private class RequestCategoriesTask extends AsyncTask<String, Void, List<Category>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestCategoriesTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Category> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
categories = JsonReader.getCategories(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return categories;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Category> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
categories = result;
if (result != null) {
if (categories != null && categories.size() != 0) {
//for brands_adapter
categories_adapter = new Categories_View_Adapter(categories);
categories_Rec_View.setAdapter(categories_adapter);// set adapter on recyclerview
categories_Rec_View.getLayoutParams().height = (188*(categories_adapter.getItemCount()+1)+328);
} else {
}
} else {
}
}
}
}
}
}
View Pager Adapter
ImageSlideAdapter.java
package com.techzone.yallaassouk.Adapters;
/**
* Created by Yazan on 5/1/2016.
*/
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.ImageView;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.R;
import com.techzone.yallaassouk.TouchImageView;
import com.techzone.yallaassouk.fragment.ProductDetailFragment;
import com.techzone.yallaassouk.man_fragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
public class ImageSlideAdapter extends PagerAdapter {
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options;
private ImageLoadingListener imageListener;
FragmentActivity activity;
List<Band> bands;
Fragment homeFragment;
public ImageSlideAdapter(FragmentActivity activity, List<Band> bands,
Fragment homeFragment) {
this.activity = activity;
this.homeFragment = homeFragment;
this.bands = bands;
options = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.a1)
.showStubImage(R.drawable.a2)
.showImageForEmptyUri(R.drawable.a3).cacheInMemory()
.cacheOnDisc().build();
imageListener = new ImageDisplayListener();
}
#Override
public int getCount() {
return bands.size();
}
#Override
public View instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.vp_image, container, false);
ImageView mImageView = (ImageView) view
.findViewById(R.id.image_display);
imageLoader.displayImage(
((Band) bands.get(position)).getImageURL(), mImageView,
options, imageListener);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
private static class ImageDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Sorry for being not formatted. I'm new here
I found what was causing the 'ViewPager' not to fire 'OnTouchListener'
In layout XML file :
<com.techzone.yallaassouk.ExtendedViewPager
android:id="#+id/man_view_pager"
android:layout_width="fill_parent"
android:layout_height="137dp" />
<com.techzone.yallaassouk.Utils.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="130dp"/>
the problem was the 'paddingTop' of the 'CirclePageIndicator' it was set to '130dp' which covers the 'ViewPager' and it was receiving the touch events instead of 'ViewPager' itself.
Thank you.

How to Censored Bad Words / Offensive Words in Android Studio [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i'm developing an Android Social app in Android Studio
Can anyone know How to filter bad words / offensive words when posting a new status.
For Example i post something bad words and offensive it will turn to like this "****" also when i post many words it will turn like this "i will hit your ***** right now"
please if you know how to i really need it
Thank you in Advance.
This is my PublishingActivity.java Code
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.iscooldev.socialnetwork.R;
import com.iscooldev.socialnetwork.api.APIService;
import com.iscooldev.socialnetwork.api.GlobalAPI;
import com.iscooldev.socialnetwork.api.PostsAPI;
import com.iscooldev.socialnetwork.api.UsersAPI;
import com.iscooldev.socialnetwork.app.AppConst;
import com.iscooldev.socialnetwork.data.LocationModel;
import com.iscooldev.socialnetwork.data.ResponseModel;
import com.iscooldev.socialnetwork.data.userItem;
import com.iscooldev.socialnetwork.helpers.CacheManager;
import com.iscooldev.socialnetwork.helpers.CropSquareTransformation;
import com.iscooldev.socialnetwork.helpers.FilePath;
import com.iscooldev.socialnetwork.helpers.GPSHelper;
import com.iscooldev.socialnetwork.helpers.M;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.thin.downloadmanager.DownloadRequest;
import com.thin.downloadmanager.ThinDownloadManager;
import java.io.File;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
public class PublishActivity extends AppCompatActivity implements OnClickListener, DialogInterface.OnClickListener {
public Intent mIntent;
public LinearLayoutManager layoutManager;
EditText insertedLink;
private ImageView mImagePreview;
private ImageButton addPhoto;
private ImageButton sendStatus;
private ImageButton changePrivacy;
private EditText statusInput;
private TextView profileName, postPrivacy;
private ImageView profilePicture;
private String privacy = "public";
private String statusValue = null;
private String linkValue = null;
private Uri imageUriValue = null;
private LinearLayout urlPreviewLayout;
private TextView urlValuePreview;
private TextView placeValuePreview;
private LinearLayout placePreviewLayout;
private String placeValue = null;
private ThinDownloadManager downloadManager;
private CacheManager mCacheManager;
private Gson mGson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
mCacheManager = CacheManager.getInstance(this);
mGson = new Gson();
setContentView(R.layout.activity_publish);
initializeView();
if (getIntent().hasExtra(Intent.EXTRA_SUBJECT)) {
setStatusValue(getIntent().getExtras().get(Intent.EXTRA_SUBJECT).toString());
}
if (getIntent().hasExtra(Intent.EXTRA_TEXT)) {
String text = getIntent().getExtras().get(Intent.EXTRA_TEXT).toString();
if (M.isValidUrl(text)) {
setLinkValue(text);
} else {
setStatusValue(text);
}
}
if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
setImageUriValue((Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM));
M.L(getIntent().getType());
}
getUser();
}
}
public void initializeView() {
downloadManager = new ThinDownloadManager(AppConst.DOWNLOAD_THREAD_POOL_SIZE);
addPhoto = (ImageButton) findViewById(R.id.addPhoto);
sendStatus = (ImageButton) findViewById(R.id.sendStatus);
changePrivacy = (ImageButton) findViewById(R.id.changePrivacy);
mImagePreview = (ImageView) findViewById(R.id.imagePreview);
statusInput = (EditText) findViewById(R.id.statusEdittext);
profilePicture = (ImageView) findViewById(R.id.postOwnerImage);
profileName = (TextView) findViewById(R.id.postOwnerName);
postPrivacy = (TextView) findViewById(R.id.postPrivacy);
TextView removeLink = (TextView) findViewById(R.id.removeLink);
TextView removePlace = (TextView) findViewById(R.id.removePlace);
ImageButton addPlace = (ImageButton) findViewById(R.id.addPlace);
ImageButton addLink = (ImageButton) findViewById(R.id.addLink);
placePreviewLayout = (LinearLayout) findViewById(R.id.placePreviewLayout);
placeValuePreview = (TextView) findViewById(R.id.placeValuePreview);
urlPreviewLayout = (LinearLayout) findViewById(R.id.urlPreviewLayout);
urlValuePreview = (TextView) findViewById(R.id.urlValuePreview);
sendStatus.setOnClickListener(this);
addPhoto.setOnClickListener(this);
changePrivacy.setOnClickListener(this);
addPlace.setOnClickListener(this);
addLink.setOnClickListener(this);
removePlace.setOnClickListener(this);
removeLink.setOnClickListener(this);
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.title_publish));
}
private void getUser() {
if (M.isNetworkAvailable(this)) {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(0, new Callback<userItem>() {
#Override
public void success(userItem user, retrofit.client.Response response) {
try {
mCacheManager.write(mGson.toJson(user), "Profile-0.json");
updateView(user);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
} else {
try {
updateView((userItem) mGson.fromJson(mCacheManager.readString("Profile-0.json"), new TypeToken<userItem>() {
}.getType()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateView(userItem user) {
if (user.getName() != null) {
profileName.setText(user.getName());
} else {
profileName.setText(user.getUsername());
}
if (getFilePath(user.getPicture()) != null) {
Picasso.with(getApplicationContext())
.load(getFilePath(user.getPicture()))
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(profilePicture);
} else {
Picasso.with(getApplicationContext())
.load(AppConst.IMAGE_PROFILE_URL + user.getPicture())
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(profilePicture);
downloadFile(AppConst.IMAGE_PROFILE_URL + user.getPicture(), user.getPicture());
}
}
private void downloadFile(String url, String hash) {
if (getFilePath(hash) == null) {
Uri downloadUri = Uri.parse(url);
Uri destinationUri = Uri.parse(M.getFilePath(getApplicationContext(), hash));
DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setDestinationURI(destinationUri);
downloadManager.add(downloadRequest);
}
}
private String getFilePath(String hash) {
return M.filePath(getApplicationContext(), hash);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == AppConst.SELECT_PICTURE) {
setImageUriValue(data.getData());
}
}
}
#Override
public void onClick(final View v) {
if (v.getId() == R.id.removePlace) {
setPlaceValue(null);
} else if (v.getId() == R.id.removeLink) {
setLinkValue(null);
} else if (v.getId() == R.id.addPlace) {
final GPSHelper mGpsHelper = new GPSHelper(this);
if (mGpsHelper.canGetLocation()) {
GlobalAPI mGlobalAPI = APIService.createService(GlobalAPI.class, M.getToken(this));
mGlobalAPI.getCurrentPlace(mGpsHelper.getLatitude(), mGpsHelper.getLongitude(), new Callback<LocationModel>() {
#Override
public void success(LocationModel location, retrofit.client.Response response) {
if (location.isStatus()) {
setPlaceValue(location.getAddress());
} else {
mGpsHelper.showSettingsAlert();
}
}
#Override
public void failure(RetrofitError error) {
mGpsHelper.showSettingsAlert();
}
});
} else {
mGpsHelper.showSettingsAlert();
}
} else if (v.getId() == R.id.addLink) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(getString(R.string.Insert_a_link));
insertedLink = new EditText(this);
insertedLink.setText("http://");
alert.setView(insertedLink);
alert.setPositiveButton(getString(R.string.ok), this);
alert.setNegativeButton(getString(R.string.cancel), this);
alert.show();
} else if (v.getId() == addPhoto.getId()) {
launchImageChooser();
} else if (v.getId() == sendStatus.getId()) {
String statusText = statusInput.getText().toString().trim();
if (!statusText.isEmpty()) {
setStatusValue(statusText);
}
if (getStatusValue() == null && getImageUriValue() == null && getLinkValue() == null) {
M.T(v,
getString(R.string.Error_empty_post));
} else {
PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(this));
TypedFile image = null;
if (getImageUriValue() != null) {
image = new TypedFile("image/jpg", new File(FilePath.getPath(this, getImageUriValue())));
}
M.showLoadingDialog(this);
mPostsAPI.publishPost(image, getStatusValue(), getLinkValue(), getPlaceValue(), privacy, new Callback<ResponseModel>() {
#Override
public void success(ResponseModel responseModel, Response response) {
M.hideLoadingDialog();
M.T(v, responseModel.getMessage());
if (responseModel.isDone()) {
startActivity(new Intent(PublishActivity.this, MainActivity.class));
finish();
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.T(v, getString(R.string.ServerError));
}
});
}
} else if (v.getId() == changePrivacy.getId()) {
if (privacy.equals("public")) {
postPrivacy.setText(R.string.privatePrivacy);
privacy = "private";
M.T(v, getString(R.string.changed_to_private));
} else {
postPrivacy.setText(R.string.publicPrivacy);
privacy = "public";
M.T(v, getString(R.string.changed_to_public));
}
}
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Choose An Image"),
AppConst.SELECT_PICTURE);
}
#Override
public void onClick(DialogInterface dialog, int which) {
String Link = insertedLink.getText().toString();
if (!Link.equals("http://") && !Link.equals("")) {
setLinkValue(Link);
}
}
public String getPlaceValue() {
return placeValue;
}
public void setPlaceValue(String placeValue) {
if (placeValue != null) {
if (placePreviewLayout.getVisibility() != View.VISIBLE) {
placePreviewLayout.setVisibility(View.VISIBLE);
placeValuePreview.setText(placeValue);
}
} else {
if (placePreviewLayout.getVisibility() != View.GONE) {
placePreviewLayout.setVisibility(View.GONE);
placeValuePreview.setText("");
}
}
this.placeValue = placeValue;
}
public Uri getImageUriValue() {
return imageUriValue;
}
public void setImageUriValue(Uri imageUriValue) {
this.imageUriValue = imageUriValue;
mImagePreview.setImageURI(imageUriValue);
if (mImagePreview.getVisibility() != View.VISIBLE) {
mImagePreview.setVisibility(View.VISIBLE);
}
}
public String getLinkValue() {
return linkValue;
}
public void setLinkValue(String linkValue) {
if (linkValue != null) {
if (urlPreviewLayout.getVisibility() != View.VISIBLE) {
urlPreviewLayout.setVisibility(View.VISIBLE);
urlValuePreview.setText(linkValue);
}
} else {
if (urlPreviewLayout.getVisibility() != View.GONE) {
urlPreviewLayout.setVisibility(View.GONE);
urlValuePreview.setText("");
}
}
this.linkValue = linkValue;
}
public String getStatusValue() {
return statusValue;
}
public void setStatusValue(String statusValue) {
String statusInputValue = statusInput.getText().toString().trim();
if (!statusValue.equals(statusInputValue)) {
String finalStatus;
if (TextUtils.isEmpty(statusInputValue)) {
finalStatus = statusValue;
} else {
finalStatus = statusInputValue + " " + statusValue;
}
statusInput.setText(finalStatus);
this.statusValue = finalStatus;
} else {
this.statusValue = statusValue;
}
}
}
Suppose you have an input string s and the list of words you want to replace by asterisks:
String s = "i will hit your head right now";
List<String> words = Arrays.asList("head", "now"); // suppose these words are offensive
You just iterate over list of offensive words, looking if input string contains one, and perform a replacement. The simplest way to do this is by using regex:
for (String word : words) {
Pattern rx = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE);
s = rx.matcher(s).replaceAll(new String(new char[word.length()]).replace('\0', '*'));
}
// s: i will hit your **** right ***
I've added \\b at the front and end of regex pattern to match just whole words (i. e. "head" will be processed, "header" will not). And this piece:
new String(new char[n]).replace('\0', c)
constructs a new string of n chars c.
After that, use resulting s wherever you need.
It is a basic about java, not android related. A way to do this is you make a list of your bad words and replace it from the string that user input. Refer to example below
String userInput = "this is an example of some bad words";
ArrayList<String> badWords = new ArrayList<>();
badWords.add("some");
badWords.add("bad");
badWords.add("words");
for (int i = 0; i < badWords.size(); i++) {
String badWord = badWords.get(i);
if(userInput.toLowerCase().contains(badWord)){
userInput = userInput.replace(badWord, "*****");
}
}

Menu not displaying/flashes up momentarily and disappears

having an issue with getting an options menu to display from a fragment. If I don't have any of the code in the main activity portion nothing happens. After adding onCreateOptionsMenu to the main activity the icon appears momentarily in the toolbar, but then disappears, almost as if the view is being repainted?
Update:
Removed the onCreateOptionsMenu and onOptionsItemSelected from the fragment. Corrected the missing #Override on the onOptionsItemSelected in the activity. Issues persist. See updated WallpaperActivity.java below.
Updated WallpaperActivity.java
package com.death2all110.blisspapers;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageButton;
import android.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class WallpaperActivity extends Activity {
public final String TAG = "BlissPapers";
protected static final String MANIFEST = "wallpaper_manifest.xml";
protected static final int THUMBS_TO_SHOW = 4;
/*
* pull the manifest from the web server specified in config.xml or pull
* wallpaper_manifest.xml from local assets/ folder for testing
*/
public static final boolean USE_LOCAL_MANIFEST = false;
ArrayList<WallpaperCategory> categories = null;
ProgressDialog mLoadingDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primary_dark));
setContentView(R.layout.activity_wallpaper);
mLoadingDialog = new ProgressDialog(this);
mLoadingDialog.setCancelable(false);
mLoadingDialog.setIndeterminate(true);
mLoadingDialog.setMessage("Retreiving wallpapers from server...");
mLoadingDialog.show();
new LoadWallpaperManifest().execute();
UrlImageViewHelper.setErrorDrawable(getResources().getDrawable(com.death2all110.blisspapers.R.drawable.ic_error));
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, About.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
Wallpaper.wallpapersCreated = 0;
}
protected void loadPreviewFragment() {
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setActionBar(ab);
WallpaperPreviewFragment fragment = new WallpaperPreviewFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(android.R.id.content, fragment);
ft.commit();
}
public static class WallpaperPreviewFragment extends Fragment {
static final String TAG = "PreviewFragment";
WallpaperActivity mActivity;
View mView;
public int currentPage = -1;
public int highestExistingIndex = 0;
ImageButton back;
ImageButton next;
TextView pageNum;
ThumbnailView[] thumbs;
protected int selectedCategory = 0; // *should* be <ALL> wallpapers
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = (WallpaperActivity) getActivity();
next(); // load initial page
}
public void setCategory(int cat) {
selectedCategory = cat;
currentPage = -1;
next();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(com.death2all110.blisspapers.R.layout.activity_wallpaper, container, false);
back = (ImageButton) mView.findViewById(com.death2all110.blisspapers.R.id.backButton);
next = (ImageButton) mView.findViewById(com.death2all110.blisspapers.R.id.nextButton);
pageNum = (TextView) mView.findViewById(com.death2all110.blisspapers.R.id.textView1);
thumbs = new ThumbnailView[THUMBS_TO_SHOW];
thumbs[0] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView1);
thumbs[1] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView2);
thumbs[2] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView3);
thumbs[3] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView4);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
previous();
}
});
return mView;
}
public ArrayList<WallpaperCategory> getCategories() {
return mActivity.categories;
}
protected Wallpaper getWallpaper(int realIndex) {
return getCategories().get(selectedCategory).getWallpapers().get(realIndex);
}
protected void setThumbs() {
for (ThumbnailView v : thumbs)
v.setVisibility(View.INVISIBLE);
final int numWallpapersInCategory = getCategories().get(selectedCategory)
.getWallpapers().size();
boolean enableForward = true;
for (int i = 0; i < thumbs.length; i++) {
final int realIndex = (currentPage * thumbs.length + i);
if (realIndex >= (numWallpapersInCategory - 1)) {
enableForward = false;
break;
}
Wallpaper w = getWallpaper(realIndex);
thumbs[i].setOnClickListener(null);
thumbs[i].getName().setText(w.getName());
thumbs[i].getAuthor().setText(w.getAuthor());
UrlImageViewHelper.setUrlDrawable(thumbs[i].getThumbnail(), w.getThumbUrl(),
com.death2all110.blisspapers.R.drawable.ic_placeholder, new ThumbnailCallBack(w, realIndex));
}
back.setEnabled(currentPage != 0);
next.setEnabled(enableForward);
}
public void next() {
getNextButton().setEnabled(false);
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (++currentPage + 1));
setThumbs();
}
public void previous() {
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (--currentPage + 1));
setThumbs();
}
protected void skipToPage(int page) {
if (page < currentPage) {
while (page < currentPage) {
previous(); // should subtract page
}
} else if (page > currentPage) {
while (page > currentPage) {
next();
}
}
}
protected View getThumbView(int i) {
if (thumbs != null && thumbs.length > 0)
return thumbs[i];
else
return null;
}
protected ImageButton getNextButton() {
return next;
}
protected ImageButton getPreviousButton() {
return back;
}
class ThumbnailCallBack implements UrlImageViewCallback {
Wallpaper wall;
int index;
public ThumbnailCallBack(Wallpaper wall, int index) {
this.wall = wall;
this.index = index;
}
#Override
public void onLoaded(ImageView imageView, Drawable loadedDrawable, String url,
boolean loadedFromCache, boolean error) {
final int relativeIndex = index % 4;
if (!error) {
getThumbView(relativeIndex).setOnClickListener(
new ThumbnailClickListener(wall));
}
getThumbView(relativeIndex).setVisibility(View.VISIBLE);
if (relativeIndex == 3)
getNextButton().setEnabled(true);
}
}
class ThumbnailClickListener implements View.OnClickListener {
Wallpaper wall;
public ThumbnailClickListener(Wallpaper wallpaper) {
this.wall = wallpaper;
}
#Override
public void onClick(View v) {
Intent preview = new Intent(mActivity, Preview.class);
preview.putExtra("wp", wall.getUrl());
startActivity(preview);
}
}
}
public static String getDlDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_download_loc);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
}
public static String getSvDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return null;
}
}
protected String getWallpaperDestinationPath() {
String configFolder = getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath();
}
// couldn't find resource?
return null;
}
protected String getResourceString(int stringId) {
return getApplicationContext().getResources().getString(stringId);
}
public static String getResourceString(Context c, int id) {
return c.getResources().getString(id);
}
private class LoadWallpaperManifest extends
AsyncTask<Void, Boolean, ArrayList<WallpaperCategory>> {
#Override
protected ArrayList<WallpaperCategory> doInBackground(Void... v) {
try {
InputStream input = null;
if (USE_LOCAL_MANIFEST) {
input = getApplicationContext().getAssets().open(MANIFEST);
} else {
URL url = new URL(getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_manifest_url));
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical
// 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
input = new BufferedInputStream(url.openStream());
}
OutputStream output = getApplicationContext().openFileOutput(
MANIFEST, MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
// file finished downloading, parse it!
ManifestXmlParser parser = new ManifestXmlParser();
return parser.parse(new File(getApplicationContext().getFilesDir(), MANIFEST),
getApplicationContext());
} catch (Exception e) {
Log.d(TAG, "Exception!", e);
}
return null;
}
#Override
protected void onPostExecute(ArrayList<WallpaperCategory> result) {
categories = result;
if (categories != null)
loadPreviewFragment();
mLoadingDialog.cancel();
super.onPostExecute(result);
}
}
}
Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_about"
android:icon="#drawable/ic_menu_info"
android:title="#string/action_about"
android:showAsAction="always">
</item>
</menu>
In your onCreate() method for your fragment, try adding this one line of code:
setHasOptionsMenu(true);
Android API reference: enter link description here
I had the same problem when implementing a menu from a fragment
To me you should keep only one reference to onCreateOptionsMenu() and onOptionsItemSelected(). Since the fragment is hosted inside the Activity, it's enough to manage options menu from there. So:
Delete all instances of onCreateOptionsMenu() and onOptionsItemSelected() from your fragment;
Delete all instances of setHasOptionsMenu(true) you previously added;
In your Activity, just keep:
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
Note that in your code #Override is missing here and there.
That said, why are onCreateOptionsMenu() and onOptionsItemSelected() methods also available for fragments? Because if you have multiple fragments that can be shown in the same Activity, you might want to have each fragment add some items to the Activity OptionsMenu.
That is done with setHasOptionsMenu(true) and there are a lot of questions already answered here on the topic. But, as per what you said, that's not your case. You just want an Activity menu, so forget about the fragment.
The menu disappearing was you calling menu.clear().
Got it figured out.
I removed
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setActionBar(ab);
from the loadPreviewFragment()
Then removed the Toolbar view from my activity_wallpaper.xml layout
And changed the parent theme in my style.xml from
parent=Theme.Material.NoActionBar
to
parent=Theme.Material
Thanks for the help guys.

Categories

Resources