Display web service results on a form (Codename One) - java

After watching these videos, I'm trying to do the same but I'm finding it very difficult as I'm using the old GUI Builder.
I created a form called Form A. I want those results from the web service to display on the form A and be able to navigate upon clicking any of those images just like what happened inside the video.
I'm using the following methods:
private Map response;
#Override
protected void beforeFormA(Form f) {
getattractive();
ArrayList arr = (ArrayList) response.get("results");
for (Object m:arr){
Map ma = (Map)m;
address =(String) ma.get("formatted_address");
findContainer(f).addComponent(new Label(""+ address ));
}
}
Connection Request:
private void getattractive(){
ConnectionRequest r= new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parse= new JSONParser();
response= parse.parseJSON(new InputStreamReader(input));
}
};
String doc="Johor";
r.setUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+doc+"+city+point+of+interest&language=en&key=api_key");
r.setPost(false);
r.setHttpMethod("GET");
InfiniteProgress prog=new InfiniteProgress();
Dialog dlg=prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance(). addToQueueAndWait(r);
}
First record from the webservice (Attached picture):
Please kindly help.
Regards,
IDE: NetBeans
Desktop OS: Windows 7
Simulator

Related

How to access a variable stored in an online file

Am still new to Android in some stuff and I want to do something that I do on my php script which is kind of a SAAS. There I have some line of code that runs online to check for new update of my cms when the use opens the admin dashboard.
I want to do the same with my android app by maybe saving a txt file on a github repository like
http://github.com/wasiro/myapp/version.txt
which I will be updating when i make a major app update
Where i save something like 1.0.9.734 so that my app can get the variable and use it to inform my user that there is a new update alternatively
currenty i have this on my code
public static final String BaseUrl = "http://github.com/wasiro/myapp/version.txt";
Any assistance on achieving this would help alot and if there are better ways to do it please enlighten me.
Don't confuse this to JSON because I want to use GitHub to store my variable like I do with my phone script
Edit:
When I tried this instead of the variable in the file being extracted and read it was the path to the file that got on the way of the code
I think everyone is too quick to brush the question aside to being a duplicate instead of understanding what is all about? So sad this is what the SO community has become.
Your issue is to open a file located elsewhere.
private class myStreamReader extends AsyncTask<String, Void, String> {
String str = "";
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://github.com/wasiro/myapp/version.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
str = in.readLine();
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
//do something here
httpStuff.setText(str);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}

codename one web services soap call not working

I want to consume SOAP based web services when click on a login button.
My code is as follows
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" CaterId : "+catererId.getText());
Log.p(" Username : "+loginId.getText());
Log.p(" Password : "+password.getText());
final String InputParameter = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
+" <soap:Header/>"
+" <soap:Body>"
+" <tem:AuthenticateSupervisor>"
+" <tem:username>TestAbhi</tem:username>"
+" <tem:password>TestAbhi</tem:password>"
+" <tem:caterer>calihanint</tem:caterer>"
+" </tem:AuthenticateSupervisor>"
+" </soap:Body>"
+"</soap:Envelope>";
ConnectionRequest r= new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(InputParameter.getBytes("UTF-8"));
}
#Override
protected void postResponse() {
//super.postResponse();
}
#Override
protected void readResponse(InputStream input) throws IOException {
//super.readResponse(input);
XMLParser parser = new XMLParser();
Element elem = parser.parse(new InputStreamReader(input));
Log.p(" Came heer"+elem);
}
};
r.setUrl("http://192.168.10.224:8888/CXPPostScheduleService/Service.asmx");
r.setPost(false);
/*r.addArgument("username", "TestAbhi");
r.addArgument("password", "TestAbhi");
r.addArgument("caterer", "calihanint");*/
r.setContentType("application/soap+xml;charset=UTF-8");
NetworkManager.getInstance().addToQueueAndWait(r);
r.getResponseData();
}
});
It displays an html file as response. Could you please assist me to check what I'm doing wrong in this code.
I assume you need a post request try:
r.setPost(true);
If you are calling this from the device make sure the device is in the same network as the server otherwise the NAT local address will be unreachable. Notice that this will also apply to the simulator if the server is hosted elsewhere and not on your machine.
I also suggest checking the server logs, the error response code and post the error HTML. You can use the network monitor tool in the simulator to further debug this.

Java - How to Retrieve and use a single value from azure mobile services in Android

I am new to azure but i know certain things like how to retrieve and store data to azure , i followed azure official documentation for this purpose.
Link is Here - https://azure.microsoft.com/en-in/documentation/articles/mobile-services-android-get-started-data/
But the problem is, this tutorial is only showing How to retrieve and use Data from azure using Adapters and Lists . I want to know , How can i retrieve a single value from azure mobile services and how to use it in android.
Plzz provide me both backend code (if there is any) and java code for this . THANKS in advance
I got it solved. No need to create a custom API.
Just follow the basics , Here is the code :-
final String[] design = new String[1];
private MobileServiceTable<User> mUser;
mUser = mClient.getTable(User.class);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<User> result =
mUser.where().field("name").eq(x).execute().get();
for (User item : result) {
// Log.i(TAG, "Read object with ID " + item.id);
desig[0] = item.getDesignation(); //getDesignation() is a function in User class ie- they are getters and setters
Log.v("FINALLY DESIGNATION IS", desig[0]);
}
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
designation.setText(desig[0]);
}
}.execute();
DON'T forget to create a class User for serialization and all. Also you should define the array .
FEEL FREE to write if you got it not working.
EDIT :-
design[0] is an array with size 1.
eq(x) is equal to x where , x variable contains username for which i want designation from database (azure).
You can do this with a custom API. See this link: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-use-server-scripts/#custom-api
Code looks like this:
exports.post = function(request, response) {
response.send(200, "{ message: 'Hello, world!' }");
}
It's then reachable at https://todolist.azure-mobile.net/api/APIFILENAME.
If you want to access a table you can do something like:
exports.post = function(request, response) {
var userTable = tables.getTable('users');
permissionsTable
.where({ userId: user.userId})
.read({ success: sendUser });
}
function sendUser(results){
if(results.length <= 0) {
res.send(200, {});
} else {
res.send(200, {result: results[0]});
}
}
You can then follow the instructions for using the API on your Android client here: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-call-custom-api/
How your app is written will change how this code works/looks, but it looks something like:
ListenableFuture<MarkAllResult> result = mClient.invokeApi( "UsersAPI", MarkAllResult.class );
That invokes the API. You need to write the class and Future to handle the results. The above page explains this in great detail.
The most optimal solution would be to create an api on your server which accepts an ID to return an single object/tablerow.
In your android app, you only have to call:
MobileServiceTable<YourClass> mYourTable;
mClient = new MobileServiceClient(
"https://yoursite.azurewebsites.net/",
mContext);
mYourTable = mClient.getTable(YourClass.class);
YourClass request = mYourTable.lookUp(someId).get();
// request -> https://yoursite.azurewebsites.net/tables/yourclass/someId
YourClass should have the same properties as the object on the server.

Google App Engine HTTP ERROR 503 error

Ï am Taking data From server written in "C" using Sockets .
My java class name is ReceivingData, and here's the code for receiving the data and storing it in ArrayList and passing the ArrayList to other Class's Constructor.
package pack.exp;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ReceivingData implements Runnable
{
public static void main(String[] args)
{
Thread t = new Thread(new ReceivingData());
t.start();
}
public List<String> obj1;
#Override
public void run()
{
Socket s;
InputStream stream;
try
{
s = new Socket("10.9.211.22", 6870);
stream = s.getInputStream();
byte[] data = new byte[13];
int read;
String can_Id= null;
while((read = stream.read(data)) != -1)
{
String can_Data=
String.format("%02X:%02X:%02X:%02X,
data[0], data[1], data[2], data[3]);
List<String> obj1= new ArrayList<String>();
obj1.add(can_Data.substring(0, 2));
obj1.add(can_Data.substring(3, 5));
obj1.add(can_Data.substring(6, 8));
obj1.add(can_Data.substring(9, 11));
Receiving_At_Regular_IntervalServlet rari= new
Receiving_At_Regular_IntervalServlet(obj1);
Thread.sleep(3000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is the Servlet which is receiving the data from ArrayList passed by the above File.
and storing this data from the arraylist in to the Entity for datastore and deploys it on the Google App engine.
package pack.exp;
#SuppressWarnings("serial")
public class Receiving_At_Regular_IntervalServlet extends HttpServlet
{
List<String> obj2= new ArrayList<String>();
public Receiving_At_Regular_IntervalServlet(List<String> obj2) throws
IOException
{
this.obj2= obj2;
System.out.println("Receiving in Web Project" + obj2);
System.out.println("");
System.out.println("");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
Key k1 = KeyFactory.createKey("C","0D F0 0800 1");
String parameter1 = obj2.get(0);
Entity can1 = new Entity(k1);
can1.setProperty("First Parameter", parameter1);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(can1);
Entity can11 = null;
try
{
can11= datastore.get(k1);
}
catch (EntityNotFoundException e)
{
e.printStackTrace();
}
String first_P= (String) can11.getProperty("First Parameter");
resp.setContentType("text/plain");
resp.getWriter().println("Parameter--- " + first_P);
}
}
The ReceivingData code evidently runs a thread and reads data from 10.9.211.22 port 6870 using Socket from a local computer. That's fine. It converts four bytes to a List and passes that to Receiving_At_Regular_IntervalServlet. Fine but not what you need.
This part might work on a development computer but won't work if deployed to the cloud. AppEngine servers does not permit developers to define main(), use Socket or communicate with private IP subnet 10. Forget about deploying that code to AppEngine.
Receiving_At_Regular_IntervalServlet has a custom constructor. AppEngine does not call your constructor because its servlet code expects only the default constructor. That is probably when your 503 error occurs.
With servlets the data is not supposed to come in via a constructor. Data must come in via members of the request parameter of the doGet method (though to be RESTful you should rather use doPut in this example). You insert the data into the request parameter but sending a correctly constructed http request to the server. Your code lacks that web application design.
Build your main program and your AppEngine code in separate projects and make main talk to servlet using http.
HTTP ERROR 503 error
You can't help anything when a server throws this error. It is only thrown when a service from the server is unavailable.
You need explicit handling on such error codes, other than 200 OK, in the client app and appropriate message has to be shown or as the alternate requirement suggestion.
Refer to:
Status Code definitions
Java - 503 - SC_SERVICE_UNAVAILABLE

Blackberry permissions to connect internet after signing?

While working with Browser Field in Blackberry the code is working when running in simulator before signing. But after signing app is not working, means webpage is not loading.. code is as follows...
code:
public final class MyScreen extends MainScreen
{
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
ButtonField bf = new ButtonField("google");
bf.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
Dialog.alert("this is button click");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
BrowserField browserField = new BrowserField();
add(browserField);
browserField.requestContent("http://www.google.com");
}
}, 2000, false);
}
});
add(bf);
}
}
As per the following code, if i am executing it in simulator before signing working good & website is loading. But after signing my app with signing keys and if i am executing in device, it is not executing means website is not loading, just blank page is displaying.
Not getting what is the problem with my app before & after signing.
After searching in internet, got some information that we need to pass some suffixes to work after signing, in devices when using HTTPconnections like
HttpConnection httpConn;
StreamConnection s;
String url;
s = (StreamConnection)Connector.open(url+";deviceside=true");
But if i am passing the same code in browser field means it is concatenating with the given url like..
browserField.requestContent("http://www.google.com" + ";deviceside=true");
and getting error like unable to find "http://www.google.com;deviceside=true"
so, can anyone please suggest me how to access internet using browser field after blackberry applications are signed.
My app needs to support OS 6.0 & 7.0
try this code -
String url="http://www.google.com";
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent(url);

Categories