IOIOActivity and AppCompactActivity - java

I'm not experienced in Java development and migrating from Eclipse. I don't know how to use the nested classes in my case where I need to extend AppCompactActivity and IOIOActivity. Considering, I have another inner class Looper already extending another class. The code below isn't running what is inside Testing class. Can someone help me about how to execute my inner class, which is Testing class.
My code:
public class MainActivity extends AppCompatActivity {
private class Testing extends IOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
}
Thankss

I found my answer and I would like to share it with you all for the future. This is for starting a new IOIOActivity in Android Studio. IOIO developers haven't written the official IOIO code for AppCompactActivity yet. After couple of days trying, its finally tested and working with IOIO led.
Create a new Class file called AppCompactIOIOActivity (I just like that name) in your package. Note: all credits to Ytai. IOIO code from App507
public class AppCompactIOIOActivity extends AppCompatActivity implements IOIOLooperProvider {
private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);
public AppCompactIOIOActivity() {
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.helper_.create();
}
protected void onDestroy() {
this.helper_.destroy();
super.onDestroy();
}
protected void onStart() {
super.onStart();
this.helper_.start();
}
protected void onStop() {
this.helper_.stop();
super.onStop();
}
#SuppressLint("WrongConstant")
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if((intent.getFlags() & 268435456) != 0) {
this.helper_.restart();
}
}
protected IOIOLooper createIOIOLooper() {
throw new RuntimeException("Client must override one of the createIOIOLooper overloads!");
}
public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
return this.createIOIOLooper();
}
}
Then in your MainActivity
public class MainActivity extends AppCompactIOIOActivity {
private ToggleButton button_;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_ = (ToggleButton) findViewById(R.id.toggleButton);
}
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
#Override
protected void setup() throws ConnectionLostException {
showVersions(ioio_, "IOIO connected!");
led_ = ioio_.openDigitalOutput(0, true);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
led_.write(!button_.isChecked());
Thread.sleep(100);
}
#Override
public void disconnected() {
enableUi(false);
toast("IOIO disconnected");
}
#Override
public void incompatible() {
showVersions(ioio_, "Incompatible firmware version!");
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void showVersions(IOIO ioio, String title) {
toast(String.format("%s\n" +
"IOIOLib: %s\n" +
"Application firmware: %s\n" +
"Bootloader firmware: %s\n" +
"Hardware: %s",
title,
ioio.getImplVersion(IOIO.VersionType.IOIOLIB_VER),
ioio.getImplVersion(IOIO.VersionType.APP_FIRMWARE_VER),
ioio.getImplVersion(IOIO.VersionType.BOOTLOADER_VER),
ioio.getImplVersion(IOIO.VersionType.HARDWARE_VER)));
}
private void toast(final String message) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
});
}
private int numConnected_ = 0;
private void enableUi(final boolean enable) {
// This is slightly trickier than expected to support a multi-IOIO use-case.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (enable) {
if (numConnected_++ == 0) {
button_.setEnabled(true);
}
} else {
if (--numConnected_ == 0) {
button_.setEnabled(false);
}
}
}
});
}
}
Don't forget to add your resources and dependances from IOIO developers. Good luck!

Related

Nested callback is too deep

How to replace nested callbacks (Testing.java) for easy reading like this:
if(isValidGenderID() && isValidReligionID() && isValidMaritalID()){
// DO PRIMARY TASK
}
Nested callbacks are too deep, making the program not easy to read!. How to resolved this problem?
//PersonValidation.java
public static void isValidGenderID(#NonNull Context context, int genderID, final IGenderDataSource.IIsExistGenderIDCallback callback) {
GenderDataSource.getInstance(context).isExistGenderID(genderID, new IGenderDataSource.IIsExistGenderIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
public static void isValidReligionID(#NonNull Context context, int religionID, final IReligionDataSource.IIsExistReligionIDCallback callback) {
ReligionDataSource.getInstance(context).isExistReligionID(religionID, new IReligionDataSource.IIsExistReligionIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
public static void isValidMaritalID(#NonNull Context context, int maritalID, final IMaritalDataSource.IIsExistMaritalIDCallback callback) {
MaritalDataSource.getInstance(context).isExistMaritalID(maritalID, new IMaritalDataSource.IIsExistMaritalIDCallback() {
#Override
public void onSuccess(boolean result) {
callback.onSuccess(result);
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}
// GenderDataSource.java
#Override
public void isExistGenderID(final int ID, #NonNull final IIsExistGenderIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// ReligionDataSource.java
#Override
public void isExistReligionID(final int ID, #NonNull final IIsExistReligionIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// MaritalDataSource.java
#Override
public void isExistMaritalID(final int ID, #NonNull final IIsExistMaritalIDCallback callback) {
Runnable r = new Runnable() {
#Override
public void run() {
db.sqlRawQuery();
callback.onSuccess();
}
};
appExecutors.getLocalDb().execute(r);
}
// Testing.java (Nested calls are too deep, making the program not easy to read)
#Override
public void createCustomer(#NonNull final Customer customer, #NonNull final ICustomerDataSource.ICreateCustomerCallback callback) {
//
// isValidGenderID?
//
isValidGenderID(context, customer.getGenderID(), new IGenderDataSource.IIsExistGenderIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// isValidReligionID?
//
isValidReligionID(context, customer.getReligionID(), new IReligionDataSource.IIsExistReligionIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// isValidMaritalID?
//
isValidMaritalID(context, customer.getMaritalID(), new IMaritalDataSource.IIsExistMaritalIDCallback() {
#Override
public void onSuccess(boolean result) {
if (result) {
//
// DO PRIMARY TASK
//
} else {
callback.onFailure("Marital is not valid");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
//
} else {
callback.onFailure("Religion is not valid!");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
//
} else {
callback.onFailure("Gender is not valid!");
}
}
#Override
public void onFailure(String result) {
callback.onFailure(result);
}
});
}

How to fix ExoPlayer video Freeze 2.9.6

I use this code to play the full-screen video but I have a problem when it is video playing and moving from the main activity to the full-screen activity occurs freezing of the video for 2-3 seconds This problem occurs only with the releases after 2.8.3 only but with 2.8.0 works Video is smooth
code full: https://github.com/MATPOCKIH/ExoPlayerFullscreen
PlayerViewManager
public class PlayerViewManager {
private static final String TAG = "ExoPlayerViewManager";
public static final String EXTRA_VIDEO_URI = "video_uri";
private static Map<String, PlayerViewManager> instances = new HashMap<>();
private Uri videoUri;
public boolean isPlayerPlaying;
private boolean isMustPlaying;
private UniversalPlayerView universalPlayer;
public static PlayerViewManager getInstance(String videoUri) {
PlayerViewManager instance = instances.get(videoUri);
if (instance == null) {
instance = new PlayerViewManager(videoUri);
instances.put(videoUri, instance);
}
return instance;
}
private PlayerViewManager(String videoUri) {
this.videoUri = Uri.parse(videoUri);
}
public void preparePlayer(PlayerHolderView playerHolderView) {
if (playerHolderView == null) {
return;
}
if (universalPlayer == null) {
universalPlayer = createPlayer(playerHolderView.getContext());
isPlayerPlaying = true;
isMustPlaying = true;
}
universalPlayer.initialize(videoUri, playerHolderView);
}
public void releaseVideoPlayer() {
if (universalPlayer != null) {
universalPlayer.release();
}
universalPlayer = null;
}
public void goToBackground() {
if (universalPlayer != null /*&& !isMustPlaying*/) {
//isPlayerPlaying = player.getPlayWhenReady();
universalPlayer.pause();
}
}
public void goToForeground() {
if (universalPlayer != null && isMustPlaying) {
universalPlayer.play();
}
}
public void pausePlayer(){
if (universalPlayer != null) {
universalPlayer.pause();
isPlayerPlaying = false;
isMustPlaying = false;
}
}
public void playPlayer(){
if (universalPlayer != null) {
universalPlayer.play();
isPlayerPlaying = true;
isMustPlaying = true;
}
}
private UniversalPlayerView createPlayer(Context context){
if (videoUri.getScheme().startsWith("http")){
return new FaceterExoPlayerView(context);
}
return new FaceterExoPlayerView(context);
}
}
FaceterExoPlayerView
public class FaceterExoPlayerView extends UniversalPlayerView {
private Uri videoUri;
private DefaultDataSourceFactory dataSourceFactory;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private Context context;
public FaceterExoPlayerView(Context context) {
this.context = context;
}
#Override
public void initialize(Uri videoUri, PlayerHolderView playerHolderView) {
if (playerHolderView == null || videoUri == null)
return;
exoPlayerView = playerHolderView.findViewById(R.id.exo_player);
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "faceter"));
MediaSource videoSource = buildMediaSource(videoUri, null);
player.prepare(videoSource);
}
player.clearVideoSurface();
player.setVideoTextureView((TextureView) exoPlayerView.getVideoSurfaceView());
exoPlayerView.setPlayer(player);
exoPlayerView.hideController();
setResizeModeFill(playerHolderView.isResizeModeFill());
}
#Override
public void play() {
player.setPlayWhenReady(true);
}
#Override
public void pause() {
player.setPlayWhenReady(false);
}
#SuppressWarnings("unchecked")
private MediaSource buildMediaSource(Uri uri, #Nullable String overrideExtension) {
int type = Util.inferContentType(uri, overrideExtension);
switch (type) {
/*case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new DashManifestParser(), (List<RepresentationKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new SsManifestParser(), (List<StreamKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);*/
case C.TYPE_HLS:
return new HlsMediaSource.Factory(dataSourceFactory)
/*.setPlaylistParser(
new FilteringManifestParser<>(
new HlsPlaylistParser(), (List<RenditionKey>) getOfflineStreamKeys(uri)))*/
.createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
#Override
public void release() {
if (player != null) {
player.release();
}
player = null;
}
#Override
public void setResizeModeFill(boolean isResizeModeFill) {
if (isResizeModeFill) {
exoPlayerView.setResizeMode(RESIZE_MODE_FILL);
} else {
exoPlayerView.setResizeMode(RESIZE_MODE_FIT);
}
}
}
PlayerHolderView.java
public class PlayerHolderView extends FrameLayout {
private String videoUrl;
private boolean isResizeModeFill = true;
private OnUserInteractionListener onUserInteractionListener;
public PlayerHolderView(#NonNull Context context) {
super(context);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.layout_player, this, true);
View controlView = this.findViewById(R.id.exo_controller);
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).pausePlayer();
}
});
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FullscreenVideoActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
getContext().startActivity(intent);
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private List<PlayerHolderView> playerHolders = new ArrayList<>();
private List<TextView> links = new ArrayList<>();
private List<String> mVideoUrls = new ArrayList<>(
Arrays.asList(
//"http://10.110.3.30/api/Playlists/6a3ecad7-e744-446f-9341-0e0ba834de63?from=2018-09-20&to=2018-09-21"
"https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/TearsOfSteel.m3u8",
"http://redirector.c.youtube.com/videoplayback?id=604ed5ce52eda7ee&itag=22&source=youtube&sparams=ip,ipbits,expire,source,id&ip=0.0.0.0&ipbits=0&expire=19000000000&signature=513F28C7FDCBEC60A66C86C9A393556C99DC47FB.04C88036EEE12565A1ED864A875A58F15D8B5300&key=ik0",
"https://html5demos.com/assets/dizzy.mp4"
//"https://cdn.faceter.io/hls/ab196789-8876-4854-82f3-087e5682d013",
//"https://cdn.faceter.io/hls/65d1c673-6a63-44c8-836b-132449c9462a"
)
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerHolders.add((PlayerHolderView) findViewById(R.id.holder1));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder2));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder3));
links.add((TextView) findViewById(R.id.title1));
links.add((TextView) findViewById(R.id.title2));
links.add((TextView) findViewById(R.id.title3));
}
#Override
public void onResume() {
super.onResume();
int i = 0;
for (final String videoUrl : mVideoUrls) {
playerHolders.get(i).setupPlayerView(videoUrl);
playerHolders.get(i).setOnUserInteractionListener(this);
links.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVideoTitleClicked(videoUrl);
}
});
i++;
}
}
#Override
public void onPause() {
super.onPause();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).goToBackground();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).releaseVideoPlayer();
}
}
public void onVideoTitleClicked(String videoUrl) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
startActivity(intent);
}
}
FullscreenVideoActivity
public class FullscreenVideoActivity extends AppCompatActivity {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of
// API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
private String mVideoUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_video);
mContentView = findViewById(R.id.enclosing_layout);
PlayerHolderView playerHolderView = findViewById(R.id.player_holder);
playerHolderView.setResizeModeFill(false);
mVideoUri = getIntent().getStringExtra(PlayerViewManager.EXTRA_VIDEO_URI);
PlayerViewManager.getInstance(mVideoUri).preparePlayer(playerHolderView);
/*
// Set the fullscreen button to "close fullscreen" icon
View controlView = playerView.findViewById(R.id.exo_controller);
ImageView fullscreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
fullscreenIcon.setImageResource(R.drawable.exo_controls_fullscreen_exit);
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).pausePlayer();
}
});*/
}
#Override
public void onResume() {
super.onResume();
PlayerViewManager.getInstance(mVideoUri).goToForeground();
}
#Override
public void onPause() {
super.onPause();
PlayerViewManager.getInstance(mVideoUri).goToBackground();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide();
}
private void hide() {
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide() {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, 100);
}
}
Just try out this code for video freeze problem:
#Override
public void play() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
public void pause() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
Here player.getPlaybackState(); is help full to get it to back state.

Android-AltBeacon-library intergration in a java class

I'm trying to integrate the altbeacon function in a java class in android studio, but I'm getting an error because of the getActivity. I want to created an object from this class in onahter Activities..
so any idea how could it work?
It works perfect, when I add the altbeacon class in a activity under protected void onCreate(Bundle savedInstanceState).
public class detectRoom implements BeaconConsumer {
private List <IBeaconSensor> beaconList = new ArrayList <IBeaconSensor> ();
private BeaconManager beaconManager;
public detectRoom() {
name="detectRoom";
}
private String detectRoomName(String raum) {
return raum;
}
public void detectRoomMet () {
for (int i = 0;i< beaconList.size() ;i++){
if(beaconList.get(i).getName().equals("45")) { // 6 = Minor of Ibeacon
detectRoomName("Room3");
}
if(beaconList.get(i).getName().equals("55")) {
detectRoomName("Room2");
}
if(beaconList.get(i).getName().equals("85")) {
detectRoomName("Room1");
}
else {
detectRoomName("UnknowRoom");
}
}
}
#Override
public void onBeaconServiceConnect() {
beaconManager = new BeaconManager(getApplicationContext());
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
this.beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
beaconList.clear();
for(Iterator<Beacon> iterator = beacons.iterator(); iterator.hasNext();) {
beaconList.add(new IBeaconSensor (iterator.next().getId3().toString()));
}
}
}
});
try {
this.beaconManager.startRangingBeaconsInRegion(new Region("MyRegionId", null, null, null));
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public Context getApplicationContext() {
return null;
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
this.beaconManager.unbind(this);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return false;
}
public void bindBeacon() {
beaconManager.bind(this);
}
public void unBindBeacon() {
beaconManager.unbind(this);
}
}
When making a POJO that extends BeaconConsumer you must do two things:
Pass a reference to an Android Context to the POJO.
Chain the methods bindService, unbindService, getApplicationContext to the Context above.
Like this:
public class Pojo extends BeaconConsumer() {
private Context mContext;
public Pojo(Context context) {
mContext = context;
}
#Override
public Context getApplicationContext() {
return mContext.getApplicationContext();
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
mContext.unbindService(serviceConnection);
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return mContext.bindService(intent, serviceConnection, i);
}
...
}

Realm database is not updating

Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference

Loading multiple AdMob videos

For demonstration purposes, the app has one activity that simply offers this:
You click a button, view a rewarded video, and you are rewarded with whatever.
The Problem
How can I load the videos? From what I have seen you can only call mAd.loadAd() once. There are 3 videos, each with their own AD UNIT ID. Each ad unit can have its own listener, but only one video loads so it doesn't matter...
When trying to load multiple videos
For example:
mAd1.loadAd("AD_UNIT_1", new AdRequest.Builder().build());
mAd2.loadAd("AD_UNIT_2", new AdRequest.Builder().build());
mAd3.loadAd("AD_UNIT_3", new AdRequest.Builder().build());
results in only the last video being loaded and this in log:
W/Ads: Loading already in progress, saving this object for future refreshes.
onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd1 = MobileAds.getRewardedVideoAdInstance(this);
mAd2 = MobileAds.getRewardedVideoAdInstance(this);
mAd3 = MobileAds.getRewardedVideoAdInstance(this);
listeners...
mAd1.loadAd() etc
}
Thank you for your help
Edit: It's clear I am thinking about this problem wrong. I have 5+ ad zones that each will play a rewarded video and give a different reward (for example, one gives coins, one gives a level up, and so on..). There is no reason to load 5 videos. I should load one in onCreate(), so it's ready when needed, then load it again after the item is rewarded so it's ready for next time.
So the question remains, if there is just the one video, and thus one ad zone, being loaded onCreate() then how can I track what reward to give?
Here's a simple solution...
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewarded(RewardItem rewardItem) {
switch(Constants.currentAd) {
case("REWARD1"):
//do something
Constants.currentAd = "";
break;
case("REWARD2"):
//do something
Constants.currentAd = "";
break;
case("REWARD3"):
//do something
Constants.currentAd = "";
break;
}
}
});
mAd.loadAd("REWARDED_VIDEO_UNIT_ID", new AdRequest.Builder().build());
}
public void showRewardedVideo() {
if (mAd.isLoaded()) {
mAd.show();
}
}
Constants.java
public class Constants {
public static String currentAd = "";
}
Showing the ad after button click
rewardButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Constants.currentAd = "REWARD1";
dismiss();
((MainActivity) getActivity()).showRewardedVideo();
}
});
REWARDED_VIDEO_UNIT_ID is one ad unit for rewarded video in AdMob...remove the rest. No need for other units, you can track whatever you like in the listener.
Other simple soluction...
AbstractRewardVideo.java
public abstract class AbstractRewardVideo {
private RewardedVideoAd mAd;
private String adId = "ca-app-pub...";
private Activity activity;
abstract protected RewardedVideoAdListener getListener();
public void init(Activity activity) {
this.activity = activity;
mAd = MobileAds.getRewardedVideoAdInstance(activity);
setAdId(adId);
loadRewardedVideoAd();
}
public Activity getActivity(){
return this.activity;
}
public void loadRewardedVideoAd() {
mAd.loadAd(adId, new AdRequest.Builder().build());
}
public void showVideo(){
setListener(getListener());
if (mAd.isLoaded()) {
mAd.show();
} else {
Utils.exibirToast("Don't loaded!");
}
}
public void setAdId(#NonNull String id){
this.adId = id;
}
public void setListener(RewardedVideoAdListener listener){
mAd.setRewardedVideoAdListener(listener);
}
}
Reward1.java
public class Reward1 extends AbstractRewardVideo {
public Reward1(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
Reward2.java
public class Reward2 extends AbstractRewardVideo {
public Reward2(Activity activity) {
init(activity);
}
#Override
protected RewardedVideoAdListener getListener() {
return new Listener();
}
private class Listener implements RewardedVideoAdListener {
#Override
public void onRewarded(RewardItem rewardItem) {
//Do something...
}
public void onRewardedVideoAdLoaded() {}
public void onRewardedVideoAdOpened() {}
public void onRewardedVideoStarted() {}
public void onRewardedVideoAdClosed() { loadRewardedVideoAd(); }
public void onRewardedVideoAdLeftApplication() {}
public void onRewardedVideoAdFailedToLoad(int i) {}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity{
Reward1 reward1;
Reward2 reward2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reward1 = new Reward1(this);
reward2 = new Reward1(this);
...
reward1.showVideo();
...
reward2.showVideo();
}
}
MobileAds.initialize ( this, "ca-app-pub-4761500786576152~8215465788" );
RewardedVideoAd mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(Video_Ad.this);
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}

Categories

Resources