Facebook like and comment not working on Android webview - android-studio

I have tried webview with Android studio and FB share and other social media share buttons are working fine. But FB direct like and comment button on my website is not working. When I press like button I can see white screen with left top screen number "1". Please kindly help me.
MainActivity.Java
package com.example.neermaicom;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import static android.content.Intent.*;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url == null || url.startsWith("http://") || url.startsWith("https://")) return false;
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
} catch (Exception e) {
return true;
}
}
});
webView.loadUrl("http://www.neermai.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
//This method require to use back button if want to go previous web page
#Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
}else {
super.onBackPressed();
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

This is due to the Facebook user auth, unfortunately android webview is not fully compatible with auth systems, an alternative that I use in my webview applications is to use "Chrome Custom Tabs" to auth access to the system of comments that I use.
In my application when the user clicks on comment, a Google Chrome tab is opened inside my application showing the comments page, when the user is not logged, the chrome auth the user without having to close or minimize my application to open google chrome. Everything is done within my own application.
To start the Chrome Tab when I added an "Intent" to shouldOverrideUrlLoading, below is an example of my code.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("#comments")){
Uri uri = Uri.parse(url);
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.build().launchUrl(PostActivity.this, uri);
return true;
}
else {
view.loadUrl(url);
return true;
}
}
And in Gradle app:
implementation 'androidx.browser:browser:1.3.0-alpha01'
My url for comment pages has "#comments" you change to something standard that you have in your comment page URLs or if the facebook comment system is directly on the post page, put something that is standard in the url of your posts to open in the google chrome tab.

Related

Create Android splash screen using SVG animation

I am developing an app using Xamarin.Forms and I am trying to insert the splash screen to my Android project.
I found a few tutorials for creating a splash screen with a background color and a static png image, but I want to use my svg animation as splash screen. I thought I could follow a tutorial for static image and just replace the png image with the svg animation, but it didn't work. Here's what I have so far:
On SplashActivity.cs:
[Activity(Label = "SplashActivity", Theme = "#style/Theme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
}
protected override void OnResume()
{
base.OnResume();
Task startupWork = new Task(() => { SimulateStartup(); });
startupWork.Start();
}
async void SimulateStartup()
{
await Task.Delay(5000);
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
On MainActivity.cs:
// I only changed the MainLauncher property to false
[Activity(Label = "MyApp", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
...
}
On styles.xml (in the Xamarin.Android project):
<style name="Theme.Splash" parent="android:Theme">
<item name="android:windowBackground">#drawable/desenhando5s</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="colorPrimaryDark">#004632</item>
</style>
When I run the application, it only shows a black screen as splash screen and then shows my login page as always.
Can anybody tell me what I have to do to set my animation as the splash screen?
(FYI: in case anyone wants to know, I created the animation using SVGator)
You could use FFImageLoading to load your svg image in your SplashActivity instead of set it in styles.xml.
Splash screen:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FFImageLoading.Views.ImageViewAsync
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Code:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.layout5);
var filePath = "check";
var imageView = FindViewById<ImageView>(Resource.Id.imageView);
ImageService.Instance.LoadCompiledResource(filePath).WithCustomDataResolver(new SvgDataResolver(64, 0, true)).Into(imageView);
}
protected override void OnResume()
{
base.OnResume();
Task startupWork = new Task(() => { SimulateStartup(); });
startupWork.Start();
}
async void SimulateStartup()
{
await Task.Delay(5000);
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
Updated:
Please check the screenshot. The .svg image is in the drawable folder. The layout5 is the splash screen in the layout folder.

cannot find symbol variable imageView2

I am just starting with Android Studio. I got some code from the web on how to ass a splash screen to my app, but it has compiling errors. I could use some help.
the errors are:
error. can not find symbol variable imageView2
error. can not find symbol variable s_img
error. can not find symbol variable s_image_black
error. can not find symbol variable s_image_black
I know this is due to my lack of knowledge, but I am just starting and trying to use this example to learn. Any help would be much appreciated.
Cheers
Paul
package org.quaestio.kotlinconvertedwebview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.ImageView;
import org.quaestio.kotlinconvertedwebview.MainActivity;
import java.util.Random;
public class Splashscreen extends Activity {
Thread splashTread;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
imageView = (ImageView)findViewById(R.id.imageView2);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
int[] ids = new int[]{R.drawable.s_img,R.drawable.s_image_black, R.drawable.s_image_black2};
Random randomGenerator = new Random();
int r= randomGenerator.nextInt(ids.length);
this.imageView.setImageDrawable(getResources().getDrawable(ids[r]));
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
Intent intent = new Intent(Splashscreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
Splashscreen.this.finish();
} catch (InterruptedException e) {
// do nothing
} finally {
Splashscreen.this.finish();
}
}
};
splashTread.start();
}
}
activity_splashscreen below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#feffc3"
android:layout_gravity="center"
android:id="#+id/lin_lay"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/splash"
android:background="#drawable/splash_img" />
</LinearLayout>
The problem is that you're setting an id wich don't correspond with the xml file. For example imageView = (ImageView)findViewById(R.id.imageView2); you need to change imageView2 with your xml imageview id wich is "splash". For the pthers error you need to check that files in the drawable folder.
Hope it was helpful
The ImageView in your xml has id splash, so in your code, instead of:
imageView = (ImageView)findViewById(R.id.imageView2);
you should do
imageView = (ImageView)findViewById(R.id.splash);
Also, this line:
int[] ids = new int[]{R.drawable.s_img, R.drawable.s_image_black, R.drawable.s_image_black2};
assumes that in your drawable folder there exist all these drawables:
s_img, s_image_black, s_image_black2
but apparently they don't, so you have to copy or create them and put them in the drawable folder.

Android Studio 3.2.1: Silent Mode Toggle app crashes when clicked even though no error in code

I'm just starting to learn coding for Android App by following the book Android App Development for Dummies to create the Silent Mode Toggle App.
Everything seems fine in the code (no error except for warning that:
"Casting 'findViewById(R.id.phone_icon)' to 'ImageView' is redundant.
This inspection reports unnecessary cast expressions."
I have read through a similar problem here (Application Crashes - Silent Mode Toggle - Android for Dummies) and it says to try:
1) Change "extends ActionBarActivity" to just "extends Activity" and import - mine is already as such.
2) delete or comment the 'if' in the onCreate method out - mine don't have this section.
3) change the parameter of the setContentView to: R.layout.fragment_main - not very sure what this means but don't seem to be relevant to my code? (his codes and mine are slightly different)
MainActivity.java Code
package com.dummies.silentmodetoggle;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.dummies.silentmodetoggle.util.RingerHelper;
public class MainActivity extends Activity {
AudioManager audioManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
setContentView(R.layout.activity_main);
FrameLayout contentView =
(FrameLayout) findViewById(R.id.content);
contentView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RingerHelper.performToggle(audioManager);
updateUi();
}
});
}
private void updateUi() {
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
int phoneImage = RingerHelper.isPhoneSilent(audioManager)
? R.mipmap.ringer_off
: R.mipmap.ringer_on;
imageView.setImageResource(phoneImage);
}
#Override
protected void onResume(){
super.onResume();
// Update our UI in case anything has changed.
updateUi();
}
}
RingerHelper.java
The book says to create a java file at: "src/main/java/com/dummies/silentmodetoggle/util/RingerHelper.java" but did not state how. Since I do not have a util folder so I'd created a package (New>Package) at "src/main/java/com.dummies.silentmodetoggle" and added the RingerHelper java file in the util folder. Note sure if this is the problem? The code is as below:
package com.dummies.silentmodetoggle.util;
import android.media.AudioManager;
public class RingerHelper {
// private to prevent users from creating a RingerHelper object
private RingerHelper(){}
/* Toggles the phone's silent mode */
public static void performToggle(AudioManager audioManager) {
// If the phone is currently silent, then unsilence it. If
// it's currently normal, then silence it.
audioManager.setRingerMode(
isPhoneSilent(audioManager)
? AudioManager.RINGER_MODE_NORMAL
: AudioManager.RINGER_MODE_SILENT);
}
/* Returns whether the phone is currently in silent mode. */
public static boolean isPhoneSilent(AudioManager audioManager){
return audioManager.getRingerMode()
== AudioManager.RINGER_MODE_SILENT;
}
}
Error from LogCat when I clicked the button on app
2018-12-01 22:11:44.029 30122-30122/com.dummies.silentmodetoggle E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dummies.silentmodetoggle, PID: 30122
java.lang.SecurityException: Not allowed to change Do Not Disturb state
at android.os.Parcel.readException(Parcel.java:1683)
at android.os.Parcel.readException(Parcel.java:1636)
at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
at com.dummies.silentmodetoggle.util.RingerHelper.performToggle(RingerHelper.java:13)
at com.dummies.silentmodetoggle.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
2018-12-01 22:11:44.672 1315-1315/? E/EGL_emulation: tid 1315: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
Otherwise the app seems to work fine, ie, when I click on the volume button of the device itself to silent, the app image will change to silent and vice versa. It just crashes when I try to click on the image of the app itself.
I really have no idea what's going on. Please help. Thanks very much!
You need to add permissions for Do Not Disturb State. I was facing the same issue and I added the following lines to my Main_Activity.java code in onCreate method and it works fine Now:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}

kotlin tcp socket client not working python server

I want to make an app that will connect to my python server using sockets.
When I press the connect button it does not even print the got connection on my PS, please help. Thank you
I have this basic code in kotlin:
//Kotlin Code
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import java.io.DataOutputStream
import java.net.Socket
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.start_page)
fun connect(v : View) {
try{
val soc = Socket("192.168.1.5", 1419)
val dout = DataOutputStream(soc.getOutputStream())
dout.writeUTF("1")
dout.flush()
dout.close()
soc.close()
}
catch (e:Exception){
e.printStackTrace()
}
}
}
The connect function is activated when clicked on a button, this is the xml code for my start screen
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/connect"
android:layout_width="108dp"
android:layout_height="50dp"
android:layout_marginBottom="127dp"
android:layout_marginEnd="228dp"
android:layout_marginStart="256dp"
android:onClick="connect"
android:text="#string/connect"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
and this is my code in python server:
#Python code
import socket
s = socket.socket()
s.bind(('0.0.0.0', 1419))
s.listen(5)
c, addr = s.accept()
print ('Got connection from', addr)
code_encoded = c.recv(1024)
code_decoded = code_encoded.decode('utf-8')
print(code_decoded)
c.close()
s.close()
I fixed it by implementing asynctask in my function and used java instead of kotlin but it should work similarly in kotlin as well.
The function is now, like this,
class ServerConnection extends AsyncTask<MainActivity.ConnParams, Void, Void> {
#Override
protected Void doInBackground(MainActivity.ConnParams... params)
{
String ip = params[0].ip;
int port = params[0].port;
String message = params[0].message;
try
{
Socket socket = new Socket(ip, port);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write(message);
printWriter.flush();
printWriter.close();
socket.close();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
}
Although asynctask is not good for tasks where you need it to be in background for longer periods of time, at which time I would recommend using android services.

Why Android libslide menu with actionbarsherlock open automatically?

I have a project with the sliding menu (from jeremy feinstein) and actionbarsherlock.
For some reason, when the activity shows up the slide menu open automatically too.
Quick note about my app architecture:
All of my activities have the slide menu integrated and on menu item click I start the related activity (with FLAG_ACTIVITY_SINGLE_TOP).
All my activities extends the class shown below.
This is quite annoying because every time the user click on one item, the menu get expanded as well forcing the user to close it down.
Anyone knows what it is causing this behavior?
What should I do to fix it and have the expected behavior.
I post below the concerned code:
package com.example.mypapp;
import com.example.mypapp.R;
import ocom.example.mypapp.SampleListFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class MyAppBaseActivity extends SlidingFragmentActivity {
protected ListFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setBehindContentView(R.layout.menu_frame);
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new SampleListFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
toggle();
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
toggle();
return true;
}
}
Where SlidingFragmentActivity has been modified to extend SherlockFragmentActivity as suggested on official page of Jeremy Feinstein when actionbarsherlock is also in the picture.

Resources