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

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);
}
}

Related

Why is the menu I created not working with a new Intent

I am new to android development.
I created a MenuItem to start a new activity (SettingsActivity) when clicked. I have no errors and everything is working fine except that when I click the created menu, it does not do anything.
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.visualizer_menu, menu);
return true;
}
public boolean onOptionSelected(MenuItem item){
int itemThatWasClicked = item.getItemId();
if (itemThatWasClicked == R.id.action_settings){
Intent settingsActivityIntent = new Intent(this, SettingsActivity.class);// using explicity intent to open new activity
startActivity(settingsActivityIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
I have tried adding a Toast in onOptionSelected(), it didn't work. the menu is not just responding
I have the following code in my SettingsActivity.java for now
package android.example.com.visualizerpreferences;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
ActionBar actionBar = this.getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}
Below is my visualizer_menu.xml in my menu resource file
<?xml version="1.0" encoding="utf-8"?>
<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:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never"/>
</menu>
replace your
public boolean onOptionSelected(MenuItem item){
to
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
Menu item create :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
Click listeners :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

launching Activity only once(First app use) Using Boolean flags

So i got my firstScreen that i want to be shown just on the first app use.
and i have my mainActivity which will follow the firstScreen.
Im only starting with android and i don't want to use the solutions brought in here: How to launch activity only once when app is opened for first time? AND Can I have an android activity run only on the first time an application is opened? because i dont know SharedPreferrences yet.
So how can i achieve that using Boolean flags?
I have got:boolean firstTimeUse = false; In my firstScreenActivity
And when i start myMainActivity i set the flag to true;
firstTimeUse = true;
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
The problem is the MainActivity doesn't recognize the Boolean variable.
Am i doing it wrong? Or i can still make some modifications and do it with flags?
EDIT
FirstScreen.java:
package com.example.predesignedmails;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class FirstScreen extends AppCompatActivity
{
TextView welcomeTextTextView;
String welcomeText;
ImageButton goToMainImageButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_screen);
viewsInitialization();
welcomeText = "Welcome to Pre Designed Mails.\n"
+ "In here you will have a tons of Emails templates for about every purpose you will need.\n"
+ "Just fill the small details and click Send.\n\n"
+ "Send E-mails fast and efficient!";
welcomeTextTextView.setText(welcomeText);
welcomeTextTextView.setMovementMethod(new ScrollingMovementMethod());
goToMainImageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_screen, 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);
}
#Override
protected void onResume()
{
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true))
{
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
// First launch code
Log.d("FirstLaunchCheckUp","First Launch");
}
}
private void viewsInitialization()
{
welcomeTextTextView = (TextView) findViewById(R.id.welcome_text_text_view_id);
goToMainImageButton = (ImageButton) findViewById(R.id.go_to_main_button_id);
}
}
The onResume() method i added manually. It wasn't added automatically when i crated a new activity in Eclipse.
MainActivity.java:
package com.example.predesignedmails;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
Button hatefullMailButton;
Button loveMailsButton;
Button welcomeScreenButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color)); // Setting background color
viewsInitialization();
hatefullMailButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,HatefulMailsActivity.class);
startActivity(intent);
}
});
loveMailsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,LoveMailsActivity.class);
startActivity(intent);
}
});
welcomeScreenButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,FirstScreen.class);
startActivity(intent);
}
});
}
#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);
}
private void viewsInitialization()
{
hatefullMailButton = (Button) findViewById(R.id.hateful_email_button_id);
loveMailsButton = (Button) findViewById(R.id.love_email_button_id);
welcomeScreenButton = (Button) findViewById(R.id.welcome_screen_button_id);
}
}
In your Activity
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true)){
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
//your first launch code
}
}
SharedPreference helper class
public class SettingsManager
{
public static final String FIRST_LAUNCH= "first_lauch";
public static String getString(Context context, String key, String defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defValue);
}
public static int getInt(Context context, String key, int defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defValue);
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defValue);
}
public static void saveString(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public static void saveInt(Context context, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
}
public static void saveBoolean(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
}
}
For the future you can write more simple methods on this SettingsManager, like
public static int getFirstLaunch(Context context) {
return getBoolean(context, FIRST_LAUNCH, true);
}
public static int saveFirstLaunch(Context context, boolean value) {
return saveBoolean(context, FIRST_LAUNCH, value);
}
And use it like
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getFirstLaunch(this)){
SettingsManager.saveFirstLaunch(this, false);
//your first launch code
}
}
The reason why firstScreen does not recognize boolean firstTimeUse in mainActivity is because it does not yet exist. Only after you have executed the line startActivity(intent) will there exist an object of class mainActivity. Basically, you cannot set a boolean on something that does not yet exist.
Instead, what you can do is pass extra information to an activity that is to be started. When the just-started-activity is initializing itself it can read the extra information and act on it.
So build your intent for the activity you want to start and also set extra information in the 'extras':
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
intent.putExtra("firstTimeUse", true);
startActivity(intent);
Now for your MainActivity to know the value of firstTimeUse it must read the extras:
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstTimeUse = getIntent().getBooleanExtra("firstTimeUse", false);
// do processing dependent on whether it's the first time or not
}
}
This should solve your problem of "the MainActivity doesn't recognize the Boolean variable".

Android Share Menu

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;
}

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);
}
}

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