My app has a 3-tabbed ActionBar layout. The 3 tabs are Dashboard, Feed and Messages.
When you click any of the three, the application is supposed to create a WebView of www.flyalaskava.org/incog/mobile/ which - if you do not have an active session for - will display an image and a "log-in with facebook" button.
The problem is, when I load the first tab (Dashboard) and cliek Log-In with Facebook, it logs me in - but as soon as I click onto another tab, I lose my session and am re-prompted.
Please keep in mind that currently all of these are using the same php file and that the log-in system works perfectly outside of Android. Sorry if this is a newbie question - any help is appreciated.
package com.example.testing;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import com.handmark.pulltorefresh.library.PullToRefreshWebView;
public class Main extends FragmentActivity implements ActionBar.TabListener {
PullToRefreshWebView mPullRefreshWebView;
WebView mWebView;
/**
* The serialization (saved instance state) Bundle key representing the
* current tab position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.pull_refresh_webview);
mWebView = mPullRefreshWebView.getRefreshableView();
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new SampleWebViewClient());
mWebView.loadUrl("http://www.google.com");
// Set up the action bar to show tabs.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText(R.string.title_section1)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section2)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section3)
.setTabListener(this));
}
private static class SampleWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM)
);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
displayAlert();
break;
case R.id.menu_exit:
displayExit();
break;
default:;
}
return(super.onOptionsItemSelected(item));
}
public void displayAlert() {
new AlertDialog.Builder(this)
.setMessage("This Application was created by Grant Adkins")
.setTitle("About")
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.cancel();
}
}
)
.show();
}
public void displayExit() {
new AlertDialog.Builder(this).setMessage("Exit the application")
.setTitle("Are you sure?")
.setCancelable(false)
.setNeutralButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.cancel();
}
}).setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
}
)
.show();
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
String summary = "<html><body>No Network Connection.</body></html>";
mWebView.loadData(summary, "text/html", null);
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the
// container view
int page = tab.getPosition() + 1;
if(page == 1) {
/// eventually is going to load index.php?content=dashboard
mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/");
isOnline();
} else if (page == 2) {
/// eventually is going to load index.php?content=messages
mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/");
isOnline();
} else if (page == 3) {
/// eventually is going to load index.php?content=feed
mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/");
isOnline();
} else {
mWebView.loadUrl("http://www.google.com");
isOnline();
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(
Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))
);
return textView;
}
}
}`
*\\\\\\\\UPDATE\\\\\\*
I found this article which seems to be a similar problem, maybe because im using mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/"); it is acting like a new browser, is there any way to change urls without using that method.
Here is a picture of the problem.
Add the following lines after having created your WebView :
CookieSyncManager.createInstance(mWebView.getContext()).sync();
CookieManager.getInstance().acceptCookie();
Consider using a Service instead of cookies. A Service will allow you to maintain a connection to your server in the background of your application. Services are easily referenced once created (read about Services and Intents). The Service would then act as your session to your server.
Related
So here is the link of the application:-Nearpeer-Offline messenger
So After integrating firebase, sometimes while i am restarting this application i got stuck at first activity (mainactivity), its hang and after 10-20 sec later, error comes "application not responding" and app closes.
I already ask question before here :- link
But didn't get good response response.
Here i am providing an MainActivity code:-
package com.nearpeer.app;
/**
*
* Wifi-Direct based multi-user chat application
*
*/
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.analytics.FirebaseAnalytics;
/**
* The app's main entry point. Holds 2 fragments: {#link ChatSearchScreenFrag} and {#link ChatHistoryScreenFrag}.
* The 1st fragment offers to scan for new chat groups and users. The 2nd offers to view chat history.
*/
public class MainScreenActivity extends FragmentActivity implements ActionBar.TabListener
{
private AlertDialog mDialog=null;
private OnClickListener AlertCheckBoxClickListener=null; //used to handle check-box click events for a dialog
SectionsPagerAdapter mSectionsPagerAdapter; //adapter for the tab view. Contains all the frags
ViewPager mViewPager; //a layout widget in which each child view is a separate page (a separate tab) in the layout.
//both fragment will initialize these references when they're created:
public ChatHistoryScreenFrag mHistoryFrag = null;
public ChatSearchScreenFrag mSearchFrag = null;
boolean isServiceStarted = false;
boolean wasWifiDialogShown = false;
static int mDisplayedFragIndex = 0;
public static long ChatRoomAccumulatingSerialNumber=0;
public static String UniqueID=null;
public static String UserName = ":>~"; //setting a default user name
static boolean isToNotifyOnNewMsg = false; //defines if notifications should be shown on arrival of new messages
static int RefreshPeriodInMs = 30000; //defines the peer refresh period
private boolean mIsRunForTheFirstTime=false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
//FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
/*Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
try {
InitializeTabHandlerAndAdapter();
if (!isServiceStarted && ChatSearchScreenFrag.mService == null) {
startService(new Intent(this, LocalService.class));
isServiceStarted = true;
}
getPrefs(); //get the shared prefs
//Happens only when the app is run for the very 1st time on a device
if (MainScreenActivity.UniqueID == null) {
UserName = new String(Secure.getString(getContentResolver(), Secure.ANDROID_ID)); //get a unique id
UniqueID = new String(UserName);
}//if
//Remove the title bar for out entire app
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
toast.show();
}
}//end of onCreate()
#Override
protected void onResume()
{
super.onResume();
//check if this activity was launched by the b-cast receiver after a wifi shutdown
try {
boolean isToDisplayWifiDialog = getIntent()
.getBooleanExtra(Constants.WIFI_BCAST_RCVR_WIFI_OFF_EVENT_INTENT_EXTRA_KEY, false);
if (isToDisplayWifiDialog && !wasWifiDialogShown) {
new EnableWifiDirectDialog().show(getSupportFragmentManager(), "MyDialog"); //show a dialog
wasWifiDialogShown = true;
}
//if this app is run for the very 1st time, we want to launch the settings activity first.
if (mIsRunForTheFirstTime) {
//launch the preferences activity
startActivity(new Intent(this, QuickPrefsActivity.class));
mIsRunForTheFirstTime = false;
}
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
toast.show();
}
}
#Override
protected void onPause()
{
super.onPause();
savePrefs(); //save the preferences
}//end of onPause()
private void InitializeTabHandlerAndAdapter()
{
// Set up the action bar (enable tab display).
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the two
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
#Override
//if a tab was changed by a swipe gesture
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position); //update the tab bar to match the selected page
mDisplayedFragIndex=position; //update the index of the currently displayed frag
if (position==1) //if the view has moved to the history fragment:
{
mHistoryFrag.loadHistory(); //reload the history list view
}
invalidateOptionsMenu();
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}//for
}//end of InitializeTabHandlerAndAdapter()
/**
* Used to modify menu item according to the app's state
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
//Check wifi state.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(mWifi.isConnected()||wifi.isWifiEnabled()) {
ChatSearchScreenFrag.mIsWifiDirectEnabled = true;
}
//if the wifi-direct is disabled, we want to disable the chat room creation option
menu.getItem(0).setEnabled(ChatSearchScreenFrag.mIsWifiDirectEnabled);
//if this menu is opened when the chat search is active:
if (mDisplayedFragIndex==0)
{
//hide the 'delete history option:
menu.findItem(R.id.action_delete_all_history).setVisible(false);
}
else //history frag is active:
{
//show the 'delete history option:
menu.findItem(R.id.action_delete_all_history).setVisible(true);
menu.findItem( R.id.clear_ignore_list).setVisible(false);
}
return true;
}
#SuppressLint("HandlerLeak")
Handler FirstTimeMenuUpdater = new Handler()
{
#Override
public void handleMessage(Message msg)
{
MainScreenActivity.this.invalidateOptionsMenu();
}
};
/**
* Called only once when the app starts
*/
#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_screen_menu, menu);
FirstTimeMenuUpdater.sendEmptyMessageDelayed(0, 500);
return true;
}//end of onCreateOptionsMenu()
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_settings://setting was clicked
{
startActivity(new Intent(this, QuickPrefsActivity.class));
break;
}
case R.id.action_create_new_chat_room: //exit app was clicked
{
mDialog =CreatePublicChatCreationDialog();
mDialog.show();
AlertCheckBoxClickListener= new OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog dialog = MainScreenActivity.this.mDialog;
EditText ed = (EditText) dialog.findViewById(R.id.choosePassword);
boolean b= !ed.isEnabled();
ed.setEnabled(b);
}
};
CheckBox ch = (CheckBox) mDialog.findViewById(R.id.checkBoxSetPassword);
ch.setOnClickListener(AlertCheckBoxClickListener);
break;
}
case R.id.clear_ignore_list: //exit app was clicked
{
if (mSearchFrag!=null)
mSearchFrag.ClearIgnoredUsersList();
break;
}
case R.id.feedback: //exit app was clicked
{
startActivity(new Intent(this, FeedbackActivity.class));
break;
}
case R.id.about: //exit app was clicked
{
startActivity(new Intent(this, AboutusActivity.class));
break;
}
case R.id.action_exit: //exit app was clicked
{
kill();
break;
}
case R.id.action_delete_all_history: //delete all history was clicked
{
mHistoryFrag.DeleteAllHistory();
break;
}
}//switch
return true;
}//end of onOptionsItemSelected()
#Override
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction)
{
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}//end of onTabSelected()
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
/**
* A FragmentPagerAdapter that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
Fragment fragment=null; //will hold the relevant fragment to be returned
switch (position)
{
case 0:
fragment = new ChatSearchScreenFrag(); //create a new chat search fragment
break;
case 1:
fragment = new ChatHistoryScreenFrag(); //create a new history display fragment
break;
}
return fragment;
}//end of getItem()
#Override
public int getCount()
{
return 2; // Show 2 total pages.
}
//Returns the title for each tab
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.main_screen_tab1_title).toUpperCase(l);
case 1:
return getString(R.string.main_screen_tab2_title).toUpperCase(l);
}
return null;
}
}//end of class
/**
* Called when the refresh button in the chat search fragment is clicked
*/
public void onRefreshButtonClicked (View v)
{
mSearchFrag.onRefreshButtonClicked(v); //call the frag's method
}//end of onRefreshButtonClicked()
/**
* Reads the saved preferences
*/
protected void getPrefs()
{
SharedPreferences prefs = getPreferences(0);
ChatRoomAccumulatingSerialNumber = prefs.getLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, 0);
UserName = prefs.getString(Constants.SHARED_PREF_USER_NAME, null);
UniqueID = prefs.getString(Constants.SHARED_PREF_UNIQUE_ID, null);
isToNotifyOnNewMsg = prefs.getBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, false);
RefreshPeriodInMs = prefs.getInt(Constants.SHARED_PREF_REFRESH_PERIOD, 10000);
mIsRunForTheFirstTime = prefs.getBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, true);
}//end of getPrefs(){
/**
* Saved the shared preferences
*/
protected void savePrefs()
{
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, ChatRoomAccumulatingSerialNumber); //save to current SN
editor.putString(Constants.SHARED_PREF_USER_NAME, UserName);
editor.putString(Constants.SHARED_PREF_UNIQUE_ID, UniqueID);
editor.putBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, isToNotifyOnNewMsg);
editor.putInt(Constants.SHARED_PREF_REFRESH_PERIOD, RefreshPeriodInMs);
editor.putBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, false);
editor.commit();
}//end of savePrefs()
/**
* Calls the kill() method of {#link ChatSearchScreenFrag}, resets all static variables,
* calls the system's garbage collector and finishes.
*/
public void kill(){
savePrefs();
mSearchFrag.kill(); //close the entire app (service and welcome socket)
//we'de like to reset all static variables in our app:
ChatActivity.mIsActive=false;
ChatActivity.mMsgsWaitingForSendResult=null;
ChatSearchScreenFrag.mService=null;
ChatSearchScreenFrag.mIsWifiDirectEnabled=false;
ChatSearchScreenFrag.mIsConnectedToGroup=false;
ChatSearchScreenFrag.mManager = null;
ChatSearchScreenFrag.mChannel = null;
LocalService.mNotificationManager=null;
//Indicates to the VM that it would be a good time to run the garbage collector
System.gc();
finish(); //close this activity
}//kill()
private AlertDialog CreatePublicChatCreationDialog()
{
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.public_chat_creation_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Create A New Room")
.setView(textEntryView)
.setIcon(R.drawable.settings_icon)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
boolean isPassword=false;
String password="";
String roomName=null;
EditText ed = (EditText) mDialog.findViewById(R.id.choosePassword);
//gets password if exists
isPassword= ed.isEnabled();
if(isPassword){password=ed.getText().toString();}
//gets rooms name
ed = (EditText) mDialog.findViewById(R.id.chooseRoomsName);
roomName=ed.getText().toString();
//if the room's name is invalid:
if(roomName==null || roomName.length()<1){
// pop alert dialog and reload this dialog
new AlertDialog.Builder(MainScreenActivity.this)
.setTitle("Missing name error")
.setMessage("A room must have a name")
//yes button setter
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {mDialog.show();}})//setPositive
.setOnCancelListener(new OnCancelListener(){
public void onCancel(DialogInterface dialog){mDialog.show();}})
.show();
//end of alert dialog
}//if
else{//there is a room name
//the room is ready to be created
//call the service and create a new public chat room
if (password.equalsIgnoreCase(""))
password=null;
ChatSearchScreenFrag.mService.CreateNewHostedPublicChatRoom(roomName,password);
}//else
}//onClick dialog listener
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
}).create();
}//end of ShowPublicChatCreationDialog()
}//end of class
Though it is commercial application but i have to share this because this issue must be solve by any how.
Here is the log cat what i got while stucking at screen:-
logcat
Can anyone please help me check my code to see why it cannot be
launched in the app itself but directs me to a browser? ): Thanks!!
MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://intelligami.com/submitqn");
mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
private class MyWebViewClient extends MyAppWebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Where is the error? :D
It keeps opening up in the browser.
In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;
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);
}
}
I am just starting to learn how to program, so sorry if this is a weird or dumb question.
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors located here.
Here is the code with the two thingies:
package com.example.ryanfolz.gridgame;
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);
// Add either a "next" or "finish" button to the action bar, depending on which page
// is currently selected.
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? R.string.action_finish
: R.string.action_next);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_previous:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
The fragment is here
package com.example.ryanfolz.gridgame;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ScreenSlidePageFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
ViewGroup rootView;
private int mPageNumber;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
if(mPageNumber == 1){
rootView = (ViewGroup) inflater
.inflate(R.layout.test, container, false);
((TextView) rootView.findViewById(R.id.test)).setText("Hello");
}else {
rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_screen_slide_page, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
}
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
}
Delete these line from your import
import android.app.FragmentManager;
import android.app.Fragment;
When your IDE ask for which class to import, you should choose these classes from support package instead, like this:
android.support.v4.app.FragmentStatePagerAdapter;
Instead of using getFragmentManager(), you should call getSupportFragmentManager()
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors
If you check the example properly they have imported
import android.support.v4.app.FragmentManager;
and not
import android.app.FragmentManager;
And also they have used
getSupportFragmentManager()
and not
getFragmentManager()
This changes is required because you are using the android support library for your fragment.
In your ScreenSlideActivity file, change
import android.app.FragmentManager;
to
import android.support.v4.app.FragmentManager;
And for ScreenSlidePageFragment, change this line
import android.app.Fragment;
into this
import android.support.v4.app.Fragment;
At last. Change all
getFragmentManager()
to
getSupportFragmentManager()
i have just started with android but have done some c# which seems very similar to java
in short, the problem lies in the closeDialog method
I am not very familiar with view/viewgroup so please dont bombard me with incorrect usage of objects, etc.
in short, i am creating a simple app which i hope to improve on (it is basically the start of a huge project)
the _showhint dialog opens fine, and shows the "hint" as expected, but the closeDialog force closes the app, I have no idea why
package com.example.app;
import android.app.Activity;
import android.app.Dialog;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageImageURI = null;
private TextView lblAnswer, lblWelcome;
private EditText edtInput;
public TextView showText ;
public Button btnShowHint, btnCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtInput = (EditText) findViewById(R.id.edtInput) ;
lblWelcome = (TextView) findViewById(R.id.lblWelcome) ;
lblAnswer = (TextView) findViewById(R.id.lblAnswer) ;
btnShowHint = (Button) findViewById(R.id.btnHelp);
btnCalculate = (Button) findViewById(R.id.btnShow) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void calculate(View vw)
{
String [] arrEditStore = new String[edtInput.length()] ;
String arrOperators [] = {"+", "-", "*", "/", "(", ")"} ;
}
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
EDIT: ADDED "this" to final Dialog dialog = new Dialog(this)
I have discovered what has caused the problem
GIVEN CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
SOULTION
first, I moved the decleration of the btnClose to the top
public Button btnShowHint, btnCalculate, btnClose;
then in the design view, removed the link of the button Close onclick method refering to closeDialog.
Afterwards, removing the closeDialog method completely, and also moving some of that code to the _showHint method
it also makes logical sense, thanks to #Mike M. who commented on the post, helped me reason it out, since I say, THIS button must close the dialog but in the method of this button, I am assigning it to be used by itself, which doesn't make logical sense at all, here is the changed code and it works
CHANGED CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
btnClose = (Button) showHintDialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showHintDialog.dismiss();
}
});
}
We all make stupid and unnessasary mistakes at times, some worse than others, but if you find a solution to a problem you have had, maybe somewhere someone has the same issue, so post a solution to your problem, it might help that someone!!!
cheers
When I try to access outer class with this code:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
it says:
The method getActivity() is undefined for the tyoe Logger
No enclosing instance of the type Logger is accessible in scope
Here is my Logger.java:
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageSwitcher;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class Logger extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
static boolean isBoxOpen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logger);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle("Sosyaaal");
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));
Thread connectivity = new Thread(){
public void run(){
try {
while(true)
{
while(!isBoxOpen)
{
if( !isOnline() )
{
isBoxOpen = true;
// display error
runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(Logger.this)
.setTitle("Bağlantı Sorunu")
.setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
.setCancelable(false)
.setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Logger.isBoxOpen = false;// Try Again
}
})
.show();
}
});
}
}
}
} catch (Exception e) {
}
}
};
connectivity.start();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logger, menu);
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Giriş fragment activity
return new GirisFragment();
case 1:
// Kayıt fragment activity
return new KayitFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GirisFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public GirisFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_giris,
container, false);
return rootView;
}
}
public static class KayitFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private ImageSwitcher cinsiyetSwitcher;
public KayitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kayit,
container, false);
cinsiyetSwitcher = (ImageSwitcher) getView().findViewById(R.id.cinsiyetSwitcher);
cinsiyetSwitcher.setFactory(new ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return myView;
}
});
return rootView;
}
}
}
*EDIT*
Changing this line:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
to this:
ImageView myView = new ImageView((Logger)getActivity().getApplicationContext());
solved the problem, but that was not what I was looking for. Thanks to Kapil Vij for correct Answer!
Do this
ImageView myView = new ImageView(getActivity());
getActivity() method is accessible in fragment class, and u r trying to access it using FragmentActivity class instance.
change to:
Logger.this.getApplicationContext()
Logger it-self is activity you call getActivity to get the reference of the activity inside a Fragment
EDIT
Saw that you are calling it inside a fragment change you code to:
ImageView myView = new ImageView(KayitFragment.this.getActivity().getApplicationContext());