Picasso Showing the Error Path Must Not Be Empty? - java

I am trying to fetching image from firebase. so when there is no image in firebase i want that my app logo will be set there. but my app is crashing and throwing the error into a log-cat.
I tried using if-else condition. and also on Success and on Error Methods. but did't worked fine.
private static final String Earnings_Freebies = "EARNINGS_FREEBIES";
private Earnings_Freebies list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earnings_freebies);
list = (Earnings_Freebies) getIntent().getExtras().getSerializable(Earnings_Freebies);
if (TextUtils.isEmpty(list.getmImageView())){
m_EF_ImageView.setImageResource(R.drawable.app_logo);
mProgressBarEF.setVisibility(View.GONE);
}
Picasso.with(getApplicationContext())
.load(list.getmImageView())
.into(m_EF_ImageView, new Callback() {
#Override
public void onSuccess() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.GONE);
}
#Override
public void onError() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.VISIBLE);
}
});
I want when there is error. or i forget to put image into firebase then app logo will automatically set into Image-view.

You can try below code. If not helpful then let me know a bit more about Earnings_Freebies model.
Make sure you were using latest dependency of Picasso.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earnings_freebies);
list = (Earnings_Freebies) getIntent().getExtras().getSerializable(Earnings_Freebies);
if (list == null && TextUtils.isEmpty(list.getmImageView())){
m_EF_ImageView.setImageResource(R.drawable.app_logo);
mProgressBarEF.setVisibility(View.GONE);
Picasso.with(getApplicationContext())
.load(R.mipmap.ic_launcher) // can also be a drawable
.into(m_EF_ImageView);
} else {
Picasso.with(getApplicationContext())
.load(list.getmImageView())
.placeholder(R.mipmap.ic_launcher) // can also be a drawable
.into(m_EF_ImageView);
}
}

you can try this way:
private static final String Earnings_Freebies = "EARNINGS_FREEBIES";
private Earnings_Freebies list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earnings_freebies);
list = (Earnings_Freebies) getIntent().getExtras().getSerializable(Earnings_Freebies);
if (list != null && list.getmImageView() != null && !TextUtils.isEmpty(list.getmImageView())){
Picasso.with(getApplicationContext())
.load(list.getmImageView())
.into(m_EF_ImageView, new Callback() {
#Override
public void onSuccess() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.GONE);
}
#Override
public void onError() {
mProgressBarEF.setVisibility(View.GONE);
mFailedImage.setVisibility(View.VISIBLE);
}
});
}else{
Picasso.with(getApplicationContext())
.load(R.drawable.app_logo)
.placeholder(R.drawable.app_logo)
.into(m_EF_ImageView);
}
}

1) Picasso supports both download and error placeholders as optional features.
2) An error drawable will be used in case where there’s a failure in loading the image. In this case the interim placeholder image will be replaced by the error drawable that’s placed inside .error() method, where you can display your app's icon image in case of error.
Picasso.with(this).load("https://someImageURL")
.error(R.mipmap.ic_launcher) // Your app's icon image displayed on error
.placeholder(R.drawable.user_placeholder) // some placeholder image
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Log.d("TAG", "onSuccess");
}
#Override
public void onError() {
Toast.makeText(getApplicationContext(), "An error occurred", Toast.LENGTH_SHORT).show();
}
});

Related

Retrofit throws an error

I've created some Pojo model and I'm getting data from api into my android app. Data should be downloaded on button click.
Here is how I made this:
public class DownloadMain extends Fragment implements Callback<Partner> {
private static final String TAG = DownloadMain.class.getSimpleName();
private Button dloadPartners;
private Call callPartners;
public DownloadMain() {}
public DownloadMain newInstance() { return new DownloadMain(); }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_main, container, false);
dloadPartners = (Button) view.findViewById(R.id.downloadPartners);
dloadPartners.setOnClickListener(btnListener);
callPartners = APIHelper.getApiService().getPartners();
return view;
}
Button.OnClickListener btnListener = (new Button.OnClickListener() {
#Override
public void onClick(View v) {
callPartners.enqueue(DownloadMain.this);
}
});
#Override
public void onResponse(Call call, Response response) {
if(response.body() == null) {
try {
response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "No Partners!", Toast.LENGTH_SHORT).show();
} else {
List<Partner> partners = (List<Partner>) response.body();
Log.d(TAG, "Number of partners received: " + partners.size());
}
}
#Override
public void onFailure(Call call, Throwable t) {
}
}
So problem is here. When I click on button it gives me a notice (toast) "No partners!".
And when I click again it throws me an error:
IllegalStateException: Already executed. at
retrofit2.OkHttpCall.enqueue(OkHttpCall.java:78)
at this line in Button onClick method:
callPartners.enqueue(DownloadMain.this);
I can't figure it out why retrofit is not getting any data.
QUESTION: Could someone help me to resolve this problem?
You can call only once. If you need to do more calls use clone.
From javadoc:
An invocation of a Retrofit method that sends a request to a webserver and returns a response. Each call yields its own HTTP request and response pair. Use clone() to make multiple calls with the same parameters to the same webserver; this may be used to implement polling or to retry a failed call.
Basically the code should be
callPartners.clone().enqueue(DownloadMain.this);

Microsoft translator API , Translate.execute() method not invokes in android

I am trying to make an Android app that will use some API for translation (now I use Microsoft API - microsoft-translator-java-api-0.6.2-jar-with-dependencies.jar )
I have done this for single String, but I want to translate some pdf file. Someone know how can I send PDF to this translator and get it back translated?
public class FirstFrag extends MainNavigation.SectionFrag {
private Button translate;
String translatedText;
public FirstFrag(){
super();
}
public static FirstFrag newInstance(Context c, int section){
FirstFrag ret = new FirstFrag();
ret.setSection(section);
return ret;
}
#Override
public void afterCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.afterCreateView(inflater, container, savedInstanceState);
setContentView(R.layout.first_frag_layout);
translate = (Button) findViewById(R.id.btnProgressBar);
translate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
translate.setEnabled(false);
new TranslateFromBing().execute();
}
});
}
#Override
protected void onRetryClicked() {}
// Async Task Class
class TranslateFromBing extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
Translate.setClientId("MY CLIENT ID");
Translate.setClientSecret("MY CLIENT SECRET");
translatedText = null;
try {
translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
}
#Override
protected void onPostExecute(String file_url) {
Toast.makeText(getActivity().getApplicationContext(), "Translation complete", Toast.LENGTH_LONG).show();
TextView translated = (TextView) findViewById(R.id.translatedText);
if(translatedText != null) {
translated.setText(translatedText);
}
else {
translated.setText("ERROR HERE");
}
}
}
You are invoking execute inside method that is called on UI thread. I dont know this API but it most probably does communicate with server and if it returns data immediately - and not through some kind of callback, then it is probably doing HTTP communication.
This is not allowed under android, you should call this api inside AsyncTask.
Another thing is, You should analyze logcat - it should provide you with additional hints on whats wrong. The fact you call execute inside try/catch is probably because you were getting android.os.NetworkOnMainThreadException.

BitmapFactory.decodeStream() is working without INTERNET PERMISSION

I am supposed to fetch images from internet and display it on my activity.For this i am using asynctask class.I forgot to mention INTERNET permission in my manifest file and the application is running succesfully without giving any exception and is able to fetch all the images on Emulator.
On device it is showing Network error.
My question is why emulator is behaving like this.I am using genymotion emulator (Google Nexus 4)
Code is like:-
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button btnClick = null;
Button btnClick2 = null;
Context context = MainActivity.this;
ImageView imageview = null;
ProgressBar progressBar;
String URL = "http://images.visitcanberra.com.au/images/canberra_hero_image.jpg";
String URLTiger = "http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg";
String URLTree = "http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg";
String URLSky = "http://www.ucl.ac.uk/news/news-articles/1213/muscle-fibres-heart.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick2 = (Button)findViewById(R.id.btnClick2);
imageview = (ImageView)findViewById(R.id.imageview);
progressBar = (ProgressBar)findViewById(R.id.progressbar);
progressBar.setVisibility(ProgressBar.GONE);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnClick:
new ImageDownloader(this).execute("http://stylonica.com /wp-content/uploads/2014/02/nature.jpg");
new ImageDownloader(this).execute(URLTiger);
new ImageDownloader(this).execute(URLTree);
new ImageDownloader(this).execute(URLSky);
break;
case R.id.btnClick2:
new Thread(new Runnable() {
#Override
public void run() {
btnClick2.post(new Runnable() {
#Override
public void run() {
btnClick2.setText("Thread B");
}
});
}
}).start();
break;
}
}
public class ImageDownloader extends AsyncTask<String,String,Bitmap> {
ProgressDialog progressDialog;
Context context;
Bitmap bitmap;
public ImageDownloader(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// progressDialog = ProgressDialog.show(context,"Loading Image ","Please wait....");
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... args) {
try {
Log.d("new URL(args[0]..............", new URL(args[0]) + "");
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap image) {
if(image != null){
imageview.setImageBitmap(image);
// progressDialog.dismiss();
progressBar.setVisibility(ProgressBar.INVISIBLE);
}else{
// progressDialog.dismiss();
progressBar.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(context, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
And I have not mentioned INTERNET permission in my manifest file.
Disclaimer: I work on Genymotion.
The answer is that it is a Genymotion bug. :(
Android API compliance is absolutely fundamental for Genymotion.
Please, accept our apologies for the time you lost on this.
We investigated this bug immediately and fixed it.
You will have the fix in our next release.
The problem only happen on version 2.3.7, 4.1.1 et 4.2.2.

AsycTask Throwing IllegalStateException - Fragment Not Attached To Activity

I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.
public class NotificationsPreferenceFragment extends PreferenceFragment {
private static Context context;
public NotificationsPreferenceFragment() {
}
public NotificationsPreferenceFragment(Context context) {
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
getPreferenceManager().findPreference(getString(R.string.send_all_notifications))
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
class NotificationSendTask extends DialogAsyncTask {
public static final String TAG = "NotificationFragment";
public NotificationSendTask(Activity activity, String dialogMsg) {
super(activity, dialogMsg);
}
#Override
protected String doInBackground(String... params) {
String url = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.notification_web_service_url), getString(R.string.default_notification_web_service_url));
if (NetworkingHelper.isNetworkAvailable(getActivity())) {
NotificationDao notificationDao = new NotificationDaoImpl(DatabaseManager.getInstance(getActivity().getApplicationContext()), getActivity().getApplicationContext());
List<Notification> unsentNotificationList = notificationDao.findAllNotSent();
if (unsentNotificationList.size() != 0) {
NotificationSenderTask ns = new NotificationSenderTask(url, context);
try {
if (ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (unsentNotificationList)).get()) {
return getString(R.string.success);
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(TAG, e.getMessage());
}
return getString(R.string.failed_to_send_notifications);
} else {
return getString(R.string.no_notifications_to_send);
}
} else {
return getString(R.string.no_connection_notifications);
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null && dialog.isShowing()) {
dialog.hide();
}
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
}
NotificationSendTask notificationSendTask = new NotificationSendTask(getActivity(), "Sending unsent notifications...");
notificationSendTask.execute();
return true;
}
});
getPreferenceManager().findPreference(getString(R.string.export_notifications)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
NotificationExportTask notificationExportTask = new NotificationExportTask(NotificationsPreferenceFragment.this.getActivity(), 1);
notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
}
I am getting the following exception:
java.lang.IllegalStateException: Fragment NotificationsPreferenceFragment{416092f8} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:741)
at android.app.Fragment.getString(Fragment.java:763)
Can someone please explain to me why this is happening and suggest ways to fix this issue?
UPDATE:
Here is the code for the Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
Since you are performing background task in your app. there is no guarantee that user will stay on same screen until task finishes so if user navigates to other screen or presses home button before task is completed; your fragment is detached from activity. So always make sure that you have fragment attached with the Activity.
try checking with
if (isAdded) {
//Do your UI stuff here
}
add above check wherever you get callback
Move your code from onCreate to onActivityCreated instead of trying to getActivity # onCreate.
That's because the fragment can be created when the activity is not yet ready, that's when you are trying to use it.
That is of course if you are adding the fragment to an activity like:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();

YouTube API does not play videos as expected

I'm attempting to build a very simple video player using the Youtube API for Android. So far I have one video (which can be clicked and played) and two thumbnails below it - my problem is: I need to figure out how I can (correctly) assign different videos to each thumbnail - then play them.
I've attempted assign the thumbnails so using:
public static final String VIDEO1_ID = "HNtBphqE_LA";
public static final String VIDEO2_ID = "YWteQj_q3Ro";
public static final String VIDEO3_ID = "Ak--L4bYly0";
But for some reason I get the correct thumbnail displayed and video played for both youTubeThumbnailLoader1 and youTubeThumbnailLoader2.
Any suggestions? I simply need to tweak/modify the code below to show unique videos/thumbnails (instead of the same one repeated multiple times as it is now) and play them.
Screenshot
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
youTubeThumbnailView1 = (YouTubeThumbnailView)findViewById(R.id.youtubethumbnailview1);
youTubeThumbnailView1.initialize(API_KEY, this);
youTubeThumbnailView2 = (YouTubeThumbnailView)findViewById(R.id.youtubethumbnailview2);
youTubeThumbnailView2.initialize(API_KEY, this);
youTubeThumbnailView1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(youTubePlayer != null){
youTubePlayer.play();
}
}});
youTubeThumbnailView2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(youTubePlayer != null){
youTubePlayer.play();
}
}});
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
youTubePlayer = player;
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView,
YouTubeInitializationResult error) {
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {
youTubeThumbnailLoader1 = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
youTubeThumbnailLoader1.setVideo(VIDEO1_ID);
youTubeThumbnailLoader2 = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
youTubeThumbnailLoader2.setVideo(VIDEO2_ID);
}
private final class ThumbnailLoadedListener implements
YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onThumbnailError(YouTubeThumbnailView arg0, ErrorReason arg1) {
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView arg0, String arg1) {
}
}
}
P.S.
I think this may have to do with the fact I'm using youTubeThumbnailView1 and youTubeThumbnailView2 to create multiple thumbnails - however I have a feeling this might not be the correct way of doing so.
You didn't set the right video for your thumbnails. There is no difference inside each thumbnailView clickListener!
try something like this in your onCreate
public void onCreate(Bundle icicle){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
youTubeThumbnailView1 = (YouTubeThumbnailView)findViewById(R.id.youtubethumbnailview1);
youTubeThumbnailView1.initialize(API_KEY, this);
youTubeThumbnailView2 = (YouTubeThumbnailView)findViewById(R.id.youtubethumbnailview2);
youTubeThumbnailView2.initialize(API_KEY, this);
youTubeThumbnailView1.setOnClickListener(new OnClickListener(){
if(youTubePlayer != null){
youTubePlayer.loadVideo(VIDEO1_ID)
youTubePlayer.play();
}
});
youTubeThumbnailView2.setOnClickListener(new OnClickListener(){
if(youTubePlayer != null){
youTubePlayer.loadVideo(VIDEO2_ID)
youTubePlayer.play();
}
});
}
Note: I see a lot of messy stuff in your code.
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {
youTubeThumbnailLoader1 = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
youTubeThumbnailLoader1.setVideo(VIDEO1_ID);
youTubeThumbnailLoader2 = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
youTubeThumbnailLoader2.setVideo(VIDEO2_ID);
}
This part shows that you lack basic understanding of programming. You could simply just write:
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
thumbnailLoader.setVideo(VIDEO1_ID);
thumbnailLoader.setVideo(VIDEO2_ID);
}
which is clearly not what you intended. I guess you have to create different Listeners in your onCreate. Dont pass this inside the initialze method of your thumbnailViews and make the same switch I show you for the clickListener.
Also Try to nail down the problem you have and post only relating stuff.

Categories

Resources