How to access a variable stored in an online file - java

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) {}
}

Related

How to parse the object "rates" and get the string "EUR" from this API (picture attached) in my android studio project?

This is the openexchangerate from where I want to parse the EUR Rate
#Override
protected Void doInBackground(Void... voids) {
try {
String uRl = "https://openexchangerates.org/api/latest.json?app_id=9d60a61dd1914783b037cc5835ee9829&symbols=EUR";
JSONObject reader = new JSONObject(uRl);
JSONObject sys = reader.getJSONObject("rates");
EUR = sys.getString("EUR");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
textView.setText(EUR);
}
This is my code to parse the EUR Rate. I used a simple textview in xml to display the rate. But nothing is getting displayed in the emulator. Could someone please help me where I am making mistake?
Screenshot of my emulator
The point is you're trying to parse the API URL to JSON object, instead of the API response.
You should call the API first, then parse the API response to JSON object.
A similar problem has been solved here: Use JSON API in Java
Hope this is helpful.

Best way to get Amazon page and product information

I want to get Amazon page and product information from their website so I work on a future project. I have no experience with APIs but also saw that I would need to pay in order to use Amazon's. My current plan was to use a WebRequest class which basically takes down the page's raw text and then parse through it to get what I need. It pulls down HTML from all the websites I have tried except amazon. When I try and use it for amazon I get text like this...
??èv~-1?½d!Yä90û?¡òk6??ªó?l}L??A?{í??j?ì??ñF Oü?ª[D ú7W¢!?É?L?]â  v??ÇJ???t?ñ?j?^,Y£>O?|?I`OöN??Q?»bÇJPy1·¬Ç??RtâU??Q%vB??^íè|??ª?
Can someone explain to me why this happens? Or even better if you could point me towards a better way of doing this? Any help is appreciated.
This is the class I mentioned...
public class WebRequest {
protected String url;
protected ArrayList<String> pageText;
public WebRequest() {
url = "";
pageText = new ArrayList<String>();
}
public WebRequest(String url) {
this.url = url;
pageText = new ArrayList<String>();
load();
}
public boolean load() {
boolean returnValue = true;
try {
URL thisURL = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(thisURL.openStream()));
String line;
while ((line = reader.readLine()) != null) {
pageText.add(line);
}
reader.close();
}
catch (Exception e) {
returnValue = false;
System.out.println("peepee");
}
return returnValue;
}
public boolean load(String url) {
this.url = url;
return load();
}
public String toString() {
String returnString = "";
for (String s : pageText) {
returnString += s + "\n";
}
return returnString;
}
}
It could be that the page is returned using a different character encoding than your platform default. If that's the case, you should specify the appropriate encoding, e.g:
new InputStreamReader(thisURL.openStream(), "UTF-8")
But that data doesn't look like character data at all to me. It's too random. It looks like binary data. Are you sure you're not downloading an image by mistake?
If you want to make more sophisticated HTTP requests, there are quite a few Java libraries, e.g. OkHttp and AsyncHttpClient.
But it's worth bearing in mind that Amazon probably doesn't like people scraping its site, and will have built in detection of malicious or unwanted activity. It might be sending you gibberish on purpose to deter you from continuing. You should be careful because some big sites may block your IP temporarily or permanently.
My advice would be to learn how to use the Amazon APIs. They're pretty powerful—and you won't get yourself banned.

Display web service results on a form (Codename One)

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

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.

Java Android FTP Upload Issue & "Async"

I am attempting to upload via ftp a file, named "advancedsettings.xml" located in path "/storage/emulated/0/advancedsettings.xml" from my Android device. It doesn't seem to be working; the file does not upload and the following exception is thrown:
01-06 17:56:17.498 28084-28084/com.name.example.appname E/SmsReceiver﹕ android.os.NetworkOnMainThreadException
I discovered that basically, an application cannot attempt to perform a networking operation "on its main thread".
I am new at Java but I understand, following from this, I must implement "ASync"; I haven't understood how to implement it. Could somebody help describe this to me and how I might implement it in respect of the below code?
My code is as follows:
public class FtpUpload {
// use this method to upload the file using file path global var and ftp code,
//then return the link string.
//TO DO: UID file name to prevent file already exists overwrite on server?
public void total() {
FTPClient con = null;
String dest_fname = "advancedsettings.xml"; // Added to create a destination file with a dynamically created name (same as the file name in /sdcard/ftp/)
try
{
con = new FTPClient();
con.connect("ftp.domain.co.uk");
// Check your USERNAME e.g myuser#mywebspace.com and check your PASSWORD to ensure they are OK.
if (con.login("username", "password"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/storage/emulated/0/advancedsettings.xml";
FileInputStream in = new FileInputStream(data);
boolean result = con.storeFile(dest_fname, in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
} else { // This Error Log was created
// Create error log as a file
File log_file = new File("/storage/emulated/0/error.txt");
try {
FileWriter lfw = new FileWriter(log_file);
BufferedWriter lout = new BufferedWriter(lfw);
// Continue
lout.write("Upload Connection Failed!");
lout.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.e("SmsReceiver", e1.toString());
}
}
}
catch (Exception e)
{
Log.e("SmsReceiver", e.toString());
}
}
Thank you in advance.
K
Shamefully I didn't initially come across this documentation on Async Tasks, which has proven invaluable.
With a bit of improv though, I got it working. I just modified my class as such:
private class FtpUpload extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
//code here
}
And used the following to call the above Async method:
new FtpUpload().execute();
Of course, you won't get very far with FTP networking without declaring the following user permissions in your manifest file (outside of the "application" tags):
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Categories