Android Share Menu - java

I have an app in which I have a WebView where I display some websites.
I want create a Share button in Menu.I've tried a lot of code.
What should I write here ?
private void action_shareMenuItem(){
//??????????????? What should I write here ?
}
MainActivity.java
package com.kefelon.goldplak;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends ActionBarActivity {
WebView webview;
private ShareActionProvider mShareActionProvider;
ProgressBar loadingProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.goldplak.com");
webview.setWebViewClient(new WebViewClient() {
});
loadingProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
webview.setWebChromeClient(new WebChromeClient() {
// this will be called on page loading progress
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
loadingProgressBar.setProgress(newProgress);
//loadingTitle.setProgress(newProgress);
// hide the progress bar if the loading is complete
if (newProgress == 100) {
loadingProgressBar.setVisibility(View.GONE);
} else{
loadingProgressBar.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onBackPressed()
{
if(webview.canGoBack()){
webview.goBack();
}else{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Çıkış")
.setMessage("Uygulamadan çıkmak istediğinize emin misiniz?")
.setPositiveButton("Evet", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("Hayır", null)
.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.action_about:
action_aboutMenuItem();
break;
case R.id.action_share:
action_shareMenuItem();
break;
case R.id.action_settings:
action_settingsMenuItem();
break;
}
return true;
}
private void action_aboutMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Hakkımızda")
.setMessage("Gold Plak olarak müzik sektörü ile ilgili müşteri odaklı kişisel ve kurumsal hizmet veren, dinamik, güler yüzlü, yaratıcı kadromuzla müşterilerimizin beklentilerini karşılamak için kesintisiz hizmet vermekteyiz.\n" +
"\n" +
"Bu şekilde müşterilerimizin plak ve dj ekipmanlarından yararlanmalarını sağlayarak taleplerini karşılayabilmek. Hedefimiz, yeni çıkan tüm ürünleri sunmak, maksimum düzeyde müşteri memnuniyetini sağlamak..")
.setNeutralButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
private void action_shareMenuItem(){
//??????????????? What should I write here ?
}
private void action_settingsMenuItem(){
new AlertDialog.Builder(this)
.setTitle("Versiyon")
.setMessage("Gold Plak v1.1")
.setNeutralButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}

You may need to create an xml file inside res>menu directory of your project for a share menu,
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/share"
android:icon="#drawable/ic_action_share" // share button icon.
android:showAsAction="always"
android:title="#string/action_share">
</item>
</menu>
In your java file,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.desc_xml, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.share) {
shareNews();
}
return super.onOptionsItemSelected(item);
}
and here is the share news method,
private void shareNews() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Put Data Here");
startActivity(Intent.createChooser(shareIntent,getString("How do you want to share")));
}

This question has already been answer but anyway, this is a working solution :
in your fragment/activity:
private ShareActionProvider mShareActionProvider;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.deal_detail, menu);
// Locate MenuItem with ShareActionProviderr
MenuItem item = menu.findItem(R.id.action_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
mShareActionProvider.setShareIntent(getShareIntent());
}
// Create the share intent
private Intent getShareIntent() {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "yoursubject");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "yourtext);
return sharingIntent;
}

Related

Hide a menu item when a specific URL is loaded in WebView

I have an activity with a basic WebView. In that, I have a menu item which launches a Share intent and allows users to share the URL that they were browsing at that point of time. I also have an error HTML page which is loaded when the WebView gets any HTTP error. So, basically, I want the Share menu item to be hidden (or at least share some other URL that I can set) when that error document is loaded.
Here's my MainActiviity.java:
package com.ananya.brokenhearts;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity
{
private WebView WebView;
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
private String currentURL;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = findViewById(R.id.webView);
ProgressBar = findViewById(R.id.progressBar);
LinearLayout = findViewById(R.id.layout);
ProgressBar.setMax(100);
WebView.loadUrl("https://www.brokenhearts.ml/index.html");
WebView.getSettings().setJavaScriptEnabled(true);
WebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
LinearLayout.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
LinearLayout.setVisibility(View.GONE);
super.onPageFinished(view, url);
currentURL = url;
}
public void onReceivedError(WebView webview, int i, String s, String s1)
{
WebView.loadUrl("file:///android_asset/error.html");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url2)
{
if (url2.contains("www.brokenhearts.ml"))
{
view.loadUrl(url2);
return false;
} else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url2));
startActivity(intent);
return true;
}
}
});
WebView.setWebChromeClient(new WebChromeClient()
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
ProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.backward:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
WebView.reload();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,currentURL);
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Copied URL");
startActivity(Intent.createChooser(shareIntent,"Share URL"));
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed()
{
if (WebView.canGoForward())
{
WebView.goForward();
} else
{
Toast.makeText(this, "Can't go further", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed ()
{
if (WebView.canGoBack())
{
WebView.goBack();
} else
{
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
Regarding hiding the share menu icon, you could always use onPrepareOptionsMenu() to hide your share menu if there is an error flag.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.share).setVisible(!isPageError);
return true;
}
which would require you to have a isPageError boolean set to true in your
#Override
public void onReceivedError(WebView webview, int i, String s, String s1{
isPageError = true;
}
I solved it using moving my error page to another activity. This is my new MainActiviy.java:
package com.ananya.brokenhearts;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity
{
private WebView WebView;
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
private String currentURL;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = findViewById(R.id.webView);
ProgressBar = findViewById(R.id.progressBar);
LinearLayout = findViewById(R.id.layout);
ProgressBar.setMax(100);
WebView.loadUrl("https://www.brokenhearts.ml/index.html");
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setUserAgentString("Broken Hearts/1.0");
WebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
LinearLayout.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
LinearLayout.setVisibility(View.GONE);
super.onPageFinished(view, url);
currentURL = url;
}
#Override
public void onReceivedError(WebView webview, int i, String s, String s1)
{
WebView.loadUrl("file:///android_asset/error.html");
Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url2)
{
if (url2.contains("www.brokenhearts.ml"))
{
view.loadUrl(url2);
return false;
} else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url2));
startActivity(intent);
return true;
}
}
});
WebView.setWebChromeClient(new WebChromeClient()
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
ProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.backward:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
WebView.reload();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,currentURL);
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Copied URL");
startActivity(Intent.createChooser(shareIntent,"Share URL"));
break;
case R.id.update:
Intent intent = new Intent(MainActivity.this, UpdateActivity.class);
startActivity(intent);
finish();
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed()
{
if (WebView.canGoForward())
{
WebView.goForward();
} else
{
Toast.makeText(this, "Can't go further", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed ()
{
if (WebView.canGoBack())
{
WebView.goBack();
} else
{
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
and ErrorActivity.java:
package com.ananya.brokenhearts;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
#SuppressWarnings("deprecation")
public class ErrorActivity extends AppCompatActivity
{
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_error);
android.webkit.WebView webView = findViewById(R.id.webView3);
ProgressBar = findViewById(R.id.progressBar3);
LinearLayout = findViewById(R.id.layout3);
ProgressBar.setMax(100);
webView.loadUrl("file:///android_asset/error.html");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUserAgentString("Broken Hearts/1.0");
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
LinearLayout.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
LinearLayout.setVisibility(View.GONE);
}
});
webView.setWebChromeClient(new WebChromeClient()
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
ProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu3, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.refresh:
Intent intent = new Intent(ErrorActivity.this, MainActivity.class);
startActivity(intent);
finish();
break;
case R.id.update:
Intent intent2 = new Intent(ErrorActivity.this, UpdateActivity.class);
startActivity(intent2);
finish();
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed ()
{
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}

I am a new to Java Android . And I wanna help to my project . I want to solve the errors which have say ( Cannot resolve symbol R and the others )

package com.example.abdoanany.sqliteapp;
import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editSurname,editMarks ,editTextId;
Button btnAddData;
Button btnviewAll;
Button btnDelete;
Button btnviewUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editSurname = (EditText)findViewById(R.id.editText_surname);
editMarks = (EditText)findViewById(R.id.editText_Marks);
editTextId = (EditText)findViewById(R.id.editText_id);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
btnviewUpdate= (Button)findViewById(R.id.button_update);
btnDelete= (Button)findViewById(R.id.button_delete);
AddData();
viewAll();
UpdateData();
DeleteData();
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
if(deletedRows > 0)
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Deleted", Toast.LENGTH_LONG).show();
}
}
);
}
public void UpdateData() {
btnviewUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
editName.getText().toString(),
editSurname.getText().toString(),editMarks.getText().toString());
if(isUpdate == true)
Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
}
}
);
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString(),
editSurname.getText().toString(),
editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Id :"+ res.getString(0)+"\n");
buffer.append("Name :"+ res.getString(1)+"\n");
buffer.append("Surname :"+ res.getString(2)+"\n");
buffer.append("Marks :"+ res.getString(3)+"\n\n");
}
// Show all data
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return `super.onOptionsItemSelected`(item);
}
}
If Project - Clean or/and Project - Rebuild would not help, most probable reason, that you somewhere made error in xml files.
In that case check all your xml, maybe you lost some resource or something.

How to create an android app that opens a website

I'm using eclipse. Just started with android web apps :) !
I want to create a web application that whenever it's open, it loads a website.
Nothing visual, no buttons.
This is the main blank code I have:
package com.example.yellowtest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here the sample code for web application
activity_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/google"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
Main class
public class MainActivity extends Activity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
webView = (WebView) findViewById(R.id.google);
startWebView("https://www.google.com/");
}
#SuppressLint("SetJavaScriptEnabled")
private void startWebView(String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
use this permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://google.com");
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Have alook at PhoneGap/Cordova, webaps with API
http://cordova.apache.org/
Use this below code. It contains webview client which is safest one.
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

How would i send text from an edit textbox to another app?

Hi im trying to develop and app which requires sending of text from one edit text box to another app such as Kik, i have already made the Share menu i just need to make it send the text from my edit text box
heres my share menu code (XML):
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_share"
android:title="Share"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:actionProviderClass= "android.widget.ShareActionProvider" />
</menu>
And heres my java:
package com.example.Encryptor_Kik;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
/**
* Created with IntelliJ IDEA.
* Date: 12/12/13
* Time: 3:15 PM
* To change this template use File | Settings | File Templates.
*/
public class Decryptor extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.decryption);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu2, menu);
MenuItem shareItem = menu.findItem(R.id.menu_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hi");
mShare.setShareIntent(shareIntent);
return super.onCreateOptionsMenu(menu);
}
}
The problem is that your code is in onCreateOptionsMenu and at the time of creating it your EditText is empty so the text is empty. You need to add a listener for change of text. Here is full code-
public class Decryptor extends Activity {
EditText e;
private ShareActionProvider mShare;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.decryption);
e=(EditText)findViewById(R.id.YourID);
e.addTextChangedListener(commonTextWatcher);
TextWatcher commonTextWatcher
= new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
String text=e.getText.toString();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
if (mShare != null) {
mShare.setShareIntent(shareIntent);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu2, menu);
MenuItem shareItem = menu.findItem(R.id.menu_share);
String text=e.getText.toString();
mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
mShare.setShareIntent(shareIntent);
return super.onCreateOptionsMenu(menu);
}
}

Back button unintentionally exiting app

Hopefully this hasn't been asked.
In building an app and having successfully opened a new activity from the main activity, when the back button is pressed the app exits instead of returning to the main activity.
Here is the code for the activity that gets called from the main one.
package com.austinrhodes.simplesounds;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
public class About extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the main activity
package com.austinrhodes.simplesounds;
import android.os.Bundle;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Launch extends Activity {
int size = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//inflate view from XML
setContentView(R.layout.activity_launch);
createTvArray();
}
private void createTvArray() {
//create array of text views to be added to main view
TextView[] tv = new TextView[size];
//create a temporary text view
TextView temp;
for (int i = 0; i < size; i++)
{
//make a new text view object for each of the alarms
temp = new TextView(this);
temp.setText("Alarm: " + i); //arbitrary task
//get instance of Linear Layout
LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.linearAlarm);
// add the textview to the linearlayout
myLinearLayout.addView(temp);
tv[i] = temp;
}
}
private void openSettings(){
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
finish();
}
private void openAbout(){
Intent intent = new Intent(this, About.class);
startActivity(intent);
finish();
}
#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_launch, menu);
return true;
}
public boolean onCreateOptionsMenu1(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_launch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
openSettings();
return true;
case R.id.new_alarm:
DialogFragment newFragment = new AddAlarm();
newFragment.show(getFragmentManager(), "add_alarm");
return true;
case R.id.about:
openAbout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
The concerned parties xml snippet
<activity android:name="com.austinrhodes.simplesounds.About" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.austinrhodes.simplesounds.Launch" />
</activity>
try this
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
CurrentClass.this.finish();
Intent i = new Intent(CurrentClass.this, MainActivity.class);
startActivity(i);
return true;
default:
return false;
}

Categories

Resources