i put a webview in an activity .
the webview loads TelegramWeb's page.
when i login to the telegram account it works fine.
but when i rotate screen or reopen the app it forgets all data and needs relogin to telegram account.
so i need to save some data like coockies and other necessary files.
i used setJavaScriptEnabled=true and some other setting below:
#SuppressLint("SetJavaScriptEnabled") public class SubActivity extends Activity {
private WebView wv1;
protected void onSaveInstanceState(Bundle outState) {
wv1.saveState(outState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
Button b1=(Button) findViewById(R.id.btnSave);
wv1=(WebView)findViewById(R.id.webView1);
WebSettings ws=wv1.getSettings();
ws.setAllowContentAccess(true);
ws.setAppCacheEnabled(true);
ws.setSaveFormData(true);
wv1.setWebViewClient(new Webview());
wv1.getSettings().getCacheMode();
wv1.getSettings().getAllowContentAccess();
wv1.getSettings().getSaveFormData();
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv1.getSettings().setAllowFileAccess(true);
wv1.getSettings().setDomStorageEnabled(true);
wv1.setSaveEnabled(true);
if (savedInstanceState != null)
wv1.restoreState(savedInstanceState);
else
wv1.loadUrl("https://web.telegram.org/#/im");
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), wv1.getUrl().toString(), Toast.LENGTH_LONG).show();
}
});
}
}
but still it needs re-login to account.
better to know that SubActivity Class start from MainActivity after checking a password.
------
note:
i added this code after wf1.loadUrl and it works on screen rotation.
wv1.saveState(savedInstanceState);
but still not works when close app and reopen it. so i have to re-login.
i think i have to save the InstanceState some where.
how can i do?
If you don't want to use database for saving data you can use Shared Preferences where you save key-value pairs. More in documentation.
Try the below, it might works for cache issue,
wv1.getSettings().setDomStorageEnabled(true);
wv1.getSettings().setAppCacheEnabled(true);
The below works for device rotation and configuration changes
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
After this edit AndroidManifest.xml file like below
android:configChanges="orientation|screenSize|keyboardHidden"
Related
I am making a E-book reader application. I am using a WebView to display HTML formatted data coming through jSON.
If a user is reading a book and quits the app in between, I want to get the position of the text so that next time the user continues reading the book, it opens from the point he left it last time.
I looked up many questions but couldn't get any relevant answer.
You can do this overlaoding Activity onSaveInstanceState() and call webView.saveState() inside it
#Override
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
super.onSaveInstanceState(outState);
}
Then just call
WebView webview = (WebView)findViewById(R.id.webview);
if (savedInstanceState != null){
webview.restoreState(savedInstanceState);
}
else {
webview.loadUrl(url)
}
in Activity onCreate() method
I am beginner in android and developing an app in which i am using YouTubePlayer API in order to show Youtube Videos of specific Playlist. I'm succeed in doing so. But what I want is that whenever the user selects any video from that playlist; the video should be played in Full Screen. Here is my code:
public class Main4Activity extends AppCompatActivity
{
Toolbar main_toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
main_toolbar=(Toolbar) findViewById(R.id.my_thirdtoolbar);
setSupportActionBar(main_toolbar);
getSupportActionBar().setTitle(R.string.my_tb_title);
getSupportActionBar().setIcon(R.drawable.tblogo);
OnClickButtonListener();
}
public void OnClickButtonListener()
{
Button youtubebtn = (Button) findViewById(R.id.button8);
youtubebtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String PLAYLIST_ID = "PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40";
Intent intent=YouTubeIntents.createOpenPlaylistIntent(Main4Activity.this,PLAYLIST_ID);
startActivity(intent);
}
}
);
}
}
You can use methods from YouTubeIntents. Here are some methods that you can use:
canResolvePlayVideoIntentWithOptions (Context context)
Checks if the YouTube application installed on the user's device supports the fullscreen and finishOnEnd optional parameters when resolving a play video intent.
If this method returns true, then your application can call the createPlayVideoIntentWithOptions(Context context, String videoId, boolean fullscreen, boolean finishOnEnd) method which creates an Intent that, when resolved, will start playing the video specified by videoId, within the YouTube application.
If this method returns false, then your application should call the createPlayVideoIntent(Context context, String videoId) method instead.
Additionally, please also check other implementations and try the suggested solutions in this SO post. Hope it helps!
I created TabActivity having two tabs with two activities.
one is login tab another is welcome tab.
user should not go welcome tab unless login successfully.if he tries to select welcome tab he throws to login tab.i use tabHost.setcurrenttab(index).
But when i click direct welcome tab it works fine for first time. When i again click tab rapidly it opens welcome tab.
Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_list);
SharedPreferences mPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
username = mPreference.getBoolean("valid", false);
Toast.makeText(this, "In Create", Toast.LENGTH_SHORT).show();
//login sucessful
tabActivity.switchTab(0);
}
on onResume, i repeat the same code.
Try this in your TabActivity. This is to prevent user to switch tab if he is not logged in.(I have no time to check it now,please let me know if any issue is there with the code):
SharedPreferences mPreference;
....onCreate(){
...
mPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
username = mPreference.getBoolean("valid", false);
if(user is logged in){
tabHost.setcurrenttab(0);//welcome page
}
else{
tabHost.setcurrenttab(1);//login page
}
}
});
...
}
I want to extend a common security check to nearly every view of my application. To do this, I have made this class
public class ProtectedActivity extends ActivityBase {
boolean isAuthenticated = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread validationThread = new Thread()
{
#Override
public void run()
{
try
{
isAuthenticated = UserService.validateToken();
}
catch (FTNIServiceException e)
{
//eat it
}
finally
{
if (!isAuthenticated)
{
startActivity(new Intent(ProtectedActivity.this, SignInActivity.class));
finish();
}
}
}
};
validationThread.start();
}
}
The logic is simple. Validate the user against my restful api to make sure they are signed in. If they aren't, show them to the signin page.
This works great, because to add the security check, all I need to do is inherit from my ProtectedActivity.
public class MainMenuActivity extends ProtectedActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
The problem is, however, that I periodically receive View not attached to window manager errors. I understand why this is happening. I am starting a new intent in the parent class, and the child lives on. to attempt to alter it's view even though a new intent has started. What is a better way to handle this so that if a user is not authenticated (such as their session expires serverside), it won't error when sending the user to the sign in screen?
Don't you Thread. Use AsyncTask instead which should handle your references to windows correctly.
On a different note, I would change this to a different implementation. Why don't use the Preferences storage on the phone to store some kind token. If the token is not valid then request a new token and all the stuff you are doing currently. This way is better because you don't want to request a REST call every time.
I imagine something like this (pseudo code)
Check if credentials exist in Preference
if(valid) then do nothing
else use AsyncTask and pop up a loader screen "Waiting..."
I have people complaining my application gets FC when they launch it (meanwhile others never had a single problem). Here is my full activity source. Since it happens on devices I don't own I can not fix it. From what they tell me it doesn't work on: Motorola Blackflip, Motorola Dext, Motorola CLIQ XT. Guess Motorola doesn't like my app after all...
Could it be that I allow a minSdkVersion="3"? I tested 1.5 on the emulator and worked fine...
Thank you in advance for your responses.
public class workit extends Activity implements OnClickListener {
Button yay;
Button yay0;
Button yay1;
/** Called when the activity is first created. */
#Override
public 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.main);
yay = (Button) findViewById(R.id.gostart);
yay.setOnClickListener(this);
yay0 = (Button) findViewById(R.id.dontstart);
yay0.setOnClickListener(this);
yay1 = (Button) findViewById(R.id.exit);
yay1.setVisibility(ImageView.GONE);
ImageView inizio = (ImageView)findViewById(R.id.start);
inizio.setVisibility(ImageView.VISIBLE);
inizio.setBackgroundResource(R.drawable.start);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == yay0) {
finish();
}
if (v == yay) {
ImageView inizio = (ImageView)findViewById(R.id.start);
inizio.setVisibility(ImageView.GONE);
WebView work = new WebView(this);
setContentView(work);
work.loadUrl("file:///android_asset/index1.html");
work.setWebViewClient( new work());
work.setBackgroundColor(0);
work.getSettings().setBuiltInZoomControls(true);
work.getSettings().setDefaultZoom(ZoomDensity.FAR);
}
if (v == yay1) {
finish();
}
}
private class work extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("exit.html")) {
// TODO: do what you have to do
finish();
}
view.loadUrl(url);
return true;
}
}
}
Your best bet is to ask somebody to send you the LogCollector output (in my experience, users are very happy to provide you information to debug problems. There are some really cool people out there). That should give you a callstack, and information on what kind of exception you triggered (NullPointerException, etc).
Next up - what are you building your app against? There should be an "Android x.x" entry in your project structure somewhere. If you're building something that is supposed to run on Android 1.5, then make sure you actually build against 1.5. You CAN build against 2.0 if you want, but if you need to use 2.0-specific functions, you'll have to encapsulate them properly. (This has been explained in detail on stackoverflow several times.)
On an unrelated note - I recommend more informative variable names. "yay0" doesn't mean anything to anyone who hasn't been working intimately with the code for a while.