Setting background of imageView in RelativeLayout - java

I am setting a background of an imageView of a relative layout using Helper.sync_settting_2(img_sync, context).
try {
final RelativeLayout layout_img_sync = (RelativeLayout) findViewById(R.id.relative_lay_6);
final ImageView img_sync = (ImageView) findViewById(R.id.img_sync);
layout_img_sync.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Helper.sync_settting_2(img_sync, context);
}
});
} catch (Exception e) {
};
Here is the function Helper.sync_settting_2(ImageView sync, Context ct).
public static void sync_settting_2(ImageView sync, Context ct) {
Toast.makeText(ct, "Sync Started", Toast.LENGTH_LONG).show();
getJobData getJobs = new getJobData(null);
sync.setBackground(ct.getResources().getDrawable(
com.org.courier.R.drawable.sync_image_orange));
getJobs.setOnApiLIstner(new onApiCompleted() {
#Override
public void onApiResults(ArrayList<job_entity> events_list) {
getMessageData getMessage = new getMessageData(null);
getMessage.setOnApiLIstner(new getMessageData.onApiCompleted() {
#Override
public void onApiResults(
ArrayList<message_entity> events_list) {
getContactData getContact = new getContactData(null);
getContact
.setOnApiLIstner(new getContactData.onApiCompleted() {
#Override
public void onApiResults(
ArrayList<contact_entity> events_list) {
}
});
getContact.execute();
}
});
getMessage.execute();
}
});
getJobs.execute();
sync.setBackground(ct.getResources().getDrawable(
com.org.courier.R.drawable.sync_image_03));
Toast.makeText(ct, "Sync Finished", Toast.LENGTH_SHORT)
.show();
}
It showing an error
"java.lang.NoSuchMethodError: android.widget,ImageView.setBackground"

View.setBackground wasn't added until API 16. I ran into this issue myself, and couldn't figure out for the life of me why it was happening, since I didn't get any newAPI warnings.
If you want it to be compatible with all versions of Android, you should use:
setBackgroundResource()
or
setBackgroundDrawable()
However, for an ImageView, you should instead be setting the SRC, not the Background:
setImageResource() or setImageDrawable()

Related

Picasso doesn't download Image for First Time hosted on my company server?

When the ImagePager load first time, some times, Picasso call onError, showing the .error drawable. If I press on back button and go back to the Activity that has the ImagePager, Picasso load the picture correctly. If the ImagePager has two or more pictures and I swipe between the pictures, those are loaded correctly some times without exit and reenter to the ImagePager.
It correctly downloads other images from web. The issue arises when I tried to download from hosted company server.
I am using Picasso 'com.squareup.picasso:picasso:2.5.0'.
I also referred to below question but it doesn't help.
First time error loading picture with Picasso
Below is my MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configureToolbar(R.string.select_task);
init();
}
#Override
protected void init() {
//TODO: For QA Testing Purpose, Remove after Testing
mWidthField =findViewById(R.id.edt_txt_1);
mHeightField =findViewById(R.id.edt_txt_2);
mImage=findViewById(R.id.image_view_2);
mImageLoadButton=findViewById(R.id.image_load_button);
item=new Item();
item.setPrimaryImageURL("https://cdn.cnn.com/cnnnext/dam/assets/190119161516-01-trump-government-shutdown-0119-exlarge-169.jpg");
item.setUpc("0001111086751");
Log.d("ImageManager","Main Activity");
new ImageManager(getApplicationContext()).downloadImage(item.getPrimaryImageURL(),item.getUpc()+".jpeg",imageDownloadedCallBack);
mImageLoadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadResizedImage();
}
});
}
//TODO: For QA Testing Purpose, Remove after Testing
ImageManager.ImageDownloadedCallBack imageDownloadedCallBack=new ImageManager.ImageDownloadedCallBack() {
#Override
public void imageDownloadComplete(final Bitmap bitmap, boolean status) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("ImageManager","Image Download CallBack in Main Activity");
mImage.setImageBitmap(bitmap);
}
});
}
};
Below is my ImageManager.java
public class ImageManager {
private final Context mContext;
private int mWidth;
private int mHeight;
public ImageManager(Context mContext){
this.mContext=mContext;
}
public interface ImageDownloadedCallBack {
void imageDownloadComplete(Bitmap bitmap,boolean status);
}
private Target picassoImageTarget(Context context, final String imageDir, final String imageName,final ImageDownloadedCallBack imageDownloadedCallBack) {
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
Thread thread=new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.d("ImageManager","Image DownLoad CallBack");
imageDownloadedCallBack.imageDownloadComplete(bitmap,true);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d("ImageManager","Bitmap Failure");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
public void downloadImage(String url, String id,ImageDownloadedCallBack imageDownloadedCallBack){
// this.imageDownloadedCallBack=imageDownloadedCallBack;
Log.d("ImageManager","Download Image function");
Picasso.with(mContext).load(url).into(picassoImageTarget(mContext,"imageDir", id ,imageDownloadedCallBack));
}
}
Any help would be appreciated.
I found the answer from old post and I implemented this code in MainActivity. And now it is working good.
final Target target = new Target{...};
imageView.setTag(target);
Refer wrb-answer below for the above code:
wrb-answer

Questions about my memory problem for my soundboard android app (E/MediaPlayerNative: error (1, -19))

i have buttons to play sounds, they all works individually, after 14+ uses they dont work anymore if i doesn't restart the app
already tried to mediaplayer.realease after each use, doesnt work, think it is a memory problem dont know how do deal with it
MediaPlayer SonDeadliest
protected void onCreate(Bundle savedInstanceState)
{
boutonDeadliest.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SonDeadliest = MediaPlayer.create(getApplicationContext(),R.raw.themostdeadliestganginuganda);
SonDeadliest.start();
fin(SonDeadliest);
}
});
public void fin(MediaPlayer m)
{
if(m.isPlaying())
{
}
else
{
m.stop();
m.release();
}
}
i have like 24 buttons, i'm trying to get an app with everything that works without having to restart the application thank you :)
The problem is that using MediaPlayer repeatedly in this way can be misleading:
SonDeadliest = MediaPlayer.create(getApplicationContext(),R.raw.themostdeadliestganginuganda);
SonDeadliest.start();
It will consume unnecessary resources.
For a better understanding I suggest that you read this post. It is written using Kotlin but with a little of kotlin study you can understand.
Here is a implementation in Java, trying to use your scenario:
MediaPlayer myMediaPlayer;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Media Player setup
myMediaPlayer = new MediaPlayer();
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
//Buttons
Button button1 = view.findViewById(R.id.button_record1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.record1);
}
});
Button button2 = view.findViewById(R.id.button_record2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.record2);
}
});
}
void playSound(int rawResId) {
try {
AssetFileDescriptor afd = getContext().getResources().openRawResourceFd(rawResId);
if (afd != null) {
myMediaPlayer.reset();
myMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
myMediaPlayer.prepareAsync();
}
} catch (Exception ex) {
Log.d("MediaPLayer", "playSound exception: " + ex.getMessage());
}
}
The code can be improved, but my intention here was just to facilitate the comprehension. I'm using only 2 buttons for simplification. But I suggest you to consider using better solutions instead of creating a listener to each one of the 24 buttons. (Take a look on DataBinding, passing the resource as reference).

How to wait for a AdMob Rewarded Video to Load properly

I am trying to use the AdMob Rewarded Ad in my Android application.
In order to include it in the refered app, I need to wait for the rewarded video to load after the user click the buttom.
I am trying it throughout the code bellow, but I get the error:
java.lang.IllegalStateException: showAd must be called on the main UI
thread.
When the buttom is clicked:
b_r_ans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSomBotaoLigado() && loaded[0])
soundPool.play(soundID, MyApplication.getVolumeBotao(), MyApplication.getVolumeBotao(), 1, 0, 1f);
Toast.makeText(MyApplication.getAppContext(),carregando_rv, Toast.LENGTH_LONG).show();
Thread t_rv = new Thread(new Runnable() {
public void run() {
while(!rv_loaded){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t_rv.start();
try {
t_rv.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
mRewardedVideoAd.show();
}
});
Overrided the listener:
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
rv_loaded = true;
}
Using the mRewardedVideoAd.isLoaded() function triggers the same issue.
How can I wait for the video to load properly?
It appears to happen that you are calling show from a different thread to the UI so I'd try to force its execution on the main thread like:
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
};
mainHandler.post(myRunnable);
You can also disable the button until the ad is loaded, then in the onRewardedVideoAdLoaded function enable the button:
override fun onRewardedVideoAdLoaded() {
ad_btn.isEnabled = true
}
Hope it helps. This is the implementation that I am using.
Solved it through this code:
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
rv_loaded = true;
if(goToAnswers)
mRewardedVideoAd.show();
goToAnswers = false;
}
b_r_ans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSomBotaoLigado() && loaded[0])
soundPool.play(soundID, MyApplication.getVolumeBotao(), MyApplication.getVolumeBotao(), 1, 0, 1f);
Toast.makeText(MyApplication.getAppContext(),carregando_rv, Toast.LENGTH_LONG).show();
if(mRewardedVideoAd.isLoaded())
mRewardedVideoAd.show();
else goToAnswers=true;
}
});
This code will show a ProgressDialog while loading the reward video:
package com.mountzoft.waitForrewardvideoProperly;
import android.app.ProgressDialog;
import android.content.Context;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class MainActivity extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mAd;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Please wait... Loading Reward Video Ad!");
mProgressDialog.setCancelable(false);
}
private final showRewardVideoAd() {
mProgressDialog.show();
initializeRewardVideoAd();
loadRewardedVideoAd();
}
private void initializeRewardVideoAd(){
String adMobAppId = BuildConfig.AD_MOB_APP_ID; //id is stored in build gradle file
MobileAds.initialize(this, adMobAppId);
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(this);
}
private void loadRewardedVideoAd() {
String admobAdUnitId = BuildConfig.ADMOB_AD_UNIT_ID;//id is stored in build gradle
mAd.loadAd(admobAdUnitId,
new AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
mAd.show();
}
#Override
public void onRewardedVideoAdOpened() {
mAd = null;
}
#Override
public void onRewardedVideoStarted() {
mProgressDialog.dismiss();
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted(){
}
}
If you need to wait until rewarded ad loading use SingleLiveEvent. Please refer following code snippet.
private val isRewardedAdLoaded: LiveData<Event<Boolean>>
get() = _isRewardedAdLoaded
private var _isRewardedAdLoaded: MutableLiveData<Event<Boolean>> = MutableLiveData()
I used this is in fragment. So this from onViewCreated()
rewardedAd = createAndLoadRewardedAd()
and I post loading state as following
private fun createAndLoadRewardedAd(): RewardedAd {
val rewarded = RewardedAd(requireContext(), getString(R.string.admob_rewarded_id_test))
val adLoadCallback = object : RewardedAdLoadCallback() {
override fun onRewardedAdLoaded() {
Log.e(TAG, "onRewardedAdLoaded")
_isRewardedAdLoaded.postValue(Event(true))
}
override fun onRewardedAdFailedToLoad(errorCode: Int) {
_isRewardedAdLoaded.postValue(Event(false))
}
}
rewarded.loadAd(Builder().build(), adLoadCallback)
return rewarded
}
this is rewarded ad show method
private fun showRewardedAds(rewarded: RewardedAd) {
rewarded.show(requireActivity(), object : RewardedAdCallback() {
override fun onRewardedAdOpened() {
Log.e(TAG, "onRewardedAdOpened")
}
override fun onRewardedAdClosed() {
Log.e(TAG, "onRewardedAdClosed")
rewardedAd = createAndLoadRewardedAd()
}
override fun onUserEarnedReward(rewardItem: RewardItem) {
Log.e(TAG, "onUserEarnedReward")
translateText()
}
override fun onRewardedAdFailedToShow(errorCode: Int) {
translateText()
}
})
}
Finally I called as following
R.id.btnTranslate -> {
if (rewardedAd.isLoaded){
showMessage(
getString(R.string.translate_ads_show_warning_title),
getString(R.string.translate_ads_show_warning_msg)
)
} else {
progress.setVisible(true)
isRewardedAdLoaded.observe(viewLifecycleOwner, Observer {
it.getContentIfNotHandled()?.let { loaded ->
if (loaded and progress.isVisible){
progress.setVisible(false)
showMessage(
getString(R.string.translate_ads_show_warning_title),
getString(R.string.translate_ads_show_warning_msg)
)
}
}
})
}
}

Image uploading on Facebook

Does anybody have an idea about this website?
I am trying the code provided here, the status uploading looks fine but i can't upload any image seems as if UploadImageAsyn() is not working. Here's my code
public class ShareButtonActivity extends Activity {
// SocialAuth Component
SocialAuthAdapter adapter;
Bitmap bitmap;
// Android Components
Button update;
EditText edit;
ImageView img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img =(ImageView) findViewById(R.id.imageView1);
img.buildDrawingCache();
bitmap = img.getDrawingCache();
// Create Your Own Share Button
Button share = (Button) findViewById(R.id.sharebutton);
share.setText("Share");
// Add it to Library
adapter = new SocialAuthAdapter(new ResponseListener());
// Add providers
adapter.addProvider(Provider.FACEBOOK, R.drawable.facebook);
// Enable Provider
adapter.enable(share);
}
/**
* Listens Response from Library
*
*/
private final class ResponseListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
// Get name of provider after authentication
final String providerName=values.getString(SocialAuthAdapter.PROVIDER);
Log.d("ShareButton", "Provider Name = " + providerName);
Toast.makeText(ShareButtonActivity.this, providerName + " connected", Toast.LENGTH_LONG).show();
update = (Button) findViewById(R.id.update);
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
adapter.uploadImageAsync("Landscape Images", "icon.png", bitmap, 0,new UploadImageListener());
Toast.makeText(getApplicationContext(),"yoohooo ",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(SocialAuthError error) {
Log.d("ShareButton", "Authentication Error: " + error.getMessage());
}
#Override
public void onCancel() {
Log.d("ShareButton", "Authentication Cancelled");
}
#Override
public void onBack() {
Log.d("Share-Button", "Dialog Closed by pressing Back Key");
}
}
// To get status of message after authentication
private final class UploadImageListener implements SocialAuthListener<Integer> {
#Override
public void onExecute(String provider, Integer t) {
Log.d("Custom-UI", "Uploading Data");
Integer status = t;
Log.d("Custom-UI", String.valueOf(status));
Toast.makeText(getApplicationContext(), "Image Uploaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(SocialAuthError arg0) {
// TODO Auto-generated method stub
}
}
}
Every time i click the update button a "no" message is printed on toast. Although the program does not show any error. I would be really greatfull if anybody can help me out on this.

Can't create handler inside thread that has not called Looper.prepare()

I get this error "Can't create handler inside thread that has not called Looper.prepare()"
Can you tell me how to fix it?
public class PaymentActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment);
final Button buttonBank = (Button) findViewById(R.id.buttonBank);
buttonBank.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = ProgressDialog.show(PaymentActivity.this, "",
"Redirecting to payment gateway...", true, true);
new Thread() {
public void run() {
try {
startPayment("Bank");
} catch (Exception e) {
alertDialog.setMessage(e.getMessage());
handler.sendEmptyMessage(1);
progressDialog.cancel();
}
}
}.start();
}
});
StartPayment Method:
private void startPayment(String id) {
Bundle b = getIntent().getExtras();
final Sail sail = b.getParcelable(Constant.SAIL);
final Intent bankIntent = new Intent(this, BankActivity.class);
try {
Reservation reservation = RestService.createReservation(
sail.getId(),
getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
bankIntent.putExtra(Constant.RESERVATION, reservation);
// <workingWithDB> Storing Reservation info in Database
DBAdapter db = new DBAdapter(this);
db.open();
#SuppressWarnings("unused")
long rowid;
rowid = db.insertRow(sail.getId(), sail.getFrom(),
sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
sail.getPrice().toString(), reservation.getId().floatValue());
db.close();
// </workingWithDB>
String html = PaymentService.getRedirectHTML(id, reservation);
bankIntent.putExtra(Constant.BANK, html);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog alertDialog = builder.create();
alertDialog.setMessage(e.getMessage());
alertDialog.show();
}
startActivity(bankIntent);
}
You should know that when you try to modify your UI , the only thread who can do that is the UiThread.
So if you want to modify your UI in another thread, try to use the method: Activity.runOnUiThread(new Runnable);
Your code should be like this :
new Thread() {
public void run() {
YourActivity.this.runOnUiThread(new Runnable(){
#Override
public void run(){
try {
startPayment("Bank");//Edit,integrate this on the runOnUiThread
} catch (Exception e) {
alertDialog.setMessage(e.getMessage());
handler.sendEmptyMessage(1);
progressDialog.cancel();
}
});
}
}
}.start();
I assume you create a Handler in startPayment() method. You can't do that, as handlers can be created on th UI thread only. Just create it in your activity class.
Instead of new Thread() line, try giving
this.runOnUiThread(new Runnable() {
you cant change any UI in thread you can use runOnUIThread or AsyncTask for more detail about this click here
I've found that most thread handling can be replaced by AsyncTasks like this:
public class TestStuff extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonBank = (Button) findViewById(R.id.button);
buttonBank.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new StartPaymentAsyncTask(TestStuff.this).execute((Void []) null);
}
});
}
private class StartPaymentAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog;
private final Context context;
public StartPaymentAsyncTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage(context.getString(R.string.doing_db_work));
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(Void... ignored) {
String returnMessage = null;
try {
startPayment("Bank");
} catch (Exception e) {
returnMessage = e.getMessage();
}
return returnMessage;
}
#Override
protected void onPostExecute(String message) {
dialog.dismiss();
if (message != null) {
// process the error (show alert etc)
Log.e("StartPaymentAsyncTask", String.format("I received an error: %s", message));
} else {
Log.i("StartPaymentAsyncTask", "No problems");
}
}
}
public void startPayment(String string) throws Exception {
SystemClock.sleep(2000); // pause for 2 seconds for dialog
Log.i("PaymentStuff", "I am pretending to do some work");
throw new Exception("Oh dear, database error");
}
}
I pass in the Application Context to the Async so it can create dialogs from it.
The advantage of doing it this way is you know exactly which methods are run in your UI and which are in a separate background thread. Your main UI thread isn't delayed, and the separation into small async tasks is quite nice.
The code assumes your startPayment() method does nothing with the UI, and if it does, move it into the onPostExecute of the AsyncTask so it's done in the UI thread.
Try
final Handler handlerTimer = new Handler(Looper.getMainLooper());
handlerTimer.postDelayed(new Runnable() {
public void run() {
......
}
}, time_interval});

Categories