I have created an app which shows multiple webpages. I want that app to share image which is displayed on that webpage with whatsapp and other IM messengers, for that i have added a context menu and have implemented ACTION_SEND but it didn't work. When i try to share image it gives me error "sharing failed please try again" Here is my code
public class TopRatedFragment extends Fragment {
private ProgressBar progress;
private WebView myWebView2;
private Menu optionsMenu;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
String url = "http://images.google.com";
myWebView2 = (WebView) rootView.findViewById(R.id.webViewTop);
myWebView2.setWebChromeClient(new myWebViewClient());
myWebView2.getSettings().setJavaScriptEnabled(true);
progress = (ProgressBar) rootView.findViewById(R.id.progressBar3);
progress.setMax(100);
setHasOptionsMenu(true);
myWebView2.loadUrl(url);
myWebView2.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView View, String url) {
View.loadUrl(url);
TopRatedFragment.this.progress.setProgress(0);
return true;
}
});
myWebView2.setOnKeyListener(new android.view.View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
optionsMenu = menu;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.airport_menuRefresh:
TopRatedFragment.this.myWebView2.reload();
setRefreshActionButtonState(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, "Call");
menu.add(0, v.getId(), 0, "share image");
}
#Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="Call"){
Toast.makeText(getActivity(), "calling code", Toast.LENGTH_LONG).show();
}
else if(item.getTitle()=="share image")
{
// This is the code which i am using for share intent
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageState()));
startActivity(Intent.createChooser(share, "Share image using"));
}else{
return false;
}
return true;
}
Thanks for your help!
This line looks strange
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageState()));
The stream extra is supposed to contain the uri to the image you want to share, but you are setting it to something I don't even understand what it's supposed to do - that wouldn't even evaluate to a uri.
Currently you are not supplying the intent with any information on WHAT content you want to send. Set the stream extra to the image location uri and you should be fine.
(Btw you really should compare strings using equals() rather than ==. And you shouldn't identify menu item on titles as it would fail when localized etc. Use the menu item id.)
Related
This is my first try with Bottom Sheets.
I have a menu button in Toolbar that shows Bottom Sheets with 3 item, one of them is Switch widget that can change theme to Dark Mode. When app starts it checkes is the Dark Mode on or off.
Bottom Sheet layout
When I try to set value onCreate Method in Switch I'm getting an error:
Attempt to invoke virtual method 'void androidx.appcompat.widget.SwitchCompat.setChecked(boolean)' on a null object reference
I understand the error that Switch Widget is initialized in Bottom Sheet layout not Main and appears only when user clicks the button in Toolbar but what can I change in code?
MainActivity on Create
switchCompat = findViewById(R.id.switchMode);
sharedPreferences = getSharedPreferences("night",0);
Boolean booleanValue = sharedPreferences.getBoolean("night_mode", true);
if (booleanValue){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("night_mode", true);
editor.commit();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
switchCompat.setChecked(false);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("night_mode", false);
editor.commit();
}
}
});
Methods after onCreate:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_lang, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_more_action) {
showBottomSheetDialog();
}
return super.onOptionsItemSelected(item);
}
public void showBottomSheetDialog() {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
bottomSheetDialog.setContentView(R.layout.bottom_sheet);
LinearLayout lang = bottomSheetDialog.findViewById(R.id.languageBottom);
LinearLayout about = bottomSheetDialog.findViewById(R.id.aboutBottom);
LinearLayout darkMode = bottomSheetDialog.findViewById(R.id.darkModeBottom);
lang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showChangeLanguageDialog();
bottomSheetDialog.dismiss();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openAboutAppActivity();
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.show();
}
I am trying to implement a search Filter in my Fragment, but it does not let me. I used the same code in Activity before and it worked. Whenever I type something, the onCreateOptionsMenu() does not get called. The App looks like this : [![app Picture][1]][1]
As you can see I type something in the top and it won't get filtered.
My Fragment code: `
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setMenuVisibility(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.fragment_tab1, container, false);
if(getArguments() != null){
String yourText = getArguments().getString("interessen");
System.out.println(yourText);
}`
.
.
.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menuevents, menu);
super.onCreateOptionsMenu(menu, inflater);
MenuItem searchitem = menu.findItem(R.id.searchEvent);
//searchitem.setVisible(false);
final SearchView searchView = (SearchView) searchitem.getActionView();
final List<Event> allEvents = new ArrayList<>();
allEvents.addAll(eventList);
searchitem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
eventList.clear();
eventList.addAll(allEvents);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
eventList.clear();
eventList.addAll(allEvents);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
eventListAdapter.getFilter().filter(newText);
return false;
}
});
I did not copy the EventListAdapter in, becuase this should work just fine. Its just that the Fragment does not get Access to the SearchItem.
Anybody? :)
[1]: https://i.stack.imgur.com/JkLcL.png
You've called setMenuVisibility(), which means your Fragment is specifically opting out of having its menu being shown. It is expected that when your menu isn't shown, onCreateOptionsMenu() is not triggered.
Remove that line of code to have your menu actually be visible.
I've been working on the Android SDK platform, and it is a bit unclear how to save an application's state. I'm creating a menu which has CheckBoxes. I do get the idea of SharedPreferences but I'm not able to get my head around the implementation of SharedPreferences in CheckBoxes.
I want those checkboxes (multiple checkboxes) stay checked/unchecked even if the user relaunches the app.
public class MainActivity extends AppCompatActivity {
protected WebView myWebView;
protected TextView text_selection;
protected TextView mOutputText;
public static final String TAG = "mytag";
protected SharedPreferences sharedPreferences;
protected SharedPreferences.Editor editor;
private final String PREFERENCE_FILE_KEY = "myAppPreference";
private Context context;
protected CheckBox animal, fisheries, dairy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
//sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
//Context context = getActivity();
//SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("animal", false);
editor.putBoolean("fisheries", false);
editor.putBoolean("dairy", false);
//editor.putBoolean("checkbox", checkbox.isChecked()));
editor.commit();
this.myWebView = (WebView) findViewById(R.id.webview);
this.text_selection = findViewById(R.id.text_selected);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("------");
//mOutputText = (TextView) findViewById(R.id.tv_output);
mOutputText = findViewById(R.id.textView);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(task.isSuccessful()){
String token=task.getResult().getToken();
Log.d(TAG, "onComplete: Token: "+token);
mOutputText.setText("Token has been generated");
}else{
mOutputText.setText("Token failed");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
if (sharedPreferences.getBoolean("animal", false)) {
// findItem id function return the id of the menu
menu.findItem(R.id.animal).setChecked(true);
} else if (sharedPreferences.getBoolean("fisheries", false)) {
menu.findItem(R.id.fisheries).setChecked(true);
} else if (sharedPreferences.getBoolean("dairy", false)) {
menu.findItem(R.id.dairy).setChecked(true);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("animal", false);
} else {
item.setChecked(true);
editor.putBoolean("animal", true);
}
break;
case R.id.fisheries:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("fisheries", false);
} else {
item.setChecked(true);
editor.putBoolean("fisheries", true);
}
break;
case R.id.dairy:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("dairy", false);
} else {
item.setChecked(true);
editor.putBoolean("dairy", true);
}
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
}
Below example;
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
editor.putBoolean("dairy", isChecked);
editor.commit();
}
});
Replace the beginning stuff in your onCreate with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
animal.setChecked(getCheckboxStatus("animal"));
animal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("animal", isChecked);
}
}
);
fisheries.setChecked(getCheckboxStatus("fisheries"));
fisheries.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("fisheries", isChecked);
}
}
);
dairy.setChecked(getCheckboxStatus("dairy"));
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("dairy", isChecked);
}
}
);
// Your WebView and Firebase stuff
}
private void saveCheckBoxValue(String key, boolean isChecked) {
editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean getCheckboxStatus(String key) {
return sharedPreferences.getBoolean(key, false);
}
Change the onCreateOptionsMenu function to the following:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.animal).setChecked(sharedPreferences.getBoolean("animal", false));
menu.findItem(R.id.fisheries).setChecked(sharedPreferences.getBoolean("fisheries", false));
menu.findItem(R.id.dairy).setChecked(sharedPreferences.getBoolean("dairy", false));
return true;
}
Change the onOptionsItemSelected function to:
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
editor.putBoolean("animal", item.isChecked());
break;
case R.id.fisheries:
editor.putBoolean("fisheries", item.isChecked());
break;
case R.id.dairy:
editor.putBoolean("dairy", item.isChecked());
break;
}
editor.apply();
return super.onOptionsItemSelected(item);
}
//set the Volume switch to ON
swVolume.setChecked(true);
//attach a listener to check for the changes in state
swVolume.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
//check the current state before we display the screen
if(swVolume.isChecked()){
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(
AudioManager.STREAM_RING,
am.getStreamMaxVolume(AudioManager.STREAM_RING),
0);
}
else {
swVolume.setChecked(false);
}
Can someone tell me why can't I add the if else code into the listener?
and is the listener function just to view the switch status?
I saw one example on the internet:
public class MainActivity extends Activity {
private TextView switchStatus;
private Switch mySwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchStatus = (TextView) findViewById(R.id.switchStatus);
mySwitch = (Switch) findViewById(R.id.mySwitch);
//set the switch to ON
mySwitch.setChecked(true);
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
but I don't really know why do I need to type the if-else statement twice, cause even if I remove the if-else statement here the code is still working fine.
Can someone explain to me?
if(isChecked){
switchStatus.setText("Switch is currently ON");
}else{
switchStatus.setText("Switch is currently OFF");
}
}
});
//check the current state before we display the screen
if(mySwitch.isChecked()){
switchStatus.setText("Switch is currently ON");
}
else {
switchStatus.setText("Switch is currently OFF");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Thank you so much. :)
Simple code:
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private int a;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
final WebSettings webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
webviewtwoSettings.setTextSize(TextSize.NORMAL);
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Now My problem. After i press back button onStop() code is executed and onDestroy. How i can don't kill app ? I wanna this app in background. Now when i press back button and open app, all data is again downloaded and loaded to webview. Soo how make this process work in background ?
Sorry for my haotic english :)
Sierran
Use Android service for doing something in Background rather then Activity.
And use Broadcast receiver to invoke your Activity from service. When something your background work finished.
Android - Service
And if you want to do some little then just override onKeyDown()
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
return true;
}
return super.onKeyDown(keyCode, event);
}
I would recommend using a Service if you want to do something in the background and need it to be running more or less all the time. Check out the Service documentation here:
http://developer.android.com/reference/android/app/Service.html
An alternative in your case would be to create local caches of the websites.