How to Swipe Refreshing Layout In Recyclerview Like (YouTube) - javascript

How To Refresh RecyclerView List Like YouTube By Swiping Refresh layout
activity_main.xml:-
This Is My Main Activity java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ImagesActivity">
<ProgressBar
android:id="#+id/progress_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/Swipe_Refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
MainActivity.java
And This Is My MainActivity.Java+
please tell me the code
public class ImagesActivity extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<Upload> mUploads;
private SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mySwipeRefreshLayout = findViewById(R.id.Swipe_Refresh);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
}
}
);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(ImagesActivity.this);
mStorage = FirebaseStorage.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onWhatEverClick(int position) {
Toast.makeText(this, "Whatever click at position: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
Toast.makeText(ImagesActivity.this, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mDatabaseRef.removeEventListener(mDBListener);
}
}
ImageAdapter.java
This Is My Image Adapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
**Upload.java**
This My Upload Class
package com.codinginflow.firebaseuploadexample;
import com.google.firebase.database.Exclude;
public class Upload {
private String mName;
private String mImageUrl;
private String mKey;
public Upload() {
//empty constructor needed
}
public Upload(String name, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
mName = name;
mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
#Exclude
public String getKey() {
return mKey;
}
#Exclude
public void setKey(String key) {
mKey = key;
}
}

Related

Intent to Navigation Drawer Activity not working

I have been trying to add a Navigation Drawer Activity to my code, I followed an old tutorial that upon creation didn't create fragments, but I tried to make ti work none the less, I think I did everything right but when opening then emulator, the app doesn't take me to the activity but to the launcher one(?), is it the emulator or is it the code?
Navigation Drawer:
public class NavigationDrawerActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Options");
setSupportActionBar(toolbar);
//Init. Firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//Set name for User
View HeaderView = navigationView.getHeaderView(0);
txtFullName = findViewById(R.id.txtFullName);
if (Common.currentUser != null) {
txtFullName.setText(Common.currentUser.getName());
finish();
} else if (Common.CurrentFirebaseUser != null) {
txtFullName.setText(Common.CurrentFirebaseUser.getDisplayName());
finish();
}
//Load Options
recyclerView = findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadFilter();
}
private void loadFilter() {
FirebaseRecyclerAdapter<Category,FilterViewHolder> adapter = new FirebaseRecyclerAdapter<Category, FilterViewHolder>(Category.class, R.layout.filter_item, FilterViewHolder.class, category) {
#Override
protected void populateViewHolder(FilterViewHolder filterViewHolder, Category category, int i) {
FilterViewHolder.txtFilterName.setText(category.getName());
Picasso.with(getBaseContext()).load(category.getImage())
.into(filterViewHolder.imageView);
Category clickItem = category;
filterViewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(NavigationDrawerActivity.this, ""+ clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
SignIn leading to the Navigation Drawer (ignore the login logic):
public class SignIn extends AppCompatActivity {
private static final int RC_SIGN_IN = 1;
Button btnSignIn;
ImageView btnGoogle;
EditText edtTxtPhone, edtTxtPassword;
private static final String TAG = "SignIn";
private FirebaseAuth mAuth;
private boolean noError = false;
private GoogleSignInClient mGoogleSignInClient;
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(SignIn.this, NavigationDrawerActivity.class);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
btnSignIn = findViewById(R.id.btnSignIn);
btnGoogle = findViewById(R.id.btnGoogle);
edtTxtPhone = findViewById(R.id.edtTxtPhone);
edtTxtPassword = findViewById(R.id.edtTxtPassword);
//Initialize Firebase
FirebaseDatabase database = FirebaseDatabase.getInstance("https://app-delivery-tutorial-default-rtdb.europe-west1.firebasedatabase.app");
DatabaseReference table_user = database.getReference("User");
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkCredentials();
ProgressDialog mDialog = new ProgressDialog(SignIn.this);
mDialog.setMessage("Signin In...");
mDialog.show();
if (noError) {
table_user.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
mDialog.dismiss();
//Check If User Does Exist First
if (snapshot.child(edtTxtPhone.getText().toString()).exists()) {
//Get User Information
User user = snapshot.child(edtTxtPhone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(edtTxtPassword.getText().toString())) {
Intent successfulLogIn = new Intent(SignIn.this, NavigationDrawerActivity.class);
Common.currentUser = user;
startActivity(successfulLogIn);
} else {
Toast.makeText(SignIn.this, "Sign In Failed", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(SignIn.this, "User Not Found, Please Register First", Toast.LENGTH_SHORT).show();
Log.w(TAG, "Failed to read value.");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(SignIn.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
});
} else {
mDialog.dismiss();
Toast.makeText(SignIn.this, "Wrong Phone Number Or Password Input", Toast.LENGTH_SHORT).show();
}
}
});
//Initialize Google Firebase
mAuth = FirebaseAuth.getInstance();
createRequestGoogle();
btnGoogle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SignInGoogle();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
Toast.makeText(this, "Activity Has Been Succesful", Toast.LENGTH_SHORT).show();
} catch (ApiException e) {
Log.w(TAG, "Google Sign In Failed", e);
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(SignIn.this, NavigationDrawerActivity.class);
Common.CurrentFirebaseUser = user;
startActivity(intent);
}
}
});
}
private void SignInGoogle() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void createRequestGoogle() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void checkCredentials() {
String username = edtTxtPhone.getText().toString();
String password = edtTxtPassword.getText().toString();
if (username.isEmpty() || username.length() < 9) {
showError(edtTxtPhone, "Your Phone Number must have at least 9 character");
} else if (password.isEmpty() || password.length() < 4) {
showError(edtTxtPassword, "Your password must have at least 4 character");
} else {
noError = true;
}
}
private void showError(EditText editText, String s) {
editText.setError(s);
editText.requestFocus();
}
}
I tried to see if the fragments created were the problem, if the NavigationDrawerActivity should use an other xml file or if I was missing some logic, but I still don't understand why it would take me to the Launcher Activity instead of the NavigationDrawer one, the SignIn logic does work with other activities other than the NavigationDrawer one

How do you set Android PrintManager to automatically print 2 copies?

I created a function that prints documents but the printer screen on the Android device is always set to just 1 copy and I would like to set it to print 2 copies.
mainWebView.addJavascriptInterface(new javaScriptInterface(this), "AndroidApp");
public class javaScriptInterface {
public javaScriptInterface(Context context) {
}
#JavascriptInterface
public void print(final String data) {
runOnUiThread(new Runnable() {
#Override
public void run() {
printTheView(data);
}
});
}
}
private void printTheView(String printData) {
printWebView = new WebView(this);
printWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
createWebPagePrint(view);
super.onPageFinished(view, url);
}
});
printWebView.loadDataWithBaseURL(null, printData, "text/plain", "UTF-8", null);
}
public void createWebPagePrint(WebView webView) {
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter("Proof Of Delivery");
String jobName = "Proof Of Delivery";
PrintAttributes.Builder builder = new PrintAttributes.Builder();
builder.setMediaSize(PrintAttributes.MediaSize.NA_LETTER);
PrintJob printJob = printManager.print(jobName, printAdapter, builder.build());
}

How to connect Menu Item to a class?

menuItem E-K
i have this MenuItem E-K above and want to set a click on it to connect to a fragment named"DB"( and this DB is a resetDatasource of another fragment named "Dictonary Fragment Java class) but i can't.
Here's my code
1-Dictionary Fragment:
public class DictionaryFragment extends Fragment {
private FragmentListener listener;
ArrayAdapter<String> adapter;
ListView dictList;
public DictionaryFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dictionary, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dictList = view.findViewById(R.id.dictionaryList);
adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, getListOfWords());
dictList.setAdapter(adapter);
dictList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (listener != null)
listener.onItemClick(getListOfWords()[position]);
}
});
}
public void resetDataSource(String[] source) {
adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, source);
dictList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void filterValue(String value) {
// adapter.getFilter().filter(value);
int size = adapter.getCount();
for (int i = 0; i < size; i++) {
if (adapter.getItem(i).startsWith(value)) {
dictList.setSelection(i);
break;
}
}
}
String[] getListOfWords() {
String[] source = new String[]{
"a"
, "a, an"
, "aback"
, "abacus"
, "abaft"
, "abalone"
, "abandon"
, "abandoned"
, "abandonment"
, "abandoning"
, "abase"
, "abasement"
, "abash"
, "abashed"
, "abate"
, "abatement"
, "abattoir"
, "abbess"
, "abbey"
, "abbot"
, "abbrev"
, "abbreviate"
, "abbreviated"
, "abbreviation"
};
return source;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void setOnFragmentListener(FragmentListener listener) {
this.listener = listener;
}
}
2-DB :
public class DB {
public static String[] getData(int id) {
if (id == R.id.action_eng_kh) {
return getEngKh();
}
return new String[0];
}
private static String[] getEngKh() {
String[] source = new String[]{
"a"
, "a, an"
, "aback"
, "abacus"
, "abaft"
, "abalone"
, "abandon"
, "abandoned"
, "abandonment"
, "abandoning"
, "abase"
, "abasement"
, "abash"
, "abashed"
, "abate"
, "abatement"
, "abattoir"
, "abbess"
, "abbey"
, "abbot"
, "abbrev"
, "abbreviate"
, "abbreviated"
, "abbreviation"
};
return source;
}
}
3-In MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
MenuItem menuSetting;
DictionaryFragment dictionaryFragment;
BookmarkFragment bookmarkFragment;
DetailFragment detailFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
dictionaryFragment = new DictionaryFragment();
bookmarkFragment = new BookmarkFragment();
goToFragment(dictionaryFragment, true);
dictionaryFragment.setOnFragmentListener(new FragmentListener() {
#Override
public void onItemClick(String value) {
goToFragment(DetailFragment.getNewInstance(value), false);
}
});
bookmarkFragment.setOnFragmentListener(new FragmentListener() {
#Override
public void onItemClick(String value) {
goToFragment(DetailFragment.getNewInstance(value), false);
}
});
EditText edit_search = findViewById(R.id.edit_search);
edit_search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
dictionaryFragment.filterValue(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menuSetting = menu.findItem(R.id.action_settings);
String id = Global.getState(this, "dic_type");
if(id!= null)
onOptionsItemSelected(menu.findItem(Integer.valueOf(id)));
else
dictionaryFragment.resetDataSource(DB.getData(R.id.action_eng_kh));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Global.saveState(this, "dic_type", String.valueOf(id));
if (id == R.id.action_eng_kh) {
dictionaryFragment.resetDataSource(DB.getData(id));
menuSetting.setIcon(getDrawable(R.drawable.ic_ek));
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_bookmark) {
goToFragment(bookmarkFragment, false);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
void goToFragment(Fragment fragment, boolean isTop){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
if(!isTop)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
4- main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:icon="#drawable/ic_seldic"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="always">
<menu>
<item
android:id="#+id/action_eng_kh"
android:icon="#drawable/ic_ek"
android:orderInCategory="100"
android:title="English-Khmer"
app:showAsAction="never" />
</menu>
</item>
please help me because I'm new to code and i need help from you all in Stackoverflow
thanks

How to detect and close JavaScript dialog close button to dismisss the popup android

I am using webview to display the url. It displays the popup with scrolling map with close button.
https://www.onemap.sg/main/v2/ [this displays only in mobile]
When I click close button, it's not working. Dialog is not closing.
Moreover at the backside, map is not displaying in webview. You can see the screenshot
My code is as follows:
I couldn't guess what should be added to close the dialog. Kindly help me to resolve.
public class WebViewActivity extends AppCompatActivity {
private ImageView backIcon;
private ImageView homeIcon;
private DownloadManager dm;
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (MainActivity.this.downloadReference == intent.getLongExtra("extra_download_id", -1)) {
Query q = new Query();
q.setFilterById(new long[]{intent.getLongExtra("extra_download_id", -1)});
Cursor c = MainActivity.this.dm.query(q);
if (c.moveToFirst() && c.getInt(c.getColumnIndex("status")) == 8) {
String title = c.getString(c.getColumnIndex("title"));
File file = new File(Environment.getExternalStorageDirectory() + "/Download/" + title);
if (!file.isDirectory()) {
file.mkdir();
}
Intent testIntent = new Intent("android.intent.action.VIEW");
testIntent.setType("application/pdf");
testIntent.setDataAndType(Uri.fromFile(file), "application/pdf");
try {
MainActivity.this.startActivity(testIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, "No application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
}
}
};
private long downloadReference;
private String location;
private WebView mWebview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_main);
// Toolbar mToolbar = (Toolbar) findViewById(R.id.tool_bar);
// setSupportActionBar(mToolbar);
this.mWebview = (WebView) findViewById(R.id.webview);
this.mWebview.getSettings().setJavaScriptEnabled(true);
this.mWebview.getSettings().setLoadWithOverviewMode(true);
this.mWebview.getSettings().setUseWideViewPort(true);
this.mWebview.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
if(0 != (getApplicationInfo().flags = ApplicationInfo.FLAG_DEBUGGABLE)){
WebView.setWebContentsDebuggingEnabled(true);
}
}
loadWebView();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebview.canGoBack()) {
mWebview.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
if (mWebview.canGoBack()) {
mWebview.goBack();
} else {
finish();
}
}
private void loadWebView() {
this.mWebview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.e("urlss",url);
return super.onJsAlert(view, url, message, result);
}
});
this.mWebview.setWebViewClient(new WebViewClient() {
final ProgressDialog pd = ProgressDialog.show(MainActivity.this, "", "Loading...Please wait!", true);
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
this.pd.show();
}
public void onPageFinished(WebView view, String url) {
Log.e("url",url);
this.pd.dismiss();
MainActivity.this.mWebview.loadUrl("https://www.sla.gov.sg/INLIS/");
}
//code for feedback//
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle it
else if (url.startsWith("tel:")) {
Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(tel);
return true;
}
Log.d("Main URL ", url);
return false;
}
});
this.mWebview.loadUrl("https://www.sla.gov.sg/inlis/#/");
this.mWebview.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Request request = new Request(Uri.parse(url));
request.setMimeType("pdf");
request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url));
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, "pdf"));
request.allowScanningByMediaScanner();
if (VERSION.SDK_INT >= 11) {
request.setNotificationVisibility(0);
} else {
request.setShowRunningNotification(true);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, "pdf"));
MainActivity.this.dm = (DownloadManager) MainActivity.this.getSystemService(DOWNLOAD_SERVICE);
MainActivity.this.downloadReference = MainActivity.this.dm.enqueue(request);
MainActivity.this.registerReceiver(MainActivity.this.downloadReceiver, new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE"));
}
});
}
}

Javascript Script Engine

I'm trying to get this script engine to work but I keep getting a NullPointerException. I look at the line where it is thrown (my return line toward the very end of my code), but I can't seem to solve my problem. Do anyone have experience with javascript engines that could help?
package com.example.lab2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
/**
* #author jamiekujawa
*
*/
public class MainActivity extends Activity {
/**
* A string builder to represent the first number entered in the series of entries
*/
private String expression1;
/**
* A string builder to represent the second number entered in the series of entries
*
private StringBuilder expression2;*/
/**
* A string to represent the last operator performed
*
private String oldOperator;*/
private String foo = "";
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// declare all buttons used within the layout
Button zero = (Button) findViewById(R.id.button0);
Button one = (Button) findViewById(R.id.button1);
Button two = (Button) findViewById(R.id.button2);
Button three = (Button) findViewById(R.id.button3);
Button four = (Button) findViewById(R.id.button4);
Button five = (Button) findViewById(R.id.button5);
Button six = (Button) findViewById(R.id.button6);
Button seven = (Button) findViewById(R.id.button7);
Button eight = (Button) findViewById(R.id.button8);
Button nine = (Button) findViewById(R.id.button9);
Button times = (Button) findViewById(R.id.buttontimes);
Button clear = (Button) findViewById(R.id.buttonClear);
Button equal = (Button) findViewById(R.id.buttonEqual);
Button decimal = (Button) findViewById(R.id.buttonDecimal);
Button divide = (Button) findViewById(R.id.buttondivide);
Button add = (Button) findViewById(R.id.buttonplus);
Button subtract = (Button) findViewById(R.id.buttonminus);
// declare main text view
final TextView main = (TextView) findViewById(R.id.CalculatorText);
// Main Strings to represent the expressions
expression1 = new String();
//expression2 = new StringBuilder();
main.setText(expression1.concat("0.0"));
/*
* Set up all key listener events
*/
zero.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(expression1.toString().equals("0.0")) {
expression1 = new String("0");
main.setText(expression1);
}else {
expression1.concat("0");
main.setText(expression1);
}
}
});
one.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("1");
main.setText(expression1);
}else {
expression1.concat("1");
main.setText(expression1);
}
}
});
two.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("2");
main.setText(expression1);
}else {
expression1.concat("2");
main.setText(expression1);
}
}
});
three.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("3");
main.setText(expression1);
}else {
expression1.concat("3");
main.setText(expression1);
}
}
});
four.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("4");
main.setText(expression1);
}else {
expression1.concat("4");
main.setText(expression1);
}
}
});
five.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("5");
main.setText(expression1);
}else {
expression1.concat("5");
main.setText(expression1);
}
}
});
six.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("6");
main.setText(expression1);
}else {
expression1.concat("6");
main.setText(expression1);
}
}
});
seven.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("7");
main.setText(expression1);
}else {
expression1.concat("7");
main.setText(expression1);
}
}
});
eight.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("8");
main.setText(expression1);
}else {
expression1.concat("8");
main.setText(expression1);
}
}
});
nine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expression1.toString().equals("0.0")) {
expression1 = new String("9");
main.setText(expression1);
}else {
expression1.concat("9");
main.setText(expression1);
}
}
});
times.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
expression1.concat("*");
main.setText(expression1);
}
});
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.setText("0.0");
expression1 = new String("0.0");
//expression2 = new StringBuilder();
}
});
equal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(foo);
if(expression1.equals("")){
main.setText("0.0");
}else {
try {
main.setText(evaluate(expression1));
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
});
decimal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
expression1.concat(".");
main.setText(expression1);
}
});
divide.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
expression1.concat("/");
main.setText(expression1);
}
});
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
expression1.concat("+");
main.setText(expression1);
}
});
subtract.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
expression1.concat("-");
main.setText(expression1);
}
});
}
/**
* This method will evaluate an operation using expression1 and javaScriptEngineManager
*
* #param buttonPressed or operation to be performed
* #return the result of the operation
*/
public String evaluate(String buttonPressed) throws ScriptException{
//System.out.println(foo);
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
foo = engine.eval(expression1).toString();
return foo;
}
}

Categories

Resources