Mopub: integration with the Millennial Media native ads adapter - android

Does anyone know how to integrate the Millennial Media native ads adapter?
I read this page: https://support.millennialmedia.com/hc/en-us/articles/205081010-MoPub-Integrations
Downloaded the android adapters and then replace the APID with my APID, but don't know what the DCN is and I was unable to find it on their site.
I think I'm getting the error below because I have not inputted the DCN:
03-24 22:07:12.832 29491-29491/? D/MoPub: Attempting to invoke custom
event: com.mopub.nativeads.MillennialNative 03-24 22:07:12.850
29491-29491/? V/MoPub: Native Ad failed to load with error:
CustomEventNative was configured incorrectly.. 03-24 22:07:13.328
29491-29491/? D/MoPub: Attempting to invoke custom event:
com.mopub.nativeads.MoPubCustomEventNative
This is their adapter I'm using the Millennial Media:
package com.mopub.nativeads;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import com.millennialmedia.AppInfo;
import com.millennialmedia.MMException;
import com.millennialmedia.MMSDK;
import com.millennialmedia.NativeAd;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.mopub.nativeads.NativeImageHelper.preCacheImages;
public class MillennialNative extends CustomEventNative {
public static final String DCN_KEY = "dcn";
public static final String APID_KEY = "XXX";
private final static String LOGCAT_TAG = "MoPub->MM-Native";
private static final Handler UI_THREAD_HANDLER = new Handler(Looper.getMainLooper());
public String siteId;
#Override
protected void loadNativeAd(final Activity activity,
final CustomEventNativeListener listener,
final Map<String, Object> localExtras,
final Map<String, String> serverExtras) {
String placementId;
if ( !MMSDK.isInitialized() ) {
try {
MMSDK.initialize(activity);
} catch ( Exception e ) {
Log.e(LOGCAT_TAG, "Unable to initialize the Millennial SDK-- " + e.getMessage());
e.printStackTrace();
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
}
if ( extrasAreValid( serverExtras )) {
placementId = serverExtras.get(APID_KEY);
siteId = serverExtras.get(DCN_KEY);
} else {
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
try {
AppInfo ai = new AppInfo().setMediator("mopubsdk");
if ( siteId != null && siteId.length() > 0 ) {
ai = ai.setSiteId(siteId);
} else {
ai = ai.setSiteId(null);
}
MMSDK.setAppInfo(ai);
} catch ( IllegalStateException e ) {
Log.w(LOGCAT_TAG, "Caught exception: " + e.getMessage());
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
try {
NativeAd nativeAd = NativeAd.createInstance(placementId, NativeAd.NATIVE_TYPE_INLINE);
final MillennialStaticNativeAd millennialStaticNativeAd =
new MillennialStaticNativeAd(activity,
nativeAd,
new ImpressionTracker(activity),
new NativeClickHandler(activity),
listener);
millennialStaticNativeAd.loadAd();
} catch ( MMException e ) {
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
}
}
private boolean extrasAreValid(final Map<String, String> serverExtras) {
String placementId = serverExtras.get(APID_KEY);
return (serverExtras.containsKey(APID_KEY) &&
placementId != null && placementId.length() > 0 );
}
static class MillennialStaticNativeAd extends StaticNativeAd implements NativeAd.NativeListener {
private final Context mContext;
private NativeAd mNativeAd;
private final ImpressionTracker mImpressionTracker;
private final NativeClickHandler mNativeClickHandler;
private final CustomEventNativeListener mListener;
private final MillennialStaticNativeAd mMillennialStaticNativeAd;
public MillennialStaticNativeAd(final Context context,
final NativeAd nativeAd,
final ImpressionTracker impressionTracker,
final NativeClickHandler nativeClickHandler,
final CustomEventNativeListener customEventNativeListener) {
mContext = context.getApplicationContext();
mNativeAd = nativeAd;
mImpressionTracker = impressionTracker;
mNativeClickHandler = nativeClickHandler;
mListener = customEventNativeListener;
mMillennialStaticNativeAd = this;
nativeAd.setListener(this);
}
void loadAd() {
Log.i(LOGCAT_TAG, "Loading native ad...");
try {
mNativeAd.load(mContext, null);
} catch (MMException e) {
Log.w(MillennialNative.LOGCAT_TAG, "Caught configuration error Exception.");
e.printStackTrace();
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
mListener.onNativeAdFailed(NativeErrorCode
.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
}
}
// Lifecycle Handlers
#Override
public void prepare(final View view) {
// Must access these methods directly to get impressions to fire.
mNativeAd.getIconImage();
mNativeAd.getDisclaimer();
mImpressionTracker.addView(view, this);
mNativeClickHandler.setOnClickListener(view, this);
}
#Override
public void clear(final View view) {
mImpressionTracker.removeView(view);
mNativeClickHandler.clearOnClickListener(view);
}
#Override
public void destroy() {
mImpressionTracker.destroy();
mNativeAd.setListener(null);
mNativeAd = null;
}
// Event Handlers
#Override
public void recordImpression(final View view) {
notifyAdImpressed();
try {
mNativeAd.fireImpression();
Log.i(LOGCAT_TAG, "Millennial native impression recorded.");
} catch ( MMException m ) {
Log.e(LOGCAT_TAG, "Millennial native impression NOT tracked: " + m.getMessage() );
}
}
#Override
public void handleClick(final View view) {
notifyAdClicked();
mNativeClickHandler.openClickDestinationUrl(getClickDestinationUrl(), view);
mNativeAd.fireClicked();
Log.i(LOGCAT_TAG, "Millennial native ad clicked!");
}
// MM'S Native mListener
#Override
public void onLoaded(NativeAd nativeAd) {
// Set assets
String iconImageUrl = nativeAd.getImageUrl(NativeAd.ComponentName.ICON_IMAGE, 1);
String mainImageUrl = nativeAd.getImageUrl(NativeAd.ComponentName.MAIN_IMAGE, 1);
setTitle(nativeAd.getTitle().getText().toString());
setText(nativeAd.getBody().getText().toString());
setCallToAction(nativeAd.getCallToActionButton().getText().toString());
final String clickDestinationUrl = nativeAd.getCallToActionUrl();
if (clickDestinationUrl == null) {
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
Log.d(LOGCAT_TAG,
"Millennial native encountered null destination url. Failing over.");
mListener.onNativeAdFailed(
NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
setClickDestinationUrl(clickDestinationUrl);
setIconImageUrl(iconImageUrl);
setMainImageUrl(mainImageUrl);
final List<String> urls = new ArrayList<String>();
if ( iconImageUrl != null ) { urls.add(iconImageUrl); }
if ( mainImageUrl != null ) { urls.add(mainImageUrl); }
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
// This has to be run on the main thread:
preCacheImages(mContext, urls, new NativeImageHelper.ImageListener() {
#Override
public void onImagesCached() {
mListener.onNativeAdLoaded(mMillennialStaticNativeAd);
Log.i(LOGCAT_TAG, "Millennial native ad loaded");
}
#Override
public void onImagesFailedToCache(NativeErrorCode errorCode) {
mListener.onNativeAdFailed(errorCode);
}
});
}
});
}
#Override
public void onLoadFailed(NativeAd nativeAd, NativeAd.NativeErrorStatus nativeErrorStatus) {
final NativeErrorCode error;
switch ( nativeErrorStatus.getErrorCode() ) {
case NativeAd.NativeErrorStatus.LOAD_TIMED_OUT:
error = NativeErrorCode.NETWORK_TIMEOUT;
break;
case NativeAd.NativeErrorStatus.NO_NETWORK:
error = NativeErrorCode.CONNECTION_ERROR;
break;
case NativeAd.NativeErrorStatus.UNKNOWN:
error = NativeErrorCode.UNSPECIFIED;
break;
case NativeAd.NativeErrorStatus.LOAD_FAILED:
case NativeAd.NativeErrorStatus.INIT_FAILED:
error = NativeErrorCode.UNEXPECTED_RESPONSE_CODE;
break;
case NativeAd.NativeErrorStatus.ADAPTER_NOT_FOUND:
error = NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR;
break;
case NativeAd.NativeErrorStatus.DISPLAY_FAILED:
case NativeAd.NativeErrorStatus.EXPIRED:
error = NativeErrorCode.UNSPECIFIED;
break;
default:
error = NativeErrorCode.NETWORK_NO_FILL;
}
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
mListener.onNativeAdFailed(error);
}
});
Log.i(LOGCAT_TAG, "Millennial native ad failed: " + nativeErrorStatus.getDescription() );
}
#Override
public void onClicked(NativeAd nativeAd, NativeAd.ComponentName componentName, int i) {
Log.i(LOGCAT_TAG, "Millennial native SDK's click tracker fired.");
}
#Override
public void onAdLeftApplication(NativeAd nativeAd) {
Log.i(LOGCAT_TAG, "Millennial native SDK has left the application.");
}
#Override
public void onExpired(NativeAd nativeAd) {
Log.i(LOGCAT_TAG, "Millennial native ad has expired!");
}
}
}

Related

getting variable from native module in sub class

I have LibModule.java set as native module in reactnative
.....
class LibModule extends ReactContextBaseJavaModule {
boolean readingMyKad = false;
....
public void read_mykad_main() {
clear_results();
pre_card_status = -1;
new readMyKad(reactContext).execute();
}
public static class readMyKad extends AsyncTask<Void, Void, Integer> {
CountDownTimer readMyKadCdt;
readMyKad readMyKadObject;
private WeakReference<ReactApplicationContext> activityReference;
readMyKad(ReactApplicationContext reactContext) {
activityReference = new WeakReference<>(reactContext);
}
protected void onPreExecute() {
readMyKadObject = this;
readMyKadCdt = new CountDownTimer(25000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if ( activityReference.get().readingMyKad ) {
try {
activityReference.get().readingMyKad = false;
if (readMyKadObject.getStatus() == AsyncTask.Status.RUNNING) {
boolean bret = readMyKadObject.cancel(true);
Log.e(TAG,"readMyKadAsyncTask Timeout, cancel: " + bret);
}
} catch (Exception ignored) {
}
}
}
};
readMyKadCdt.start();
}
...............
but in class readMyKad, i need to get variables from my main module LibModule such as activityReference.get().readingMyKad.
not just get the variable but also set and call function from LibModule. how can i do that because LibModule is not an activity.
im sorry for my english and the title.

How can I make connection between retrofit and RxJava in different classes?

I have some classes as presenter and in these classes I use retrofit for some methods. But some methods are duplicated. So I want to use a class for all retrofit and connect to server methods and call them when I want.
But when I created that class it has NullpointerException Error
I will be very thankful if you help me
this is presenter codes:
public class DefinitionPresenter implements DefinitionContract.Presenter {
private KalaBeanDataSource kalaBeanDataSource;
private DefinitionContract.View view;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private DatabaseMethods databaseMethods;
private ActivityKindList activityKindList;
public DefinitionPresenter(KalaBeanDataSource kalaBeanDataSource){
this.kalaBeanDataSource = kalaBeanDataSource;
databaseMethods = new DatabaseMethods(kalaBeanDataSource,compositeDisposable);
activityKindList = new ActivityKindList();
}
#Override
public void attachView(DefinitionContract.View view) {
this.view = view;
}
#Override
public void detachView() {
view = null;
if(compositeDisposable != null && compositeDisposable.size() > 0){
compositeDisposable.clear();
}
}
#Override
public void activityKind() {
activityKindList = databaseMethods.getActivityKind();
if(activityKindList.getItems().size() > 0){
view.getActivityKind(activityKindList);
}else{
view.showMessage(databaseMethods.message);
}
}
}
And this is a class that I created for get data from server with retrofit and RxJava
public class DatabaseMethods {
private KalaBeanDataSource kalaBeanDataSource;
private CompositeDisposable compositeDisposable;
private ActivityKindList activityKindListResult;
public String message = null;
public DatabaseMethods(KalaBeanDataSource kalaBeanDataSource,CompositeDisposable compositeDisposable){
this.kalaBeanDataSource = kalaBeanDataSource;
this.compositeDisposable = compositeDisposable;
activityKindListResult = new ActivityKindList();
}
public ActivityKindList getActivityKind(){
kalaBeanDataSource.getActivityKind().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<ActivityKindList>() {
#Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
#Override
public void onSuccess(ActivityKindList activityKindList) {
activityKindListResult = activityKindList;
}
#Override
public void onError(Throwable e) {
message = e.toString();
}
});
if(message == null && activityKindListResult.getItems().size() > 0){
return activityKindListResult;
}else{
return null;
}
}
this method always returns null:
public ActivityKindList getActivityKind(){
kalaBeanDataSource.getActivityKind().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<ActivityKindList>() {
#Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
#Override
public void onSuccess(ActivityKindList activityKindList) {
activityKindListResult = activityKindList;
}
#Override
public void onError(Throwable e) {
message = e.toString();
}
});
if(message == null && activityKindListResult.getItems().size() > 0){
return activityKindListResult;
}else{
return null;
}
}
1) make this method void
2) create an interface and call it in onSuccess() and onError()
3) implement interface in your presenter

android home button pressed

please check this code completely and suggest me some ideas
i had executed this in android studio 3.0.1 and showing me no error but doesnt shows any ouput
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
// do something here...
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
check this
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
check this
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
this code was not working for me i tried of toasting a msg when home button is pressed in onHomePressed() method but msg not display plz help me to get through it
You arenĀ“t supposed to see when users press the "Home" key, mostly for security reasons and consistent behaviour for the user.
(Except for special cases like Launchers)
Most methods of doing it have been disabled already, your method probably has been disabled aswell.

How to get user ID or info in onAuthenticationSucceeded method for android fingerprint

I am implementing an android fingerprint authentication. I want to know which user, who has registered in device before, is authenticating. Is there any information about the user, who has registered and is valid for the device, in the FingerprintManager.AuthenticationResult argument in onAuthenticationSucceeded method?!
I am using this sample.
this is my class, which is implementing FingerprintManager.AuthenticationCallback:
public class FingerprintUiHelper extends FingerprintManager.AuthenticationCallback {
private static final long ERROR_TIMEOUT_MILLIS = 1600;
private static final long SUCCESS_DELAY_MILLIS = 1300;
private final FingerprintManager mFingerprintManager;
private final ImageView mIcon;
private final TextView mErrorTextView;
private final Callback mCallback;
private CancellationSignal mCancellationSignal;
private boolean mSelfCancelled;
/**
* Constructor for {#link FingerprintUiHelper}.
*/
FingerprintUiHelper(FingerprintManager fingerprintManager,
ImageView icon, TextView errorTextView, Callback callback) {
mFingerprintManager = fingerprintManager;
mIcon = icon;
mErrorTextView = errorTextView;
mCallback = callback;
}
public boolean isFingerprintAuthAvailable() {
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
return mFingerprintManager.isHardwareDetected()
&& mFingerprintManager.hasEnrolledFingerprints();
}
public void startListening(FingerprintManager.CryptoObject cryptoObject) {
if (!isFingerprintAuthAvailable()) {
return;
}
mCancellationSignal = new CancellationSignal();
mSelfCancelled = false;
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
mFingerprintManager
.authenticate(cryptoObject, mCancellationSignal, 0 /* flags */, this, null);
mIcon.setImageResource(R.drawable.ic_fp_40px);
}
public void stopListening() {
if (mCancellationSignal != null) {
mSelfCancelled = true;
mCancellationSignal.cancel();
mCancellationSignal = null;
}
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
if (!mSelfCancelled) {
showError(errString);
mIcon.postDelayed(new Runnable() {
#Override
public void run() {
mCallback.onError();
}
}, ERROR_TIMEOUT_MILLIS);
}
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
showError(helpString);
}
#Override
public void onAuthenticationFailed() {
showError(mIcon.getResources().getString(
R.string.fingerprint_not_recognized));
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
mErrorTextView.removeCallbacks(mResetErrorTextRunnable);
mIcon.setImageResource(R.drawable.ic_fingerprint_success);
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.success_color, null));
mErrorTextView.setText(
mErrorTextView.getResources().getString(R.string.fingerprint_success));
mIcon.postDelayed(new Runnable() {
#Override
public void run() {
mCallback.onAuthenticated();
}
}, SUCCESS_DELAY_MILLIS);
}
private void showError(CharSequence error) {
mIcon.setImageResource(R.drawable.ic_fingerprint_error);
mErrorTextView.setText(error);
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.warning_color, null));
mErrorTextView.removeCallbacks(mResetErrorTextRunnable);
mErrorTextView.postDelayed(mResetErrorTextRunnable, ERROR_TIMEOUT_MILLIS);
}
private Runnable mResetErrorTextRunnable = new Runnable() {
#Override
public void run() {
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.hint_color, null));
mErrorTextView.setText(
mErrorTextView.getResources().getString(R.string.fingerprint_hint));
mIcon.setImageResource(R.drawable.ic_fp_40px);
}
};
public interface Callback {
void onAuthenticated();
void onError();
}
}

RunonUI Thread blocks a AsynTask in android from executing to completion

I have an issue with runOnuiThread and AsyncTask getting called together.
My AsynchTask gets data to populate a listView through runOnUIThread call.
This Asych Task can get data even when UI is not in focus . It starts from a UI screen and runs until application is logged out.
Now data coming from this Task can populate only a particular listview.
Now if i invoke another Asynch Task from another view using call executeOnExecutor call for AsynchTask, the Asynch Task does not run to compeltion. It locks up.
If I comment out code for the never ending AsychTask called Receiver.. then all UI's listview get populated and no Asych Task locks.
This Receiver waits on a REST API call for response to return but since I am running through executeonExecutor call, it should be parallel processing.
I need to have the receiver running all the time as that is an integral of my application.
What strategy can I use here to fix this issue.
Here are my code snippets.
public class Receiver {
private final static String QUEUE_NAME = "hello";
private String m_ErrorMessage;
private IRunOnUIThreadCallback iRunOnUIThreadCallback;
private Send m_Received;
private int m_TimeoutDuration;//how long the reading of new message waits in milli seconds
public void SetCallback(IRunOnUIThreadCallback runOnUIThreadCallback)
{
iRunOnUIThreadCallback = runOnUIThreadCallback;
}
public void SetTimeoutDuration(int timeout)
{
m_TimeoutDuration = timeout;
}
public void StartReceiver(Send receiverInfo)
{
String receivedInfo = null;
try {
new ReceiveInfo ().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, receiverInfo);
}
catch(Exception exp)
{
m_ErrorMessage = exp.getMessage();
}
}
private class ReceiveInfo extends AsyncTask<Send, Void, Send>
{
//initiate vars
public receive() {
super();
//my params here
}
protected Message doInBackground(Send... receiverInfo)
{
Send recv=null;
try {
PreferenceSingleton single = PreferenceSingleton.getInstance();
final User user = single.getUser();
final SvcApi svc = LoginAuthSvc.init();
Send send=(Send)receiverInfo[0];
send.setUserId(user.getUsername());
//dxbrem
while (true) {
recv=svc.receive(send);
String str= recv.get();
if ((str == null || (str.trim().length() == 0))) {
continue;
}
//DJ uncomment
iRunOnUIThreadCallback.RunAfterIsReceived(recv);
//messages.add(message);
System.out.println(" [x] Received '" + recv + "'");
}
}catch(Exception exp)
{
m_ErrorMessage = exp.getMessage();
}
return recv;
}
}
public String getErrorMessage() {
return m_ErrorMessage;
}
}
public interface IRunOnUIThreadCallback {
public void RunAfterIsReceived(ByteSent m);
public void RunAfterIsReceived(Send m);
}
The class that handles this.. has the following code and
public class MainFragment extends Fragment implements MFragment.OnFragmentInteractionListener, IRunOnUIThreadCallback {
private Receiver mReceiver;
public void SetUICallbackOnMessageReceiver()
{
mReceiver.SetCallback(this);
}
private void callRunUIThread(final SentInfo m) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (m!= null) {
mGridArray.add(message);
if (mListAdapter != null) {
mListAdapter.notifyDataSetChanged();
mListView.setSelection(mListAdapter.getCount());
mListView.smoothScrollToPosition(mListAdapter.getCount());
}
}
}
}); // end of runOnUiThread
}
#Override
public void RunAfterIsReceived(ByteSent m) {
}
#Override
public void RunAfterIsReceived(Sent m) {
SentInfo m= new SentInfo(false, recv.getInfo());
callRunUIThread(msg);
}
mListAdapter is the ListAdapater
mListView is the ListView
Here is the AsynchTask code
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
public class CallableTask<T> extends AsyncTask<Void,Double,T> {
private static final String TAG = CallableTask.class.getName();
public static <V> void invoke(Callable<V> call,Activity activity, TaskCallback<V> callback){
new CallableTask<V>(activity,call, callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
private Callable<T> callable_;
private AsyncTask<Void, Void, String> asyncTask_;
private Context context;
private Activity activity;
private Fragment fragmentActivity;
private android.support.v4.app.Fragment dynamicFragment;
private TaskCallback<T> callback_;
private Exception error_;
public CallableTask(Fragment actvy,Callable<T> callable, TaskCallback<T> callback) {
callable_ = callable;
callback_ = callback;
fragmentActivity=actvy;
}
public CallableTask(Activity actvy,Callable<T> callable, TaskCallback<T> callback) {
callable_ = callable;
callback_ = callback;
activity=actvy;
}
#Override
protected T doInBackground(Void... ts) {
T result = null;
try{
result = callable_.call();
} catch (Exception e){
Log.e(TAG, "Error invoking callable in AsyncTask callable: " + callable_, e);
error_ = e;
}
return result;
}
#Override
protected void onPostExecute(T r) {
if(error_ != null){
callback_.error(error_);
}
else {
callback_.success(r,activity);
}
}
public static <V> void invoke(Callable<V> call, Fragment _frg, TaskCallback<V> callback) {
new CallableTask<V>(_frg,call, callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
// public CallableTask(android.support.v4.app.Fragment chatActivity,Callable<T> callable, TaskCallback<T> callback) {
// callable_ = callable;
// callback_ = callback;
// dynamicFragment=chatActivity;
// }
public CallableTask(android.support.v4.app.Fragment actvy,Callable<T> callable, TaskCallback<T> callback) {
callable_ = callable;
callback_ = callback;
dynamicFragment=actvy;
}
public static <V> void invoke(Callable<V> call, android.support.v4.app.Fragment _frg, TaskCallback<V> callback) {
new CallableTask<V>(_frg,call, callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
}
This gets called here... only when clicking on a button Send.
CallableTask.invoke(new Callable<Sent>() {
#Override
public Sent call() throws Exception {
}, this, new TaskCallback<Sent>() {
#Override
public void success(Sent result, Context context) {
mGridArray.add(result);
if (mListAdapter != null) {
mListAdapter.notifyDataSetChanged();
mListView.setSelection(mListAdapter.getCount());
mListView.smoothScrollToPosition(mListAdapter.getCount());
}
#Override
public void error(Exception e) {
}
});
Thanks
Dhiren
I finally resolved this by running a Asynch.cancel call on the thread from the activity fragment that started this thread. when I move away from activity. If I did not , it blocked any other tasks from running,

Categories

Resources