I am trying to learn about developing android TV apps and looking at sample code on github and on some tutorial links. I have grasped some basics around android TV development.
My problem is non of the tutorials properly explain how the browse fragment is populated with data from an online json source and how it is updated.
Can anyone please direct me to a link or source that can be used as a decent tutorial for a beginner?
I don't think there are any tutorials specifically for LeanBack, but you can probably find plenty of general android tutorials on how to use Retrofit to fetch json formatted data from a public API.
As for populating your BrowseFragment, something like this should do it:
//Create a rows adapter for your fragment
ArrayObjectAdapter mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
setAdapter(mRowsAdapter);
//Create a row and populate it
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(someItemPresenter);
listRowAdapter.setItems(someItems, someDiffCallback);
ListRow row = new ListRow(listRowAdapter);
//Add row
mRowsAdapter.add(row);
someItems should be a List of your fetched items. someItemPresenter should be a class that extends Presenter and handles items of the type contained in the someItems list. someDiffCallback should be a DiffCallback.
Related
I'm looking for an example on how to display points of interest (saved in fusion tables) on a google map.
To do this in html and javascript it's quite trivial, check my javascript map with fusion tables example
See Fusion Tables page containing my POIs
My goal/question is how (need help in coding it) to achieve the same in an Android app. I'm new to android development and I already invested hours for the basics and checking documentation and examples.
Check this very good Google Maps example for Android I've found to get started (my test app is based on this code).
Fusion Tables v2 reference (points to google api client)
Google API Java client samples on github (most outdated: examples on v1)
So far I achieved to display a map centered on my last known location and to show a marker on it.
Because I couldn't find good examples for this, I decided to publish and share my findings, see: firepol / android-google-maps-fusion-tables on github
Now I'd like to show markers coming from fusion tables.
I'm stuck at executing the request, which I try to do via google api client.
Google API client example for Android
ActivityFeed feed = listActivities.execute();
Here my code (which I've put inside onCreate):
protected void prepareFusion() {
// Normally READONLY should be enough (see credential with one scope), but I checked online a console
// and I could see a public table only if I would grant both permissions
List<String> scopes = new ArrayList<>(Arrays.asList(FusiontablesScopes.FUSIONTABLES, FusiontablesScopes.FUSIONTABLES_READONLY));
credential = GoogleAccountCredential.usingOAuth2(this, scopes);
//credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(FusiontablesScopes.FUSIONTABLES_READONLY));
// TODO : get account name automatically
// http://stackoverflow.com/questions/35789071/getting-the-gmail-id-of-the-user-in-android-6-0-marshmallow
credential.setSelectedAccountName("YOUR_GOOGLE_ACCOUNT");
client = new Fusiontables.Builder(
transport, jsonFactory, credential).setApplicationName("TestMap/1.0")
.build();
try {
String tableId = "1774o_WcrqSQlepLXlz1kgH_01NpCJ-6OyId9Pm1J";
Fusiontables.Query.Sql sql = client.query().sql("SELECT FileName,Name,Location FROM " + tableId);
//sql.execute();
//java.lang.IllegalStateException: Calling this from your main thread can lead to deadlock
Fusiontables.Table.Get table = client.table().get(tableId);
table.setFields("items(FileName,Name,Location)");
//table.execute();
// TODO : can't execute like this on main thread as the documentation example "suggests"
//https://developers.google.com/api-client-library/java/google-api-java-client/android
} catch (IOException e) {
e.printStackTrace();
}
}
If I try to do the same and call sql.execute() or table.execute() I get:
java.lang.IllegalStateException: Calling this from your main thread
can lead to deadlock
So I'm kinda stuck here and I'd like to know how to proceed from somebody who has experience with the google api client, even better if you can help me to get the result on the map! Thank you.
How to display the fusion tables POIs on the map?
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker to Zurich Oerlikon and move the camera
mMap.addMarker(new MarkerOptions().position(mDefaultLatLng).title("Zurich Oerlikon"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
mDefaultLatLng, 13));
// TODO: add fusion tables POIs
}
To see where I'm stuck and help me, clone my github repo firepol / android-google-maps-fusion-tables on github, open it in Android Studio, add your own Google Maps API Key and debug on your device. Thanks for your constructive comments, answers and help. Feel free to push on github as well.
In android networks calls are never made on UI/main thread.
Try using an async task if you just want to see things working or import a networking library like volley/robospice if you are developing a full project.
This commit implements the fusion tables query and shows the resulting POIs on google maps
Explanation: GoogleAccountCredential was wrong and had to be replaced with GoogleCredential. To make this work you need to create a service account, role project > service account actor (generate a private key), download the json file and place it under app/res/raw/service_account_credentials.json (in my commit I refer to this file with this precise name, but feel free to raname it and adapt the code to your needs).
Make sure to enable the Fusion Tables API in the API Manager for your project.
I implemented also a class deriving from the AsyncTask to solve the problem of the main thread.
There is some little refactoring in the commit (Location changed to LatLng) but that's it.
Whoever needs to make an android app and place fusion tables POIs on a google map can clone the github repo and have something to begin with (which was also the initial idea of my question).
i have a lot of recycler views, they all use the same adapter, i used to update them with arraylists of objects that id make as i went like this
ADAPTER
private List<CardWriter> cardMakerList;
public CardAdapter(List<CardWriter> cardMakerList){
this.cardMakerList = cardMakerList;
// this.mContext = context;
}
ACTIVITY
public List<CardWriter> cardMakerList = new ArrayList<>();
public CardAdapter cardAdapter;
recyclerView.setAdapter(cardAdapter);
CardWriter cardWriter = new
CardWriter(getResources().getDrawable(R.drawable.happy),"HAPPY","happy ");
cardMakerList.add(cardWriter);
THE PROBLEM
Ive now switched to using databases for each recycler view (using greenDao see this question) so my adapter now uses the below code (addNewCard refers to the generated java class made by greendao)
public List<addNewCard> leaseList = new ArrayList<>();
but now to get my second database(2) its the exact same properties but greendao makes a different file so i should use this in my adapter
public List<addSimpleCard> leaseList = new ArrayList<>();
but this would mean a new adapter for every database and im going to need a lot of them. All the databases im making are just lots of the same object with different properties (an image and 2 strings) but each database needs to be managed individually.
my last question (in the link above) asks how i can make all the same databases with a different title which i think would also solve my problem.
WHAT IVE TRIED
I've tried just creating an static reference to the array list and passing it the new one eg:
public static CardAdapterDB cardAdapterDB;
cardAdapterDB = new CardAdapterDB(leaseList);
this works but trying to change it for a new database
cardAdapterDB = new CardAdapterDB(simpleleaseList);
gives me an error
CardAdapterDB(java.util.List<greendao.addNewCard>) in CardAdapterDB cannot be applied to (java.util.List<greendao.addSimpleCard>)
addSimpleCard is the name of my other java file generated by greendao so this makes perfect sense but how can i get around this without creating loads of new adapters and switching them all the time?
since asking this ive tried multiple ways to get this to work but have yet to find something suitable
Android platform is really fun to work with especially when it comes to resolving issues. Indeed, there is possibly everything there is to know about Android development on the internet.
Alright, I've been searching for about a week and haven't found anything that was close from working. Let's dive into it.
We are building an Android Application that requires a read/write access to existing Contacts on a device. It has become really easy to read a contact's set photo using this method :
// Returns a stream reading a contact thumbnail
public InputStream getContactThumbnail(int id) {
// Stream reading contact image
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(
context.getContentResolver(),
ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id
)
);
// If image is null, try to read Facebook image
if (stream == null) {
stream = new ByteArrayInputStream(getFacebookPhoto(id));
}
return stream;
}
Now, the previous method receives an id as a parameter and returns a Stream making it possible to read the contact's thumbnail. It is needed to be a stream because the phone acts like a web server and has multiple threads running. If a thumbnail is requested several times in the same short time lapse, an OutOfMemoryException will be thrown for sure.
I need to correctly implement the getFacebookPhoto(int) method so that it returns whatever stream reading the Facebook profile picture of a contact that has his or her contact linked with his or her respective Facebook profile. I've tried and failed so many times.
Hypothesis #1
If a contact is linked with a Facebook profile, it has to have the Facebook ID saved somewhere. If this information is accessible, it would make it easy to get a Facebook profile picture using graph. Problem is an internet connection is needed to do so.
Hypothesis #2
Facebook thumbnails are saved somewhere on the SD card. Maybe there's a link between a Contact and those files that can be found through an SQLite request?
Hypothesis #3
sigh, I look desperate. Okay, if I understood correctly, a phone Contact and a Facebook Contact are not the same things in the database. If you query all the contacts from the following URI :
*ContactsContract.Contacts.CONTENT_URI*
you only get contacts that you created and nothing regarding Facebook links. Is there a way to find all linked contacts and get their respective photos?
Conclusion
Yeah, that's about is. To sum it up, I need to read all contacts information. For each contact, I have to find its photo. If the user has not set a picture to a contact that is linked to a Facebook profile, the profile picture which it was linked too must be read.
Up until now, the StackOverflow community has been of a great help and saved my life and job countless times. It is possible, I've seen it in other apps.
Thank you for spending of your time, it is truly appreciated.
EDIT
Let's not give up! I will start a 100pts bounty as soon as I can.
Your hypothesises are right to a certain extend. In contact application this things are handled as folows -
Device's Contact & its Facebook account are mapped by Contact's _ID & Facebook's id, this is one-to-one mapping. So from this mapping first you have to find out the Facebook id
of the conserned contact. But in which table this info is stored & wheather that table is eposed to you or not, URL to that table completely dependent on vendors.
From Facebook Id we can get corresponding profile image either from Facebook's server or from Media DB, if it is also cached in.
But this is not supported by all OEMs. And implementation varies from OEM to OEM as Google don't enforce for any common standard implementation of it.
So there is no garantee that a single implementation will work for all devices from different OEMs.
You should really go and play around with Graph Explorer on the Facebook Developers site it will help you a lot in figuring out what you need to do to get certain things. In order to get the picture for an person you just have to do is do a simple GET HTTPRequest with the graph path of /ID?fields=picture (where ID is the facebook id of the contact) which will return a JSON object that contains the link to that person's profile picture. From there it should be fairly simple for you to get the image.
You can also do the same thing to get all of a person's friends with the picture information by sending a GET request to /me/friends?fields=picture. It seems like you are trying to avoid a web connection but if the android contacts do not store the facebook id then you will have to get the ids yourself I'm afraid.
Hope that helps.
Why don't you use FQL, for Android you can use -
String query = "SELECT uid, name, pic, pic_small, pic_big FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
mAsyncFacebookRunner.request(null, params, new CustomRequestListener());
where CustomRequestListener() extends RequestListener in the Facebook Android SDK.
i'm pretty new to android programming and i'm try to read an xml file. that all works fine, and i can see in the logCat that he is receiving all the data but the app only shows 5 of the tag from the xml file. so i was wondering if i could add some sort of string that will add a new textView/listView or what ever view i need.
There is a good Android API guide on this:
http://developer.android.com/guide/topics/ui/layout/listview.html
I am developing an android project in which I have to load from group of String arrays(say title,description,id) to the listview item TextView.
I did something similar with a database using a cursor like this
String[] from = new String[]{"medicine","healthsystem"};
int[] to = new int[] {R.id.textlist1,R.id.textlist2};
// Now creating an array adapter and set it to display using my row
SimpleCursorAdapter notes =new SimpleCursorAdapter(this,R.layout.notes_row, c, from, to);
I listed all the targets in "from" and all the origin in "to".
Now my problem is I don't have a database so cant use a cursor.
I have 3 arrays of strings which i want to load into textviews(title,description,id) of each item
How to do this
Please kindly help me out
thank you :)
If you don't have a cursor, why are you using a SimpleCursorAdapter?
Read this article about creating a SimpleListView using SimpleAdapter for alternate ideas.
There are lots of examples of populating lists from various data sources in the ApiDemos project that comes with the Android SDK - browse through those, and you should find one that fits what you're trying to do.
First of all you need to create a Class that holds that information, something like:
public class StringHolder{
String titte;
String description;
int id;
}
Then you create the layout of your row that says where you want your title, your description and your image.
Then you create an Adapter. The adapter will hold your data and will say for each position in the list what information should be loaded.
At last you need to use your adapter in an activity.
For more information you can see a tutorial here: http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/