I'm trying to use an android app with my data base. I know how to retrieve and send information to the data base, but I don't know how to do it in Android.
When I type the URL, lets say "http://01.01.001.001/api/example" in the browser, I can see this:
<ArrayOfArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<ArrayOfstring>
<string>52</string>
<string>Pregunta espaƱol prueba 52</string>
<string>NO</string>
<string>SI</string>
<string>NO</string>
<string/>
<string/>
<string/>
<string/>
<string/>
<string/>
<string/>
<string i:nil="true"/>
</ArrayOfstring>
<ArrayOfstring>
<string>53</string>
<string>Pregunta 53 NIVEL 2</string>
<string>NO</string>
<string>53 mucho</string>
<string>53 Algo</string>
<string>53 Nada</string>
<string>53 Poco</string>
<string>53 Fin</string>
<string i:nil="true"/>
<string i:nil="true"/>
<string i:nil="true"/>
<string i:nil="true"/>
<string i:nil="true"/>
</ArrayOfstring>
which is a bunch of strings. How can I place each string in a variable in android? If I try
public static InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
} catch (Exception e) {
//handle the exception !
}
return content;
}
The content is always null when using the URL. Once the content is not null, how can I translate it to a set of strings?
Thanks a lot!
Related
I have been trying to authenticate via Google OAuth 2.0. Following this link.
Have been able to open the Google Auth page and login successfully.
The problem is after logging in i am redirected to the google search page.
If i close the application then in the OnAuthCompleted method of the OAuth2Authenticator i get the e.IsAuthenticated to false and not able to get any information of the user.
Xamarin Share Library code:
var authenticator = new OAuth2Authenticator(
"somekey-somekey1.apps.googleusercontent.com",
null,
"email",
new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
new Uri("com.companyname.somenameofapp:/oauth2redirect"),
new Uri("https://www.googleapis.com/oauth2/v4/"),
null,
true);
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
authenticator.Completed += OnAuthCompleted;
AuthenticationState.Authenticator = authenticator;
AuthenticationState Class
public class AuthenticationState
{
public static OAuth2Authenticator Authenticator;
}
The OnAuthCompleted method
private async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
if (e.IsAuthenticated)
{
await Navigation.PushAsync(new GoogleLoginSuccess());
}
}
Main Activity Code
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, savedInstanceState);
LoadApplication(new App());
}
CustomUrlSchemeInterceptorActivity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace XamAppGoogleAuth.Droid
{
[Activity(Label = "CustomUrlSchemeInterceptorActivity")]
[IntentFilter(
new[] { Intent.ActionView },
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
DataSchemes = new[] { "com.companyname.somenameofapp" },
DataPath = ":/oauth2redirect",
DataHost = "com.companyname.somenameofapp")]
public class CustomUrlSchemeInterceptorActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
global::Android.Net.Uri uri_android = Intent.Data;
Uri uri_netfx = new Uri(uri_android.ToString());
// load redirect_url Page
AuthenticationState.Authenticator.OnPageLoading(uri_netfx);
var intent = new Intent(this, typeof(MainActivity));
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
StartActivity(intent);
this.Finish();
return;
}
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.somenameofapp">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
<application android:label="somenameofapp.Android"></application>
<activity android:name="somenameofapp.Android.MainActivity" android:label="MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="com.companyname.somenameofapp" android:host="com.companyname.somenameofapp" />
</intent-filter>
</activity>
</manifest>
When i close the Custom Tab explicitly i am navigated back to the application with the below toast message.
What i would want is after the user authenticates with Google OAuth, they are redirected back to the application and I can get the access token and other information as needed. I have been to a lot of links regarding this but havent been able to find a solution. Kindly help
#kinder-cappy
I noticed you have the URL scheme interceptor activity in your application manifest as well as an activity class. You will have to choose one or else you will have multiple intent on trigger.
To remove the "customtabs login screen ...." message add this to your MainActivity (not interceptor class) after Xamarin.Auth initialization:
global::Xamarin.Auth.CustomTabsConfiguration.CustomTabsClosingMessage = null;
Also use Xamarin.Auth version 1.5.0.3 for now in android. It works.
If the current redirect URL scheme you specified does not works, try to get the correct redirect URL from your provider documentations. In my case, I used Google so I am using the inverted URL (client id).
If the current redirect URL scheme you specified does not work, try to get the correct redirect URL from your provider documentation. In my case, I used Google so I am using the inverted URL (client id).
In your CustomUrlSchemeInterceptorActivity DataSchemes and in Redirect URI you need to put inverted URL (ie. client ID) which you can get from the developer console.
client-id : "somekey-somekey1.apps.googleusercontent.com"
Redirect URI looks like : com.googleusercontent.apps.somekey-somekey1:/oauth2redirect
DataSchemes = new[] { "com.googleusercontent.apps.somekey-somekey1" } at your CustomUrlSchemeInterceptorActivity
I have following defined in
struts-config.xml:
<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.actionform.LoginForm"/>
</form-beans>
<action-mappings>
<!-- action for login -->
<action input="/views/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.actions.LoginAction"
parameter="method" validate="true">
<forward name="success" path="/views/Frameset.html" />
</action>
</action-mappings>
<message-resources parameter="/WEB-INF/ApplicationResources"/>
<!-- ========================= Validator plugin ================================= -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
The login form:
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (userName == null || userName.length() < 1) {
System.out.println("in validate ---");
errors.add("userName", new ActionMessage("error.userName.required"));
// TODO: add 'error.name.required' key to your resources
}
if (password == null || password.length() < 1) {
errors.add("password", new ActionMessage("error.password.required"));
// TODO: add 'error.name.required' key to your resources
}
return errors;
}
login.jsp:
<html:form action="/Login?method=loginUser">
<html:errors/>
<html:text name="LoginForm" property="userName" />
<html:messages id="err_userName" property="userName">
<bean:write name="err_userName" />
</html:messages>
</html:form>
Property file:
error.userName.required = User Name is required.
error.password.required = Password is required.
Where am I doing wrong? I am getting the following error
javax.servlet.jsp.JspException: Cannot find bean error in any scope
I just want to display the error in the same JSP.
After you obtain the ActionMessages/ActionErrors object which contains the messages or errors you want to display in your input page (using <html:messages> tags or <html:errors> tags), you must call one of the following methods from your Action object to place the result of your validation in scope:
addMessages(HttpServletRequest request, ActionMessages messages)
or
addErrors(HttpServletRequest request, ActionMessages errors)
Are you doing that?
I'm really do not care how about struts handles an exception. Using old raw code from 1.2 generally when overriding a RequestProcesor, I should probably replace the two methods - process and processException. First thing is happy about catching exception from the request after processValidation has been made. The fragment of code could look like
Exception exception = null;
if (needValidation)
try {
if (! processValidate(request, response, form, mapping)) {
return;
}
exception = (Exception)request.getAttribute(Globals.EXCEPTION_KEY);
} catch (InvalidCancelException ex) {
exception = ex;
}
ActionForward forward;
// Check out if exception occurred
if (exception != null){
forward = processException(request, response, exception, form, mapping);
The second is pretty easy if you have configured the errors forward. The errors forward is usually one of the global forwards that easily found from the mapping. Once it found, it likes to display your error message on the page. I think those would probably enough for processing an exception
exception.printStackTrace();
log.error(exception);
request.setAttribute("error", exception.getMessage());
return mapping.findForward("error");
It has been done because validate method from ActionForm or ValidatorForm doesn't throw any exceptions and I couldn't properly override this method without throwing some. Once thrown, who will care about it?!
I have a WinJS project which has a BackgroundTask in Runtime Component that triggers when Push Notification is sent (Raw notifications) from my own webservice.
And that Background service creates a local toasts and show it in action notification center.
public static void ShowNotification(int notificationId, string ToastTitle, int messageType, string messageDetails)
{
string messageText = String.Empty;
ToastTemplateType toastTemplate = ToastTemplateType.ToastText04;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(ToastTitle));//Toast notification title
toastTextElements[1].AppendChild(toastXml.CreateTextNode(messageText));
toastTextElements[2].AppendChild(toastXml.CreateTextNode(messageDetails));
var launchAttribute = toastXml.CreateAttribute("launch");
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("duration", "short");
toastNode.Attributes.SetNamedItem(launchAttribute);
//Launch params
var toastNavigationUriString = messageDetails;
var toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast"));
toastElement.SetAttribute("launch", toastNavigationUriString);
ToastNotification toast = new ToastNotification(toastXml);
toast.Tag = notificationId.ToString();
toast.ExpirationTime = DateTimeOffset.UtcNow.AddDays(3);
if (true)
{
toast.SuppressPopup = false;//to send notification directly to action center without displaying a popup on phone.
}
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
And I was handling those toasts like this in JS:
WinJS.Application.addEventListener("activated", onActivatedHandler, true);
function onActivatedHandler(args) {
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
messageDetails = args.detail.arguments;
PhonegapService.setNotificationMessage(messageDetails, function () {
window.location.href = "index.html";
});
}
}
XML format that is used in this case on my webservice is:
string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<root>" +
"<Value1>" + "Hello" + "<Value1>" +
"<Value2>" + "Raw" + "<Value2>" +
"</root>";
Now there is slightly change in Push Notifications. I want to send push notifications (Toasts) directly from my webservice rather than sending Raw messages.
My questions are:
How to attach launch params and message on my toast notification in web-service similar like we did while creating local toasts.
When toasts are received how to handle click events and get the useful messages attached with that notification.
XML in this case would be like this:
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string toast2 = string.Format(#"<toast>
<visual>
<binding template=""ToastText04"">
<text id=""1"">{0}</text>
<launch></launch>
</binding>
</visual>
</toast>",message);
string xml = toast1 + toast2;
Update 1
I used the following XML on my web-service. But I'm getting notification in an unusual format than I expected:
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string message = "some json";
string toast2 = string.Format(#"<toast launch= ""{0}"">
<visual version=""1"">
<binding template=""ToastText02"">
<text id=""1"">{1}</text>
<text id=""2"">{2}</text>
</binding>
</visual>
</toast>", message, "Alert", "Test");
You need to create an XML with the same structure as the following (with or without the custom audio):
<toast launch=\"$param\">
<audio src=\"ms-appx:///Assets/Sounds/$sound.wav\"/>
<visual>
<binding template=\"ToastText04\">
<text id=\"1\">$title</text>
<text id=\"2\">$msg</text>
</binding>
</visual>
</toast>
Notice that launch is a member of the <toast> tag.
You can handle click events the same as before when the app is activated, you get the string that is the value of launch.
I am new to Windows phone development and currently I am facing an issue. I am working on consuming a RESTful service for a windows phone application and I am getting a response successfuly in the format shown below
<StationsResp xmlns="http://www.wmata.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Stations>
<Station>
<Code>A03</Code>
<Lat>38.9095980575</Lat>
<LineCode1>RD</LineCode1>
<LineCode2 i:nil="true" />
<LineCode3 i:nil="true" />
<LineCode4 i:nil="true" />
<Lon>-77.0434143597</Lon>
<Name>Dupont Circle</Name>
<StationTogether1 />
<StationTogether2 />
</Station>
<Station>
<Code>A02</Code>
<Lat>38.9032019462</Lat>
<LineCode1>RD</LineCode1>
<LineCode2 i:nil="true" />
<LineCode3 i:nil="true" />
<LineCode4 i:nil="true" />
<Lon>-77.0397008272</Lon>
<Name>Farragut North</Name>
<StationTogether1 />
<StationTogether2 />
</Station>
</Stations>
</StationsResp>
My C# code goes below to call the service and store this response.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://api.wmata.com/Rail.svc/Stations?api_key=API_KEY_CODE_OMITTED_INTENTIONALLY");
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += OnDownloadStringCompleted;
webClient.DownloadStringAsync(uri);
}
void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs args)
{
XElement elm = XElement.Load(args.Result);
var SearchResults = elm.Elements("Station");
}
My Problem is with the last line. object 'elm' has the value as per the response posted above. However, when I try to query the object elm using any methods [like elm.Descendents(), elm.Elements()] it doesn't work. My System.Xml.Linq reference version for windows phone is 2.0.5.0. Am I missing something else?
Following is the exact error message I get.
On watch window I see the value in object elm. But LINQ query elm.Elements("Station") errors out. The error message is "System.Collections.IEnumerator.CurrentCould not evaluate expression".
Any help is greatly appreciated. Thanks in advance.
How make a sending email from controller? I have email address in database, so I get this email from base and send special text message to this email. I don't need use a View.
Here we go:
Your code:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress("yourname#yourdomain.com");
message.To.Add(new System.Net.Mail.MailAddress("receiver#receiverdomain.com"));
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
message.Subject = "subject";
message.Body = "hello receiver";
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Send(message);
And your web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="yourname#yourdomain.com" deliveryMethod="Network">
<network host="smtp.yourprovider.com" port="587" userName="yourname#yourdomain.com" password="yourpass" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
...
You could use MvcMailer. Or if you want to implement it manually you could use the SmtpClient class to send emails.