I am new to Android app development and I am stuck at a point where in my app I need to dynamically create class, define its attributes and populate them all dynamically.
This dynamic thing is required because the json file changes every time, a click event is fired and I need to populate a recyclerView, getting header and respective values from that json file.
I have come across few solutions like using javassist library and using hashmap (though I didn't get this one).
Okey I found it.
You want to parse the JSONObject at runtime and get its keys. And you don't know what structure the JSONObject would have.
Just use this Json helper class JSON HELPER
To convert JSONObject use JsonHelper.toMap(JSONObject object) given there.
//Now to get the keys
for ( String key : hashMapObject.keySet() ) {
System.out.println( key );
}
//Here hashMapObject is generated from `JsonHelper.toMap` method.
Just use Retrofit library and everything will get handled automatically and very easily Retrofit
Just follow these steps to use Retrofit
First Download and Integrate Retrofit to your android project.
//In your Gradle file. Add this line.
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
Now suppose you want to implement a Get request from a URL lets say
https://api.github.com/users/{user}/repos.
To get all the repository listed on GitHub. Here {user} will be username
So your base URL here is https://api.github.com and path for
Get Is /users/{user}/repos
Now create an interface.
public interface GitHubService {
#GET("/users/{user}/repos")
Call<List<Repo>> listRepos(#Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com").build();
GitHubService service = retrofit.create(GitHubService.class);
//Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.
Call<List<Repo>> repos = service.listRepos("robinskumar73");
Related
I'm creating a java application that pulls data from facebook videos using RestFB. How can I retrieve the custom labels from each video?
Although I'm able to pull the normal data from each video, there doesn't seem to be any RestFB function that gets custom labels.
I've tried creating my own function by copying the RestFB source code for getting the title and then changing it according to the data I need, but that doesn't seem to work.
The custom labels field is missing atm in RestFB, so you can wait until a new version is released or write a custom video type like this:
public class CustomLabelsVideo extends Video {
#Facebook("custom_labels")
private List<String> customLabels = new ArrayList<>();
public List<String> getCustomLabels() {
return customLabels;
}
public void setCustomLabels(List<String> customLabels) {
this.customLabels = customLabels;
}
}
You need to use this type in the fetchObject method, and don't forget to add the custom_labels string to the fields you fetch.
I'm using the following approach to return a Facebook user's music preferences:
//FIXME: Fetch results in a single operation
val likes = facebook.likeOperations().music
val artists = ArrayList<Artist>()
for (musicLiked in likes)
{
val musicProfile = facebook.fetchObject(musicLiked.id, Page::class.java, "id", "name", "genre");
artists.add(Artist(name = musicProfile.name, genre = musicProfile.genre))
}
The above approach won't scale, since we have an additional network operation for each artist the user likes.
I tried:
I tried using facebook.likeOperations.music however this doesn't fetch genre.
Question:
I would like to use facebook.fetchObject with a query that returns a PagedList. How to do this?
(No need to post example code in Kotlin if you prefer or are more familiar with Java - I'll be happy with information in any language).
Facebook api uses "fields" parameter in requests to return custom fields for objects. This parameter can be also used for liked music rest request.
me/music?fields=id,genre,name
above link will return all liked music with id, genre and name of the artist/group. Unfortunately FacebookTemplate does not have method which will apply for your needs. The method Facebook.likeOperations() returns instance of the LikeTemplate class which has constant PAGE_FIELDS with value
private static final String PAGE_FIELDS = "id,name,category,description,location,website,picture,phone,affiliation,company_overview,likes,checkins";
In above constant you do not have genre field. So you have two ways:
You can simply use facebook rest api with some rest library
You can override FacebookTemplate and return your own implementation of LikeTemplate as result of the likeOperations() method. You implementation of the LikeTemplate class should have different value in mentioned constant (added genre field at the end of the string)
Maybe some one will be more helpful but in my knowledge you do not have other options.
Thanks to advice given in #burovmarley's answer, I inspected the source and came up with:
val music = facebook.fetchConnections(userPage.id, "music", Page::class.java,
PagingParameters(25, 0, null, null).toMap(), "id,name,,genre")
for (musicLiked in music)
{
println("likes: ${musicLiked.name}, genre: ${musicLiked.genre}")
}
This allows using Spring Social Facebook as an unmodified dependency, and without issuing a pull request, which seem to be fairly slow in processing through the queue at the present time.
I am using Parse.com for communicating with iOS application and Web Browser. I have registered in parse.com and created an application. Now I have an iOS application ready to insert an object in that application which is working fine. Now comes the backend part, I am using JAVA for web application. Now,
https://parse.com/docs/api_libraries
According to this link, I can see the API/ Libraries I can use in JAVA is
Almonds
mobile-parse-api
Parse4j
ParseFacade
Among this 4, I have selected Parse4j to build web application with.
I am using Eclipse, I have installed GWT plugin, created a web application. Now I am adding this parse4j.jar file to that project, Added it to the build path also. And then I try to write this code
try {
Parse.initialize("my app id", "my rest app id");
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.save();
return "OK";
} catch(IllegalArgumentException e){
e.printStackTrace();
return "KO";
}
catch(ParseException e){
e.printStackTrace();
return "KO";
}
It doesn't insert the object to parse cloud. Please help why isn't working? Am I missing anything to write?
As far as I see, the code is correct. However, if Parse4j does not save the entry
this means that you write wrong the attribute name or class name. Just check the names
and class name then reply back.
Regards.
One way to validate is the do a Query, get the object and print all the attributes / data types. Then store these as static class level constants and use them throughout your class for setting values in new objects to persist.
If the get query doesn't work (without any filters), which means your class name is incorrect.
Good Luck!
I am not that new to Java Programming, but I have never worked with external libraries etc. Now I want to develop a desktop client for the "Telegram" open-source messaging platform, and I'm stuck when it comes to API-Usage.
There is pretty much documentation about the Telegram API, found at https://core.telegram.org/api, and I've already downloaded mtproto, telegram-api and tl-core from github, and compiled my own library jar from source by using gradle. As well, I've already written a small application, where the user clicks a button and is promted to enter his phone number, I'm using the Java-swing-Libraries and an ActionListener for this.
The phone number entered by the user should now be checked if it is already registered, the auth.checkPhone method seems to be capable for that. But how can I refer to it within my eclipse project? I don't see any method "checkPhone" in any of the classes! What should I do?
Please help me, I can't help myself and I am desperately stuck in my project. Even a small hint would help.
Thanks in Advance,
Lukas
Essentially you will have to fill out the blanks in the code given on GitHub in the ex3ndr/telegram-api repository. If you've got the library Jar file you built and the tl-api-v12.jarfile on your Eclipse project's Java build path, then look at the RPC Calls section of the README and
First you need to set up an AppInfo object with your API credentials, then you will also have to create some new classes that implement the AbsApiState and ApiCallback interfaces. Once these are available, you can create the TelegramApi object and make an RPC call to the Telegram service as follows; in this case using the suggested auth.checkPhone method:
// TODO set up AbsApiState, AppInfo and ApiCallback objects
TelegramApi api = new TelegramApi(state, appInfo, apiCallback);
// Create request
String phoneNumber = "1234567890";
TLRequestAuthCheckPhone checkPhone = new TLRequestAuthCheckPhone(phoneNumber);
// Call service synchronously
TLCheckedPhone checkedPhone = api.doRpcCall(checkPhone);
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
The TelegramApi object represents your connection to the remote service, which is a request response style of API. RPC calls are made via the doRpcCall method, which takes a request object from the org.telegram.api.requests package (the TLRequestAuthCheckPhone type in the example) filled in with the appropriate parameters. A response object (TLCheckedPhone above) is then returned with the result when it is available.
In the case of an asynchronous call the method returns immediately, and the onResult callback method is executed when the result is available:
// Call service aynchronously
api.doRpcCall(checkPhone, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() { }
public void onResult(TLCheckedPhone result) {
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
}
public void onError(int errorCode, String message) { }
});
Or just look at this API https://github.com/pengrad/java-telegram-bot-api
It is really simple to use
My situation - I want to write a feature for an android app using java to pull the the_title() and the_content() fields of the latest post in a specific category of a wordpress site. I don't use wordpress themes - I just use php inserts in my site's html to place various wordpress items in various places on the page.
I have not tried using xml or rss yet, but it seems to me to put extra steps in the process to do something as simple and short as what I want to do.
Using java, can't I call to a specific html file that has php inserts that pull the items I want from the wordpress database - the html pulls all the wordpress data items and the java simply pulls the strings from the html and show in my app?
the_title() and the_content() are PHP functions, so you can't call them from Java per se. You could write a web service that returns these values as JSON, which you can then use in your Android app.
// define hook for ajax functions
function core_add_ajax_hook() {
// don't run on admin
if ( !is_admin() ){
do_action( 'wp_ajax_' . $_REQUEST['action'] );
}
}
add_action( 'init', 'core_add_ajax_hook' );
// function to return latest title and content as JSON
function latest_post() {
// array for values
$json = array();
// get values for JSON array
if (have_posts()) : the_post();
// put values into JSON array
$json['the_title'] = get_the_title();
$json['the_content'] = get_the_content();
endif;
// encode to JSON and return
echo htmlentities(json_encode($json), ENT_NOQUOTES, 'UTF-8');
}
// hook function on request for action=latest_post
add_action('wp_ajax_latest_post', 'latest_post');
You can then get this info by making a request to:
http://yoursite.com/wp-load.php?action=latest_post