I'm starting to learn how to build an Android TV for the first time so I apologize for a likely obvious answer to this question. Basically, I'm trying to replicate how the Android TV Youtube App displays when there is no internet connectivity as shown:
YouTube shows the main fragment (I believe) in the back with no videos, and there seems to be a transparent overlay with an ImageView, TextView, and Button. Once there is internet connectivity and the user taps the Retry button, it loads the video content and the overlay disappears.
I'm trying to achieve this exact same technique, and with internet connectivity, I currently have this:
With no internet connectivity, I'd like to show something similar to how YouTube does.
Here's some of my basic code:
MainActivity.java:
public class MainActivity extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_browse_fragment"
android:name="com.ui.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ui.MainActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />
MainFragment.java:
public class MainFragment extends DetailsFragment
{
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setupUIElements();
setupThings();
}
public void setupThings()
{
if (isOnline() == true)
{
prepareBackgroundManager();
loadRows();
setupEventListeners();
}
else
{
// I don't know what to do here???
}
}
public Boolean isOnline()
{
try
{
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
return reachable;
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
Simple, if there's internet connection, I load the videos from online, otherwise, I inform the user like YouTube does.
Where I'm stuck is in the else statement. I'm not sure exactly what to create there to achieve this overlay.
I've looked at some solutions regarding switching fragments here:
Switching between Fragment view
How to switch between fragments during onclick?
However, I'm not sure if, for my purpose, I would need to do this?
Can someone point me in the right direction? I'm not looking to have someone write the whole code exactly like the YouTube app, but I'd like to have a small sample, with just maybe a Button or TextView? This will allow me to follow the structure and modify it to meet my requirements.
Thanks.
You can look at the Leanback Sample app, which contains an example of a BrowseErrorFragment.
To display:
BrowseErrorFragment errorFragment = new BrowseErrorFragment();
getFragmentManager().beginTransaction().replace(R.id.main_frame, errorFragment)
.addToBackStack(null).commit();
Related
I am currently making a chat app and i want to add a feature like telegram. As you can see here, there is a animation in the recycler view as if i=t zooming or decreasing its size. You can also notice that animation while opening and closing the navigation drawer. I too tried to do that using this but i get no animation in the recycler view. See this. Actually not this but like this. I took this gif from the README of the repo. So is that possible? If so, can you please tell me a simple implementation ?
Thanks in advance and i will be waiting 😀
Add overridePendingTransition in onBackPressed() method:
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(0, R.anim.slide_out_right);
}
res->anim->slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="#android:integer/config_mediumAnimTime"
android:fromXDelta="0"
android:toXDelta="100%p" />
</set>
To me it looks like an Activity transition where the translateZ value is modified. But since the Telegram Android client is open source, we can just take a look at it.
It looks like the Telegram devs use a lot of custom code instead of relying on the android SDK.
The DialogsActivity which extends a BaseFragment but is neither an Android Activity nor an Android Fragment since BaseFragmentdoesn't extend any of them, has the following method for the transition:
private void setSlideTransitionProgress(float progress) {
if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
return;
}
slideFragmentProgress = progress;
if (fragmentView != null) {
fragmentView.invalidate();
}
if (filterTabsView != null) {
float s = 1f - 0.05f * (1f - slideFragmentProgress);
filterTabsView.getListView().setScaleX(s);
filterTabsView.getListView().setScaleY(s);
filterTabsView.getListView().setTranslationX((isDrawerTransition ? AndroidUtilities.dp(4) : -AndroidUtilities.dp(4)) * (1f - slideFragmentProgress));
filterTabsView.getListView().setPivotX(isDrawerTransition ? filterTabsView.getMeasuredWidth() : 0);
filterTabsView.getListView().setPivotY(0);
filterTabsView.invalidate();
}
}
I'm trying to embed a Youtube video in a WebView, and I want to support Android version 2.
Since Google owns both Android and Youtube, I thought it would be easy, but apparently it's not. I've seen similar questions but they didn't help.
On Android 2.1 when I tap the play button, I have the message "An error occurred, please try again later."
On Android 2.3 I have player buttons but the video does not start.
Here is my code:
public class YoutubeActivity extends Activity {
private WebView webView;
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
webView = new WebView (this);
setContentView (webView);
webView.getSettings ().setJavaScriptEnabled (true);
webView.setWebChromeClient (new WebChromeClient ());
webView.setWebViewClient (new WebViewClient () {
public boolean shouldOverrideUrlLoading (WebView view, String url) {
view.loadUrl (url);
return true;
}
});
if (Build.VERSION.SDK_INT < 8) {
webView.getSettings ().setPluginsEnabled (true);
}
else {
webView.getSettings ().setPluginState (PluginState.ON);
}
webView.loadUrl ("http://youtube.com/embed/NAg4qXsk99c?rel=0");
}
protected void onPause () {
super.onPause ();
webView.loadUrl ("about:blank");
}
}
I also added android:hardwareAccelerated="true" in AndroidManifest.xml.
The Youtube Android Player API is not an option for me because I also want to support platforms without the Youtube app (like Amazon, Blackberry...).
I also tried with RTSP links but the quality is too bad.
Thanks for your help.
I'm trying to create a simple app that loading photos from a website (like 9gag). I'm using jSoup and asyncTask. The problem is when I'm running the app it shows me only the urls of the images.. what can I do in order to display the image in the listView and not the urls.
XML Prob? Help :-/
![Screen Shot]https://www.dropbox.com/s/moybisjrbdgzjre/Screenshot_2013-04-29-20-09-13.png
here's my LoadImages class:
public LoadImages(ArrayList list, ArrayAdapter adapter)
{
this.list = list;
this.adapter = adapter;
}
#Override
protected Elements doInBackground(String... params) {
org.jsoup.nodes.Document doc = null;
try
{
doc =Jsoup.connect("http://mongol.co.il/").get();
return doc.select("img");
}
catch (IOException e1)
{
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Elements result) {
super.onPostExecute(result);
int flag=0;
//Bitmap bitmap = null;
for ( org.jsoup.nodes.Element div : result )
{
String bla = div.absUrl("src");
list.add(bla);
flag++;
if(flag==3)
break;
}
adapter.notifyDataSetChanged();
}
Here's also my .xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
Thanks In advance!
You're only fetching the URLs at this point. You need to fetch the actual Bitmap data in order to show images. There are two ways to do this:
Download all the images, then show the list after everything is fetched
Show the list immediately with image placeholders, the fetch the images as they're
needed
In general, it's a better experience to respond quickly by showing what you have as you get it (option #2). A ListView is really conducive to this model. In the getView() method of the adapter you'll show the placeholder image while firing off an AsyncTask to get the bitmap. You'll then set Image in onPostExecute. Unfortunately things get messy with View recycling. This basic implementation will result in the wrong image being shown in many cases and a totally unresponsive device if the user scrolls back and forth quickly.
Fortunately, these are problems that others have solved. In fact, there is an excellent set of tutorials along with sample code on Android Developer website.
I have done something like this:
I have a DB with ID, image URL, image URI
image URI is something like file:////mnt/sdcard/<your package>/images/image1.png
I have a place Holder image for each row and in my Arraylist i have put image URI in Arraylist. then in getView method check if that URI file exists or not if not then send a broadcast to download that image(with ID). In downloader I fetch images with corresponding URL.
How to check URI exists: create a file object with URI and call isExists()
How to send broadcast: create an intent put ID in extras then call sendBroadcast(intent)
Now how to refresh list after image has been download: Send another broadcast from onPostExecute() to refresh list and catch that broadcast in your activity and call list.notifyDatasetChanged().
You are adding String to the list
String bla = div.absUrl("src");
list.add(bla);
You need to create custom adapter (for the ListView), which will take that String bla and download the image.
Try this tutorial
I am a beginner in developing and I know the question may sounds very basic but, let me cut to the chase: here is my class
public class MainActivity extends Activity {
private ListView lvPhone;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPhone = (ListView)findViewById(R.id.listPhone);
List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_blah", "384765345667", "something#someprovider.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_blah", "34856834796", "something#someprovider.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_name", "868734633", "something#someprovider.com"));
PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
}
}
and here I'd like it to be "attached" so then when the button is clicked the phone book comes up.
public void addListenerOnButton(){
imageButton = (ImageButton) findViewById(R.id.pb_button);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(MyAndroidAppActivity.this,//phone_book goes here
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();//no toaster instead
}
});
}
Would any of you please help? This is going to be really helpful for me. And please if you do answer, try to explain as you're explaining to a "Java_moron" :) (as through as possible please)
[Now I did try the chat room, no reputation point so that didn't happen and I tried to google as much as possible couldn't find anything helpful; maybe there was answer but my lack of knowledge failed me.]
Thank you,
[EDIT: Or instead of using the phone book class, how can I call contacts from phone's native contact list? Anything would be helpful really.]
The best option to start would be to activate a native activity that will bring up phone book contacts and show them to the user as a list. Selected contacts is then passed to starting activity.
Explanation:
You can learn how to start an activity and receive result from the following link:
http://developer.android.com/training/basics/intents/result.html
Basically the main code do that is as follows:
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new Uri("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
Note that the user will be calling the startActivityForResult method this will start a new activity and once that activity is finished the System will call onActivityResult() method of the original Activity and here you will receive results to which contacts has been selected.
I'm creating android app that has table layout for the main activity, and that part works perfectly... Now, the idea was to add another part of an app below the existing components, but now I have to put a tabbed layout there. Well, that part also works perfectly when I try to run just that. But what do I have to do to mix those two in such a way that these two show up one below another on the very same screen.
My main code is:
package my.android;
import android.os.Bundle;
public class MyActivity extends FragmentActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
I have different layout files for all the tabs and I have my TabsActivity class I have created following the tutorial here:
http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/
So how do I add some TabsActivity ta object to the MyActivity? And it is important to be below the content of this. Thaks in advance...
Ideally this would be done using nested Fragments, but Android doesn't support that yet. That leaves the deprecated ActivityGroup class. You'll need a top level activity that extends ActivityGroup and launches the two activities.
Here is how you launch the activities and get their views:
final Window w = getLocalActivityManager().startActivity(myTag, myIntent);
final View wd = w != null ? w.getDecorView() : null;
if ( null != wd ) {
wd.setVisibility(View.VISIBLE);
wd.setFocusableInTouchMode(true);
}
// TODO: Attach wd to a ViewGroup.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Edit: Below is a more complete solution.
This is the layout for the top level activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
Here is the top level class:
public class EmbeddedActivityParent extends ActivityGroup {
private LinearLayout mRootLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mRootLayout = (LinearLayout) findViewById(R.id.root_layout);
// Add embedded status activity.
embedActivity("StatusColumn", new Intent(this, StatusActivity.class));
// Add embedded work activity.
embedActivity("WorkArea", new Intent(this, MainActivity.class));
}
private void embedActivity(String myTag, Intent launchIntent) {
final Window w = getLocalActivityManager().startActivity(myTag, launchIntent);
final View wd = w != null ? w.getDecorView() : null;
if ( null != wd ) {
wd.setVisibility(View.VISIBLE);
wd.setFocusableInTouchMode(true);
mRootLayout.addView(wd);
}
}
}
You can add as many embedded activities as you want. You can even nest embedded activities, but be aware that performance could become a factor. We use this to support a dynamic status column.
Personally, I think there is still a use for the ActivityGroup and hope that Gooogle changes their mind about deprecating it.