I want to connect to wampserver and toast a webpage content in android app by pushing button (btnget) but when I click the button it doesn't toast.where is the problem?
my page on the localhost is "ss.php"
this is the connect class:
public class Connect extends AsyncTask {
public String link="";
public Connect(String link){
this.link=link;
}
#Override
protected Object doInBackground(Object[] params) {
try{
URL url=new URL(link);
URLConnection connection=url.openConnection();
BufferedReader reader=new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
builder.append(line);
}
MainActivity.data=builder.toString();
}catch (Exception e){
}
return "";
}}
this is main activity class:
public class MainActivity extends AppCompatActivity {
public static String data="";
Button getData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*address of the webpage on localhost:http://IP/path */
new Connect("http://192.168.56.1/localhost/shop/ss.php").execute();
getData=(Button)findViewById(R.id.btnGet);
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,data, Toast.LENGTH_SHORT).show();
}});
};
}
If I'm not mistaking the link to your site hosted locally on a WAMP instance should look something like this: http://LocalHost:8080/shop/ss.php (or another port number that you configured in wamp settings)
Related
It's been two weeks that I'm struggling to make my webbased application working on android.
It is a simple data entry application. In chrome browser, it works like a charm, but in android, which is the final deployment options, i's a nightmare.
(1) It won't store any cookie
(2) < input type=file >, won't open file browser
(3) toast won't work
(3) unable to make AVD working, and cannot debug anythings
Any help could be appreciated.
MainActivity.java
package com.example.webview;
import ...
public class MainActivity extends AppCompatActivity {
WebView webView;
String TAG = "MainActivity";
Context context;
private final String host = "sercom-farm.net";
private static final int STORAGE_PERMISSION_CODE = 123;
private final static int FILECHOOSER_RESULTCODE=1;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
final Context myApp = this;
final class MyWebChromeClient extends WebChromeClient {
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(myApp)
.setTitle("Sercom Farm App")
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.create()
.show();
return true;
}
}
private static class LocalContentWebViewClient extends WebViewClientCompat {
private final WebViewAssetLoader mAssetLoader;
LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
mAssetLoader = assetLoader;
}
#Override
#RequiresApi(21)
public WebResourceResponse shouldInterceptRequest(WebView view,
WebResourceRequest request) {
return mAssetLoader.shouldInterceptRequest(request.getUrl());
}
#Override
#SuppressWarnings("deprecation") // to support API < 21
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
}
}
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebAction();
}
public void WebAction() {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.loadUrl("file:///android_asset/m2.html");
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");
CookieManager cookieManager = CookieManager.getInstance();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{ cookieManager.setAcceptThirdPartyCookies(webView,true); }
else { cookieManager.setAcceptCookie(true); }
}
public void onBackPressed() {
// TODO Auto-generated method stub
webView.loadUrl("javascript:Fback() ;") ;
}
public class WebViewJavaScriptInterface{
private Context context;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface(Context context){
this.context = context;
}
/*
* This method can be called from Android. #JavascriptInterface
* required after SDK version 17.
*/
#JavascriptInterface
public void makeToast(String message, boolean lengthLong){
Toast.makeText(context, message, (lengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)).show();
}
}
}
I'm using
Android Studio Chipmunk | 2021.2.1 Patch 1
Build #AI-212.5712.43.2112.8609683, built on May 18, 2022
Runtime version: 11.0.12+7-b1504.28-7817840 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 7 6.1
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 2
Registry: external.system.auto.import.disabled=true
I'm making an android app using Java as a language. The idea of this app is to be able to log me in with my twitter account and be able to get the name, email and image of the account which should be shown in a kind of user profile in the app In order to log in, I'm using the package: twitterkit: 3.1.1 but I can't connect with my account, this is what I have so far:
public class loggin extends AppCompatActivity {
//pruebas twitter:
TwitterAuthClient mTwitterAuthClient;
TwitterApiClient twitterApiClient;
StatusesService statusesService;
//variable twitter
TwitterLoginButton login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Twitter.initialize(this);
login = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
login.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
login(session);
Toast.makeText(loggin.this, "falto poco", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(loggin.this, "casiiiiii", Toast.LENGTH_SHORT).show();
}
});
}
public void login(TwitterSession session){
long userId = session.getUserId();
String userName = session.getUserName();
Intent intent =new Intent(loggin.this,MainActivity.class);
intent.putExtra("username",userName);
startActivity(intent);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
login.onActivityResult(requestCode, resultCode, data);
}
I am getting compile error in line .addOnCompleteListener(LoginActivity.this : Login Activity is not an enclosed class.
Am I doing anything wrong in below code?
Below is my code in Activity
public class LoginFirebase extends AppCompatActivity {
private FirebaseAuth auth;
Button btn_Login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_firebase);
btn_Login = (Button) findViewById(R.id.btn_Login);
btn_Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
auth.signInWithEmailAndPassword("username", "password")
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
}
})
}
});
}
}
Please replace LoginActivity to LoginFirebase .
If I have created a deep link using the branch.io that opens a specific screen in my app. If this link is also available in my app and a user clicks on it, will it open my screen? or it will do nothing as the link I am trying to open from the app is pointing to the same app?
When you click on a Branch link within a webView in your App, you will have to handle the routing to the specific Activity, after reading the Branch link parameters.
Here is a sample Activity which contains a webView and and shows a couple of Branch links. When you click on a link in the webView it reopens the webview and displays the link parameters in a Toast message if a Branch link is clicked
public class MainActivity extends AppCompatActivity {
private WebView webView_;
private Button button_;
private String TAG = "WebViewController";
private Context context_;
private static final String URL_TO_LOAD = "https://evangelosg.github.io/index.html";
private static final String BRANCH_LINK_TO_LOAD = "https://ere6.app.link/b6sS0gsCfG";
#Override
protected void onNewIntent(Intent intent) {
Log.d("WebView", "onNewIntent");
setIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
Branch branch = Branch.getInstance();
branch.initSession(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
Log.d(TAG, referringParams.toString());
Toast.makeText(context_, referringParams.toString(), Toast.LENGTH_LONG).show();
if (referringParams.has(BundleExtraKeys.CLICKED_BRANCH_LINK)) {
try {
boolean clickedBranchLink = referringParams.getBoolean(BundleExtraKeys.CLICKED_BRANCH_LINK);
if (clickedBranchLink) {
//do stuff!
}
} catch (JSONException e) {
Log.d("BranchTrends", e.getMessage());
}
}
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context_ = this;
setContentView(R.layout.activity_main);
webView_ = (WebView) findViewById(R.id.webView);
webView_.setWebViewClient(new BranchWebViewController("app.link", MainActivity.class));
webView_.loadUrl(URL_TO_LOAD);
button_ = (Button) findViewById(R.id.button);
button_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.putExtra("branch", BRANCH_LINK_TO_LOAD);
customTabsIntent.intent.putExtra("branch_force_new_session", true);
finish();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(BRANCH_LINK_TO_LOAD));
}
});
}
public class BranchWebViewController extends WebViewClient {
private String myDomain_;
private Class activityToLaunch_;
BranchWebViewController(#NonNull String myDomain, Class activityToLaunch) {
myDomain_ = myDomain;
activityToLaunch_ = activityToLaunch;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(myDomain_)) {
Intent i = new Intent(view.getContext(), activityToLaunch_);
i.putExtra("branch", url);
i.putExtra("branch_force_new_session", true);
finish();
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
}
Once you read the link parameters you can route to the appropriate Activity based on the link parameters.
Here is My Code.
I just want to get the page content from the Webview after load the URL .
On Android, I have a WebView that is displaying a page.
How do I get the page source without requesting the page again?
It seems WebView should have some kind of WebResourceResponse () method in Android 3.0 but don't know how to use it.
public class WebActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://xyz.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
public WebResourceResponse shouldInterceptRequest (WebView view, String url)
{
return null;
}
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}}
I know this is old, but for future visitors, the following should work.
First, you need to define an interface such as:
final class LoadingInterface {
#JavascriptInterface
public void outputHTML(final String html){
//do what ever you want with html
}
}
Then on your WebView call
webView.addJavascriptInterface(new LoadingInterface(), "INTERFACE");
In onPageFinished put:
String js = "javascript:"
+"var html = document.getElementsByTagName('html')[0].innerHTML;"
+"window.INTERFACE.outputSchedule(html);";
webView.loadUrl(js);
If you only need part of a page, you can replace getElementsByTagName('html')[0] with something like getElementById('partOfPage')