In this code I have an if else block. In the if else I want to include a button using bundle but I have tried and I get an error. My code is below, does anyone have any ideas why I am getting the error?
package com.apps.visitkuningan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class KetWisata extends Activity{
Intent iinntteen;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.ket_wisata);
String tampil = getIntent().getExtras().getString("key");
ImageView img1 = (ImageView) findViewById(R.id.wisata);
TextView nama = (TextView) findViewById(R.id.nama);
TextView alamat = (TextView) findViewById(R.id.alamat);
TextView keterangan = (TextView) findViewById(R.id.keterangan);
Button arahkan = (Button) findViewById(R.id.arahkan);
final Bundle bundel2 = new Bundle();
final String tampil2 = null;
arahkan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
bundel2.putString("key", tampil2);
iinntteen.putExtras(bundel2);
startActivity(iinntteen);
}
});
if(tampil.equalsIgnoreCase("wis_balongdalem"))
{
img1.setBackgroundResource(R.drawable.wis_balong);
nama.setText("Balong Dalem");
alamat.setText(R.string.add_balong);
keterangan.setText(R.string.ket_balong);
iinntteen = new Intent(KetWisata.this, Arahkan.class);
tampil2 ="coba"; //TAMPIL2 CANT DETECTED..
}
if(tampil.equalsIgnoreCase("wis_curugbangkong"))
{
img1.setBackgroundResource(R.drawable.wis_bangkong2);
nama.setText("Curug Bangkong");
alamat.setText(R.string.add_bangkong);
keterangan.setText(R.string.ket_bangkong);
iinntteen = new Intent(KetWisata.this, Tentang.class);
}
if(tampil.equalsIgnoreCase("wis_buperciberem"))
{
img1.setBackgroundResource(R.drawable.wis_ciberem2);
nama.setText("Buper Cibeureum");
alamat.setText(R.string.add_ciberem);
keterangan.setText(R.string.ket_ciberem);
}
if(tampil.equalsIgnoreCase("wis_cibulan"))
{
img1.setBackgroundResource(R.drawable.wis_cibulan2);
nama.setText("Kolam Cibulan");
alamat.setText(R.string.add_cibulan);
keterangan.setText(R.string.ket_cibulan);
}
if(tampil.equalsIgnoreCase("wis_balongcicerem"))
{
img1.setBackgroundResource(R.drawable.wis_balong);
nama.setText("Balong Cicereum");
alamat.setText(R.string.add_cicerem);
keterangan.setText(R.string.ket_cicerem);
}
if(tampil.equalsIgnoreCase("wis_balongcigugur"))
{
img1.setBackgroundResource(R.drawable.wis_cigugur2);
nama.setText("Balong Cigugur");
alamat.setText(R.string.add_cigugur);
keterangan.setText(R.string.ket_cigugur);
}
if(tampil.equalsIgnoreCase("wis_curugcilengkrang"))
{
img1.setBackgroundResource(R.drawable.wis_cilengkrang2);
nama.setText("Lembah Cilengkrang");
alamat.setText(R.string.add_cilengkrang);
keterangan.setText(R.string.ket_cilengkrang);
}
if(tampil.equalsIgnoreCase("wis_cipari"))
{
img1.setBackgroundResource(R.drawable.wis_cipari2);
nama.setText("Taman Purbakala Cipari");
alamat.setText(R.string.add_cipari);
keterangan.setText(R.string.ket_cipari);
}
if(tampil.equalsIgnoreCase("wis_balongdarmaloka"))
{
img1.setBackgroundResource(R.drawable.wis_darmaloka2);
nama.setText("Balong Darmaloka");
alamat.setText(R.string.add_darmaloka);
keterangan.setText(R.string.ket_darmaloka);
}
if(tampil.equalsIgnoreCase("wis_linggarjatiindah"))
{
img1.setBackgroundResource(R.drawable.wis_linggarjat2i);
nama.setText("Linggarjati Indah");
alamat.setText(R.string.add_linggarjati);
keterangan.setText(R.string.ket_linggarjati);
}
if(tampil.equalsIgnoreCase("wis_guamaria"))
{
img1.setBackgroundResource(R.drawable.wis_guamaria);
nama.setText("Gua Maria");
alamat.setText(R.string.add_guamaria);
keterangan.setText(R.string.ket_guamaria);
}
if(tampil.equalsIgnoreCase("wis_gedungnaskah"))
{
img1.setBackgroundResource(R.drawable.wis_muslinggar2);
nama.setText("Musium Linggarjati");
alamat.setText(R.string.add_naskah);
keterangan.setText(R.string.ket_naskah);
}
if(tampil.equalsIgnoreCase("wis_buperpalutungan"))
{
img1.setBackgroundResource(R.drawable.wis_palutungan2);
nama.setText("Buper Plautungan");
alamat.setText(R.string.add_palutungan);
keterangan.setText(R.string.ket_palutungan);
}
if(tampil.equalsIgnoreCase("wis_buperpaniis"))
{
img1.setBackgroundResource(R.drawable.wis_paniis2);
nama.setText("Buper Paniis");
alamat.setText(R.string.add_paniis);
keterangan.setText(R.string.ket_paniis);
}
if(tampil.equalsIgnoreCase("wis_paseban"))
{
img1.setBackgroundResource(R.drawable.wis_paseban);
nama.setText("Gedung Merapat Lima");
alamat.setText(R.string.add_paseban);
keterangan.setText(R.string.ket_paseban);
}
if(tampil.equalsIgnoreCase("wis_gedungsahrir"))
{
img1.setBackgroundResource(R.drawable.wis_gedungsut);
nama.setText("Gedung Sutan Syahrir");
alamat.setText(R.string.add_syahrir);
keterangan.setText(R.string.ket_syahrir);
}
if(tampil.equalsIgnoreCase("wis_sanggariang"))
{
img1.setBackgroundResource(R.drawable.wis_sanggariang2);
nama.setText("Kolam Renang Sanggariang");
alamat.setText(R.string.add_sanggariang);
keterangan.setText(R.string.ket_sanggariang);
}
if(tampil.equalsIgnoreCase("wis_sangkanurip"))
{
img1.setBackgroundResource(R.drawable.wis_sangkanurip2);
nama.setText("Pemandian Sangkanurip");
alamat.setText(R.string.add_sangkanurip);
keterangan.setText(R.string.ket_sangkanhurip);
}
if(tampil.equalsIgnoreCase("wis_curugsidomba"))
{
img1.setBackgroundResource(R.drawable.wis_sidomba2);
nama.setText("Sidomba");
alamat.setText(R.string.add_sidomba);
keterangan.setText(R.string.ket_sidomba);
}
if(tampil.equalsIgnoreCase("wis_talagaremis"))
{
img1.setBackgroundResource(R.drawable.wis_talagaremis);
nama.setText("Talagaremis");
alamat.setText(R.string.add_talagaremis);
keterangan.setText(R.string.ket_talagaremis); }
if(tampil.equalsIgnoreCase("wis_tngc"))
{
img1.setBackgroundResource(R.drawable.wis_tngc);
}
if(tampil.equalsIgnoreCase("wis_wadukdarma"))
{
img1.setBackgroundResource(R.drawable.wis_waduk2);
nama.setText("Waduk Darma");
alamat.setText(R.string.add_waduk);
keterangan.setText(R.string.ket_waduk);
}
if(tampil.equalsIgnoreCase("wis_abn"))
{
img1.setBackgroundResource(R.drawable.wis_abn);
}
if(tampil.equalsIgnoreCase("wis_hasanmaulana"))
{
img1.setBackgroundResource(R.drawable.wis_hasanmaulana);
nama.setText("Gedung Hasan Maulani");
alamat.setText(R.string.add_hasanmaulana);
keterangan.setText(R.string.ket_hasanmaulana);
}
if(tampil.equalsIgnoreCase("wis_makamvanbeck"))
{
img1.setBackgroundResource(R.drawable.wis_makamvanbeck);
nama.setText("Makam Van Beck");
alamat.setText(R.string.add_makamvanbeck);
keterangan.setText(R.string.ket_makamvanbeck);
}
if(tampil.equalsIgnoreCase("wis_situscangkuang"))
{
img1.setBackgroundResource(R.drawable.wis_situscangkuang);
nama.setText("Situs Cangkuang");
alamat.setText(R.string.add_cangkuang);
keterangan.setText(R.string.ket_cangkuang);
}
if(tampil.equalsIgnoreCase("wis_talaganilem"))
{
img1.setBackgroundResource(R.drawable.wis_talaganilem);
nama.setText("Talaganilem");
alamat.setText(R.string.add_talaganilem);
keterangan.setText(R.string.ket_talaganilem);
}
//arahkan.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View arg0) {
// startActivity(new Intent(KetWisata.this, Arahkan.class));
// }
//});
}
}
Before doing this line:
getIntent().getExtras().ANYTHING_ELSE
Make sure that:
getIntent() != null && getIntent().getExtras() != null You can also check for getIntent().getExtras().isEmpty()
Related
I want to play this link but i m unable to play this link in my exoplayer
I will be able to play this link only when this referer will be added in the exoplayer but i m unable to add this referer. I dont know how can i add this referer to my exoplayer
Referer: http://nbajunkie.xyz/jp1/
https://reels2watch.com/hls/s1.m3u8
dataSourceFactory.getDefaultRequestProperties().set("Referer", "https://yourdomain.com");
I dont know how to add this referer in the header can someone help me about it or Anyone can do it for me ? Because i don’t know much about java kindly let me know how to solve this issue.
import static com.google.android.exoplayer2.util.Util.getUserAgent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.mediarouter.app.MediaRouteButton;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.DefaultMediaSourceFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.util.Util;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaLoadOptions;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.cast.framework.CastButtonFactory;
import com.google.android.gms.cast.framework.CastContext;
import com.google.android.gms.cast.framework.CastSession;
import com.google.android.gms.cast.framework.CastState;
import com.google.android.gms.cast.framework.CastStateListener;
import com.google.android.gms.cast.framework.SessionManagerListener;
import com.google.android.gms.cast.framework.media.RemoteMediaClient;
import com.google.firebase.FirebaseApp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.Myapp.hd.Steaming.R;
import com.Myapp.hd.Steaming.HelperClass;
import com.Myapp.hd.Steaming.BaseActivity;
import com.Myapp.hd.Steaming.Location;
import com.Myapp.hd.Steaming.sessionManager.SessionManager;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class Exo_Player extends BaseActivity {
private static final String TAG = "Exo_Player";
String url, userAgent;
boolean tokenEnable = false;
private InterstitialAd interstitial;
private PlayerView playerView;
private SimpleExoPlayer player;
private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
private DataSource.Factory mediaDataSourceFactory;
private Handler mainHandler;
private ProgressBar progressBar;
FirebaseFirestore db;
SessionManager sessionManager;
FirebaseFirestore firebaseFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
//////////////////////////////////////////////////////
setContentView(R.layout.exo_player_ui);
castContext = CastContext.getSharedInstance(this);
initCast();
db = FirebaseFirestore.getInstance();
sessionManager = new SessionManager(this);
FirebaseApp.initializeApp(this);
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Exo_Player.this, sessionManager.getBackads(), adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
interstitial = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
interstitial = null;
}
});
progressBar = findViewById(R.id.progressBar);
processToken();
listenCast();
}
MediaRouteButton mediaRouteButton;
CastContext castContext;
RemoteMediaClient remoteMediaClient;
public boolean initCast() {
url = getIntent().getStringExtra(getString(R.string.url));
userAgent = getIntent().getStringExtra(getString(R.string.user_agent));
tokenEnable = getIntent().getBooleanExtra(getString(R.string.t_enable), false);
mediaRouteButton = (MediaRouteButton) findViewById(R.id.media_route_button);
CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), mediaRouteButton);
if (castContext == null)
castContext = CastContext.getSharedInstance(this);
castContext.addCastStateListener(new CastStateListener() {
#Override
public void onCastStateChanged(int state) {
/*if (state == CastState.NO_DEVICES_AVAILABLE) {
// mediaRouteButton.setVisibility(View.GONE);
}
else if(state==CastState.CONNECTING) {
showToast("Connecting");
} else*/ if (state == CastState.CONNECTED) {
// showToast("Connected");
// castMetadata();
openCastPlayer();
}/* else if (mediaRouteButton.getVisibility() == View.GONE) {
mediaRouteButton.setVisibility(View.VISIBLE);
}*/
}
});
if (castContext.getCastState() == CastState.CONNECTED) {
openCastPlayer();
return true;
} else {
// showToast("not connected");
}
if (castContext.getCastState() != CastState.NO_DEVICES_AVAILABLE)
mediaRouteButton.setVisibility(View.VISIBLE);
return false;
}
private void registerListener() {
if (mCastContext != null) {
mCastContext.getSessionManager().addSessionManagerListener(
mSessionManagerListener, CastSession.class);
}
}
private void unRegisterListener() {
if (mCastContext != null) {
mCastContext.getSessionManager().removeSessionManagerListener(
mSessionManagerListener, CastSession.class);
}
}
private void showToast(String connecting) {
Toast.makeText(this, connecting, Toast.LENGTH_SHORT).show();
}
private void processToken() {
if (!HelperClass.isValid(url) || !tokenEnable) {
init("");
return;
}
HashMap<String, Object> hashMap = new HashMap<>();
enqueue(getLocInterface().getLoc(sessionManager.getToken(), hashMap), new CallBack<Location>() {
#Override
public void onComplete() {
super.onComplete();
}
#Override
public void onError(Throwable e) {
super.onError(e);
Toast.makeText(Exo_Player.this,
"Failed to process url", Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(#NotNull Location location) {
super.onNext(location);
if (location.appendResult != null)
init(location.appendResult);
}
});
}
private void init(String s) {
url += s;
Log.e(TAG, "init: new url is " + url);
mediaDataSourceFactory = buildDataSourceFactory(true);
mainHandler = new Handler();
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
RenderersFactory renderersFactory = new DefaultRenderersFactory(this);
// TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
// TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
// TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
player = new SimpleExoPlayer.Builder(this, renderersFactory).setLoadControl(loadControl).build();
playerView = findViewById(R.id.exoPlayerView);
playerView.setPlayer(player);
playerView.setUseController(true);
playerView.requestFocus();
Uri uri = Uri.parse(url);
final MediaSource mediaSource = buildMediaSource(uri, null);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
player.addListener(new Player.Listener() {
#Override
public void onTracksChanged(#NotNull TrackGroupArray trackGroups, #NotNull TrackSelectionArray trackSelections) {
Log.d(TAG, "onTracksChanged: " + trackGroups.length);
}
#Override
public void onIsLoadingChanged(boolean isLoading) {
Log.d(TAG, "onLoadingChanged: " + isLoading);
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
Log.d(TAG, "onPlayerStateChanged: " + playWhenReady);
if (playbackState == PlaybackStateCompat.STATE_PLAYING) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(#NotNull PlaybackException error) {
Log.e(TAG, "onPlayerError: ", error);
player.stop();
// errorDialog();
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}
#Override
public void onPositionDiscontinuity(int reason) {
Log.d(TAG, "onPositionDiscontinuity: true");
}
#Override
public void onPlaybackParametersChanged(#NotNull PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
Log.d("INFO", "ActivityVideoPlayer");
}
private void pausePlayer() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
private void startPlayer() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
protected void onPause() {
super.onPause();
try {
unRegisterListener();
pausePlayer();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
/////////////////////////////////////////////
try {
registerListener();
if (HelperClass.vpn(this)) {
finish();
}
startPlayer();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG, "onDestroy()...");
if (player != null)
player.release();
}
private MediaSource buildMediaSource(Uri uri, String overrideExtension) {
int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri)
: Util.inferContentType("." + overrideExtension);
switch (type) {
case C.TYPE_SS:
return new SsMediaSource.Factory(new DefaultSsChunkSource.Factory(mediaDataSourceFactory), buildDataSourceFactory(false)).createMediaSource(uri);
case C.TYPE_DASH:
return new DashMediaSource.Factory(new DefaultDashChunkSource.Factory(mediaDataSourceFactory), buildDataSourceFactory(false)).createMediaSource(uri);
case C.TYPE_HLS:
return new HlsMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);
case C.TYPE_OTHER:
return new ProgressiveMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
}
public DataSource.Factory buildDataSourceFactory(DefaultBandwidthMeter bandwidthMeter) {
return new DefaultDataSourceFactory(this, bandwidthMeter,
buildHttpDataSourceFactory(bandwidthMeter));
}
public HttpDataSource.Factory buildHttpDataSourceFactory(DefaultBandwidthMeter bandwidthMeter) {
String s = "xxxxx";
if (userAgent != null && !userAgent.isEmpty()) {
s = userAgent;
}
return new DefaultHttpDataSourceFactory(getUserAgent2(this, s), bandwidthMeter);
}
public static String getUserAgent2(Context context, String applicationName) {
return applicationName
+ "";
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (interstitial != null) {
interstitial.show(Exo_Player.this);
}
if (player != null)
player.stop();
}
// public void errorDialog() {
// new AlertDialog.Builder(this)
// .setIcon(android.R.drawable.ic_dialog_alert)
// .setTitle(getResources().getString(R.string.msg_oops))
// .setCancelable(false)
// .setMessage(getResources().getString(R.string.msg_failed))
// .setPositiveButton(getResources().getString(R.string.option_retry), new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// retryLoad();
// z }
//
// })
// .setNegativeButton(getResources().getString(R.string.option_no), new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialogInterface, int i) {
// finish();
// }
// })
// .show();
// }
// public void retryLoad() {
// Uri uri = Uri.parse(url);
// MediaSource mediaSource = buildMediaSource(uri, null);
// player.prepare(mediaSource);
// player.setPlayWhenReady(true);
// }
public void castplayer(String name, String link, String unique, String img) {
if (!isCastApiAvailable()) {
return;
}
Context context = this;
CastSession castSession = CastContext.getSharedInstance(context).getSessionManager()
.getCurrentCastSession();
if (castSession.isConnected()) {
MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_GENERIC);
movieMetadata.putString(MediaMetadata.KEY_TITLE, name);
MediaInfo mediaInfo = new MediaInfo.Builder(link)
.setMetadata(movieMetadata)
.setEntity(unique)
.build();
final RemoteMediaClient remoteMediaClient = castSession.getRemoteMediaClient();
if (remoteMediaClient == null) {
// Timber.tag(TAG).w("showQueuePopup(): null RemoteMediaClient");
return;
}
if (remoteMediaClient.isPlaying()) {
MediaInfo curMedia = remoteMediaClient.getMediaInfo();
if (curMedia != null && curMedia.getEntity().equals(unique)) {
return;
}
}
if (remoteMediaClient.isLoadingNextItem() || remoteMediaClient.isBuffering()) {
return;
}
// final QueueDataProvider provider = QueueDataProvider.getInstance(context);
// PopupMenu popup = new PopupMenu(context, binding.epLayout);
// popup.getMenuInflater().inflate(
// provider.isQueueDetached() || provider.getCount() == 0
// ? R.menu.detached_popup_add_to_queue
// : R.menu.popup_add_to_queue, popup.getMenu());
// PopupMenu.OnMenuItemClickListener clickListener = menuItem -> {
// QueueDataProvider provider1 = QueueDataProvider.getInstance(context);
// MediaQueueItem queueItem = new MediaQueueItem.Builder(mediaInfo).setAutoplay(
// false).setPreloadTime(2).build();
// MediaQueueItem[] newItemArray = new MediaQueueItem[]{queueItem};
// String toastMessage = null;
// if (provider1.isQueueDetached() && provider1.getCount() > 0) {
// if ((menuItem.getItemId() == R.id.action_play_now)
// || (menuItem.getItemId() == R.id.action_add_to_queue)) {
// MediaQueueItem[] items = Utils
// .rebuildQueueAndAppend(provider1.getItems(), queueItem);
// remoteMediaClient.queueLoad(items, provider1.getCount(),
// MediaStatus.REPEAT_MODE_REPEAT_OFF, null);
// } else {
// return false;
// }
// } else {
// if (provider1.getCount() == 0) {
// remoteMediaClient.queueLoad(newItemArray, 0,
// MediaStatus.REPEAT_MODE_REPEAT_OFF, null);
// } else {
// int currentId = provider1.getCurrentItemId();
//// if (menuItem.getItemId() == R.id.action_play_now) {
// remoteMediaClient.queueInsertAndPlayItem(queueItem, currentId, null);
remoteMediaClient.load(mediaInfo, new MediaLoadOptions.Builder().build());
// } else if (menuItem.getItemId() == R.id.action_play_next) {
// int currentPosition = provider1.getPositionByItemId(currentId);
// if (currentPosition == provider1.getCount() - 1) {
// //we are adding to the end of queue
// remoteMediaClient.queueAppendItem(queueItem, null);
// } else {
// int nextItemId = provider1.getItem(currentPosition + 1).getItemId();
// remoteMediaClient.queueInsertItems(newItemArray, nextItemId, null);
// }
// toastMessage = context.getString(
// R.string.queue_item_added_to_play_next);
// } else if (menuItem.getItemId() == R.id.action_add_to_queue) {
// remoteMediaClient.queueAppendItem(queueItem, null);
// toastMessage = context.getString(R.string.queue_item_added_to_queue);
// } else {
// return false;
// }
// }
// }
// if (menuItem.getItemId() == R.id.action_play_now) {
Intent intent = new Intent(context, ExpandedControlsActivity.class);
context.startActivity(intent);
// }
// if (!TextUtils.isEmpty(toastMessage)) {
// Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
// }
// return true;
// };
// popup.setOnMenuItemClickListener(clickListener);
// popup.show();
// }
} else {
Toast.makeText(context,
"Not Connected", Toast.LENGTH_SHORT).show();
}
}
private CastContext mCastContext;
private CastSession mCastSession;
private SessionManagerListener<CastSession> mSessionManagerListener;
private void listenCast() {
if (!isCastApiAvailable()) {
return;
}
setupCastListener();
mCastContext = CastContext.getSharedInstance(this);
mCastSession = mCastContext.getSessionManager().getCurrentCastSession();
}
private void setupCastListener() {
mSessionManagerListener = new SessionManagerListener<CastSession>() {
#Override
public void onSessionEnded(CastSession session, int error) {
onApplicationDisconnected();
mCastContext = null;
mCastSession = null;
}
#Override
public void onSessionResumed(CastSession session, boolean wasSuspended) {
onApplicationConnected(session);
}
#Override
public void onSessionResumeFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarted(CastSession session, String sessionId) {
onApplicationConnected(session);
}
#Override
public void onSessionStartFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarting(CastSession session) {
}
#Override
public void onSessionEnding(CastSession session) {
}
#Override
public void onSessionResuming(CastSession session, String sessionId) {
}
#Override
public void onSessionSuspended(CastSession session, int reason) {
}
private void onApplicationConnected(CastSession castSession) {
mCastSession = castSession;
openCastPlayer();
invalidateOptionsMenu();
}
private void onApplicationDisconnected() {
invalidateOptionsMenu();
}
};
}
private void openCastPlayer() {
castplayer(getString(R.string.app_name), url, url, url);
finish();
}
}
I remember that was changed with the newer updates at some point last year. Now you need to pass a map to setDefaultRequestProperties after building a HttpDataSource. Using a DefaultHttpDataSource.Factory should be enough if you are not considering using a custom one.
I am working on a side project in android studio and need to store some long term data to a file that can be written and readable, I am able to do this outside of android studio, but when I try to do it within, it sows a error saying
public void onClick(View v) 'onClick(View)' in 'Anonymous class derived from android.view.View.OnClickListener' clashes with 'onClick(View)' in 'android.view.View.OnClickListener'; overridden method does not throw 'java.io.FileNotFoundException'{
I have a function in a separate file that writes to a string from a file, but when I try to access that string from one of my main view pages, its asking for an exception, but will not work with said exception, I've tried try and catch but with no success
File being initialized and written:
package com.example.stellarisspeciesrandomizer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class DLCPage extends AppCompatActivity {
public static int[] DLCArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.dlc_page);
try {
File myObj = new File("hasDLC.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
DLCArray = new int[1];
Button doneButton = (Button) findViewById(R.id.button_done);
doneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws IOException {
writeToFile();
finish();
}});
ImageButton aquaticsCheckbox = (ImageButton) findViewById(R.id.aquatic_checkbox);
aquaticsCheckbox.setTag("1");
//hello
aquaticsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (aquaticsCheckbox.getTag() == "1") {
aquaticsCheckbox.setImageResource(R.drawable.checked);
aquaticsCheckbox.setTag("2");
DLCArray[0] = 1;
} else if (aquaticsCheckbox.getTag() == "2") {
aquaticsCheckbox.setImageResource(R.drawable.checkmark);
aquaticsCheckbox.setTag("1");
DLCArray[0] = 0;
}
}
});
ImageButton humanoidCheckbox = (ImageButton) findViewById(R.id.humanoid_checkbox);
humanoidCheckbox.setTag("1");
humanoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (humanoidCheckbox.getTag() == "1") {
humanoidCheckbox.setImageResource(R.drawable.checked);
humanoidCheckbox.setTag("2");
DLCArray[1] = 1;
} else if (humanoidCheckbox.getTag() == "2") {
humanoidCheckbox.setImageResource(R.drawable.checkmark);
humanoidCheckbox.setTag("1");
DLCArray[1] = 0;
}
}
});
ImageButton plantoidCheckbox = (ImageButton) findViewById(R.id.plantoid_checkbox);
plantoidCheckbox.setTag("1");
plantoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (plantoidCheckbox.getTag() == "1") {
plantoidCheckbox.setImageResource(R.drawable.checked);
plantoidCheckbox.setTag("2");
DLCArray[2] = 1;
} else if (plantoidCheckbox.getTag() == "2") {
plantoidCheckbox.setImageResource(R.drawable.checkmark);
plantoidCheckbox.setTag("1");
DLCArray[2] = 0;
}
}
});
ImageButton syntheticCheckbox = (ImageButton) findViewById(R.id.synthetic_checkbox);
syntheticCheckbox.setTag("1");
syntheticCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (syntheticCheckbox.getTag() == "1") {
syntheticCheckbox.setImageResource(R.drawable.checked);
syntheticCheckbox.setTag("2");
DLCArray[3] = 1;
} else if (syntheticCheckbox.getTag() == "2") {
syntheticCheckbox.setImageResource(R.drawable.checkmark);
syntheticCheckbox.setTag("1");
DLCArray[3] = 0;
}
}
});
ImageButton necroidCheckbox = (ImageButton) findViewById(R.id.necroids_checkbox);
necroidCheckbox.setTag("1");
necroidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (necroidCheckbox.getTag() == "1") {
necroidCheckbox.setImageResource(R.drawable.checked);
necroidCheckbox.setTag("2");
DLCArray[4] = 1;
} else if (necroidCheckbox.getTag() == "2") {
necroidCheckbox.setImageResource(R.drawable.checkmark);
necroidCheckbox.setTag("1");
DLCArray[4] = 0;
}
}
});
ImageButton lithoidCheckbox = (ImageButton) findViewById(R.id.lithoids_checkbox);
lithoidCheckbox.setTag("1");
lithoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (lithoidCheckbox.getTag() == "1") {
lithoidCheckbox.setImageResource(R.drawable.checked);
lithoidCheckbox.setTag("2");
DLCArray[5] = 1;
} else if (lithoidCheckbox.getTag() == "2") {
lithoidCheckbox.setImageResource(R.drawable.checkmark);
lithoidCheckbox.setTag("1");
DLCArray[5] = 0;
}
}
});
ImageButton ancientCheckbox = (ImageButton) findViewById(R.id.ancient_checkbox);
ancientCheckbox.setTag("1");
ancientCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (ancientCheckbox.getTag() == "1") {
ancientCheckbox.setImageResource(R.drawable.checked);
ancientCheckbox.setTag("2");
DLCArray[6] = 1;
} else if (ancientCheckbox.getTag() == "2") {
ancientCheckbox.setImageResource(R.drawable.checkmark);
ancientCheckbox.setTag("1");
DLCArray[6] = 0;
}
}
});
ImageButton federationsCheckbox = (ImageButton) findViewById(R.id.federations_checkbox);
federationsCheckbox.setTag("1");
federationsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (federationsCheckbox.getTag() == "1") {
federationsCheckbox.setImageResource(R.drawable.checked);
federationsCheckbox.setTag("2");
DLCArray[7] = 1;
} else if (federationsCheckbox.getTag() == "2") {
federationsCheckbox.setImageResource(R.drawable.checkmark);
federationsCheckbox.setTag("1");
DLCArray[7] = 0;
}
}
});
ImageButton apocalypseCheckbox = (ImageButton) findViewById(R.id.apocalypse_checkbox);
apocalypseCheckbox.setTag("1");
apocalypseCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (apocalypseCheckbox.getTag() == "1") {
apocalypseCheckbox.setImageResource(R.drawable.checked);
apocalypseCheckbox.setTag("2");
DLCArray[8] = 1;
} else if (apocalypseCheckbox.getTag() == "2") {
apocalypseCheckbox.setImageResource(R.drawable.checkmark);
apocalypseCheckbox.setTag("1");
DLCArray[8] = 0;
}
}
});
ImageButton utopiaCheckbox = (ImageButton) findViewById(R.id.utopia_checkbox);
utopiaCheckbox.setTag("1");
utopiaCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (utopiaCheckbox.getTag() == "1") {
utopiaCheckbox.setImageResource(R.drawable.checked);
utopiaCheckbox.setTag("2");
DLCArray[9] = 1;
} else if (utopiaCheckbox.getTag() == "2") {
utopiaCheckbox.setImageResource(R.drawable.checkmark);
utopiaCheckbox.setTag("1");
DLCArray[9] = 0;
}
}
});
}
public static void writeToFile() throws IOException {
int len = DLCArray.length;
for (int i = 0; i < len; i++) {
FileWriter writer = new FileWriter("hasDLC.txt");
writer.write(DLCArray[i] + "\t"+ "");
}
}
}
second page
package com.example.stellarisspeciesrandomizer;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Randomizer {
private static int[] tall= new int[3] ;
public static String RandomSpecies(String origin) throws FileNotFoundException {
readFile();
Random random = new Random();
ArrayList<String> originArray = new ArrayList<String>();
String origins1 = "Prosperous Unification";
String origins2 = "Galactic Doorstep";
String origins3 = "Lost Colony";
String origins4 = "Here Be Dragons";
String origins5 = "Ocean Paradise";
String origins6 = "Clone Army";
String origins7 = "Necrophage";
String origins18 = "Resource Consolidation";
String origins19 = "Remnants";
String origins16 = "Life Seeded";
String origins17 = "Post-Apocalyptic";
String origins8 = "Remnants";
String origins9 = "Shattered Ring";
String origins10 = "Void Dwellers";
String origins11 = "Scion";
String origins12 = "On The Shoulders of Giants";
String origins13 = "Common Ground";
String origins14 = "Hegemon";
String origins15 = "Doomsday";
String origin20 = "Syncretic Evolution";
String origin21 = "Mechanist";
String origin22 = "String of Life";
originArray.add(origins4);
originArray.add(origins5);
originArray.add(origins6);
originArray.add(origins7);
originArray.add(origins18);
originArray.add(origins19);
originArray.remove(origins17);
originArray.remove(origins16);
originArray.add(origins8);
originArray.add(origins9);
originArray.add(origins10);
originArray.add(origins11);
originArray.add(origins12);
originArray.add(origins13);
originArray.add(origins14);
originArray.add(origins15);
originArray.add(origin20);
originArray.add(origin21);
originArray.add(origin22);
originArray.add(origins1);
originArray.add(origins2);
originArray.add(origins3);
origin = originArray.get(random.nextInt(originArray.size()));
return origin;
}
public static void readFile() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("hasDLC.txt"));
tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
System.out.println(tall);
}
}
last page
package com.example.stellarisspeciesrandomizer;
import static com.example.stellarisspeciesrandomizer.Randomizer.RandomSpecies;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileNotFoundException;
public class RandomizerHome extends AppCompatActivity {
String hi = "hi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.randomizer_layout);
ImageView originImageView =(ImageView) findViewById(R.id.originImageView);
Intent dlcIntent = new Intent(this, DLCPage.class);
Button dlcButton = (Button) findViewById(R.id.dlc_button);
dlcButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dlcIntent);
}
});
Button randomizeButton = (Button) findViewById(R.id.randomize_button);
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
String originTrue = "hi";
originTrue = RandomSpecies(hi);
switch(originTrue){
case ("Prosperous Unification"): originImageView.setImageResource(R.drawable.prosperousunification);break;
case ("Galactic Doorstep"): originImageView.setImageResource(R.drawable.galacticdoorstep);break;
case ("Lost Colony"): originImageView.setImageResource(R.drawable.lostcolony);break;
case ("Here Be Dragons"): originImageView.setImageResource(R.drawable.here_be_dragons);break;
case ("Ocean Paradise"): originImageView.setImageResource(R.drawable.ocean_paradise);break;
case ("Clone Army"): originImageView.setImageResource(R.drawable.clones);break;
case ("Necrophage"): originImageView.setImageResource(R.drawable.necrophage);break;
case ("Resource Consolidation"): originImageView.setImageResource(R.drawable.resource_consolidation);break;
case ("Remnants"): originImageView.setImageResource(R.drawable.remnant);break;
case ("Life Seeded"): originImageView.setImageResource(R.drawable.life_seeded);break;
case ("Post-Apocalyptic"): originImageView.setImageResource(R.drawable.post_apocalyptic);break;
case ("Shattered Ring"): originImageView.setImageResource(R.drawable.shattered_ring);break;
case ("Void Dwellers"): originImageView.setImageResource(R.drawable.void_dwellers);break;
case ("Scion"): originImageView.setImageResource(R.drawable.scion);break;
case ("On The Shoulders of Giants"): originImageView.setImageResource(R.drawable.on_the_shoulders_of_giant);break;
case ("Common Ground"): originImageView.setImageResource(R.drawable.common_ground);break;
case ("Hegemon"): originImageView.setImageResource(R.drawable.hegemon);break;
case ("Doomsday"): originImageView.setImageResource(R.drawable.doomsday);break;
case ("Syncretic Evolution"): originImageView.setImageResource(R.drawable.syncretic_evolution);break;
case ("Mechanist"): originImageView.setImageResource(R.drawable.mechanist);break;
case ("Tree of Life"): originImageView.setImageResource(R.drawable.tree_of_life);break;
}
System.out.println(originTrue);
}
});
}
}
Here:
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
What you are doing here: define an anonymous subclass of View.OnClickListener. And when you check the documentation for that class, it says:
public abstract void onClick (View v)
Now read the compiler message again you got. overridden method does not throw 'java.io.FileNotFoundException'
Thus the real answer here is: A) you have to understand what you are doing and B) you have to read compiler error messages really carefully.
Long story short, you can not override an inherited method and add checked exceptions such as FileNotFoundException to the signature of your method. So, the solution is to step back and to really learn/understand how exception handling works in Java. One possibility here: use try/catch in your readFile(), catch the FileNotFoundException and rethrow it as (unchecked) RuntimeException. Then you do not need to have throws FileNotFoundException on your method signatures, and the compiler won't complain any more.
I'm not android studio developer or java developer but regarding for my graduation project I need to make an android app that connects to HC-05 Bluetooth module "Arduino", then starts to transmit and receive bytes ... I have found a lot of projects that connects to the Bluetooth module by showing you a list of Bluetooth devices then you can choose which one you want to connect ...
but I don't want to use this method I want to find a method that searches for a specific Bluetooth mac address and if it available, start connecting to it, if it not available, the app will continue searching ...
I don't have any experience how can programmatically make this.
so please be patient :D
I have done the XML design...
I want to add the mac address connecting code here
package mdluex.smartx;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
this is the XML design
Activity Design
the full project code on GitHub
I found the solution :D
thanks, guys ...
My full project contains this code:
package mdluex.smartx;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
String deviceName = "HC-05";
BluetoothDevice result = null;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//Serial Port Service ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
if (devices != null) {
for (BluetoothDevice device : devices) {
if (deviceName.equals(device.getName())) {
Toast.makeText(getApplicationContext(),"SamrtX is available ",Toast.LENGTH_SHORT).show();
result = device;
boolean connected=true;
try {
socket = result.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
connected=false;
Toast.makeText(getApplicationContext(),"SamrtX is not available ",Toast.LENGTH_SHORT).show();
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
if (socket!=null)
{
try
{
socket.getOutputStream().write("a".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
if (socket!=null)
{
try
{
socket.getOutputStream().write("b".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
I have small problem. My problem is auto refresh to list messages.
How can instantly check data such as WhatsApp ?
If you would like to automatically update data came from.
I do not know exactly how I can do , so I'm waiting for your help .
Code
MessagingActivity.java
package com.socialnetwork.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.socialnetwork.R;
import com.socialnetwork.adapters.MessagesAdapter;
import com.socialnetwork.animation.ViewAudioProxy;
import com.socialnetwork.api.APIService;
import com.socialnetwork.api.ChatAPI;
import com.socialnetwork.api.UsersAPI;
import com.socialnetwork.data.MessagesItem;
import com.socialnetwork.data.userItem;
import com.socialnetwork.helpers.M;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MessagingActivity extends AppCompatActivity implements OnClickListener {
public Intent mIntent = null;
private MediaRecorder recorder = null;
private String outFile = null;
private TextView recordTimeText;
private ImageButton audioSendButton;
private View recordPanel;
private View slideText;
private float startedDraggingX = -1;
private float distCanMove = dp(80);
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private Timer timer;
public int RECIPIENT_ID = 0,
CONVERSATION_ID = 0;
public LinearLayoutManager layoutManager;
private EditText messageField;
private String messageBody, USERNAME;
private MessagesAdapter messageAdapter;
private List<MessagesItem> mMessages = new ArrayList<MessagesItem>();
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
Bundle data = intent.getBundleExtra("data");
if (Integer.parseInt(data.getString("ownerID")) == RECIPIENT_ID) {
MessagesItem newMsg = new MessagesItem();
newMsg.setOwnerName(data.getString("ownerName"));
newMsg.setId(Integer.parseInt(data.getString("id")));
newMsg.setMessage(data.getString("message"));
newMsg.setDate(data.getString("date"));
newMsg.setOwnerUsername(data.getString("ownerUsername"));
newMsg.setOwnerPicture(data.getString("ownerPicture"));
newMsg.setOwnerID(Integer.parseInt(data.getString("ownerID")));
newMsg.setConversationID(Integer.parseInt(data.getString("conversationID")));
addMessage(newMsg);
} else {
Intent resultIntent = new Intent(MessagingActivity.this, MessagingActivity.class);
resultIntent.putExtra("data", intent);
M.showNotification(MessagingActivity.this, resultIntent,
data.getString("ownerUsername"),
data.getString("message"),
Integer.parseInt(data.getString("conversationID")));
}
}
};
private RecyclerView messagesList;
private LinearLayout attachLayout;
private RelativeLayout recordPannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
setContentView(R.layout.messaging);
initializer();
if (getIntent().hasExtra("conversationID")) {
CONVERSATION_ID = getIntent().getExtras().getInt("conversationID");
}
if (getIntent().hasExtra("recipientID")) {
RECIPIENT_ID = getIntent().getExtras().getInt("recipientID");
}
getUser();
getMessages();
}
}
public void initializer() {
messagesList = (RecyclerView) findViewById(R.id.listMessages);
messageAdapter = new MessagesAdapter(this, mMessages);
messagesList.setAdapter(messageAdapter);
//
layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
messagesList.setLayoutManager(layoutManager);
messageField = (EditText) findViewById(R.id.messageField);
attachLayout = (LinearLayout) findViewById(R.id.attachLayout);
recordPannel = (RelativeLayout) findViewById(R.id.record_pannel);
recordPanel = findViewById(R.id.record_panel);
recordTimeText = (TextView) findViewById(R.id.recording_time_text);
slideText = findViewById(R.id.slideText);
audioSendButton = (ImageButton) findViewById(R.id.chat_audio_send_button);
TextView textView = (TextView) findViewById(R.id.slideToCancelTextView);
textView.setText("Slide To Cancel");
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.attachBtn).setOnClickListener(this);
findViewById(R.id.sendBtn).setOnClickListener(this);
findViewById(R.id.micBtn).setOnClickListener(this);
audioSendButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
startRecording();
audioSendButton.getParent()
.requestDisallowInterceptTouchEvent(true);
recordPanel.setVisibility(View.VISIBLE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP
|| motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
startedDraggingX = -1;
stopRecording();
recordPannel.setVisibility(View.GONE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
float x = motionEvent.getX();
if (x < -distCanMove) {
stopRecording();
}
x = x + ViewAudioProxy.getX(audioSendButton);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
if (startedDraggingX != -1) {
float dist = (x - startedDraggingX);
params.leftMargin = dp(30) + (int) dist;
slideText.setLayoutParams(params);
float alpha = 1.0f + dist / distCanMove;
if (alpha > 1) {
alpha = 1;
} else if (alpha < 0) {
alpha = 0;
}
ViewAudioProxy.setAlpha(slideText, alpha);
}
if (x <= ViewAudioProxy.getX(slideText) + slideText.getWidth()
+ dp(30)) {
if (startedDraggingX == -1) {
startedDraggingX = x;
distCanMove = (recordPanel.getMeasuredWidth()
- slideText.getMeasuredWidth() - dp(48)) / 2.0f;
if (distCanMove <= 0) {
distCanMove = dp(80);
} else if (distCanMove > dp(80)) {
distCanMove = dp(80);
}
}
}
if (params.leftMargin > dp(30)) {
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
}
}
view.onTouchEvent(motionEvent);
return true;
}
});
}
private void getUser() {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(RECIPIENT_ID, new Callback<userItem>() {
#Override
public void success(userItem userItem, retrofit.client.Response response) {
if (userItem.getName() != null) {
getSupportActionBar().setTitle(userItem.getName());
} else {
getSupportActionBar().setTitle(userItem.getUsername());
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
messageAdapter.stop();
}
public void getMessages() {
M.showLoadingDialog(this);
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.getMessages(CONVERSATION_ID, RECIPIENT_ID, 1, new Callback<List<MessagesItem>>() {
#Override
public void success(List<MessagesItem> messagesItems, Response response) {
mMessages = messagesItems;
messageAdapter.setMessages(messagesItems);
M.hideLoadingDialog();
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.L(getString(R.string.ServerError));
}
});
}
private void sendMessage() {
messageBody = messageField.getText().toString().trim();
if (!messageBody.isEmpty()) {
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.addMessage(messageBody, CONVERSATION_ID, RECIPIENT_ID, new Callback<MessagesItem>() {
#Override
public void success(MessagesItem messagesItem, Response response) {
if (messagesItem != null) {
mMessages.add(messagesItem);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
messageField.setText("");
} else {
M.T(MessagingActivity.this, getString(R.string.SomethingWentWrong));
}
}
#Override
public void failure(RetrofitError error) {
M.T(MessagingActivity.this, getString(R.string.ServerError));
}
});
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.attachBtn) {
if (attachLayout.getVisibility() == View.GONE) {
attachLayout.setVisibility(View.VISIBLE);
} else {
attachLayout.setVisibility(View.GONE);
}
if (recordPannel.getVisibility() == View.VISIBLE) {
recordPannel.setVisibility(View.GONE);
}
} else if (v.getId() == R.id.sendBtn) {
sendMessage();
} else if (v.getId() == R.id.micBtn) {
attachLayout.setVisibility(View.GONE);
recordPannel.setVisibility(View.VISIBLE);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter("update_messages_list"));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mMessageReceiver);
}
public void addMessage(MessagesItem newMsg) {
mMessages.add(newMsg);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
}
private void startRecording() {
try {
startRecordingAudio();
} catch (IOException e) {
e.printStackTrace();
}
startTime = SystemClock.uptimeMillis();
timer = new Timer();
MyTimerTask myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 1000, 1000);
vibrate();
}
private void stopRecording() {
if (timer != null) {
timer.cancel();
}
if (recordTimeText.getText().toString().equals("00:00")) {
return;
}
recordTimeText.setText("00:00");
vibrate();
Toast.makeText(getApplicationContext(), "Stop Recording", Toast.LENGTH_SHORT).show();
stopRecordingAudio();
}
public void startRecordingAudio() throws IOException {
Toast.makeText(getApplicationContext(), "Start Recording...", Toast.LENGTH_SHORT).show();
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH.mm.ss");
String fileName = "audio_" + timeStampFormat.format(new Date())
+ ".mp3";
outFile = "/sdcard/";// Environment.getExternalStorageDirectory().getAbsolutePath();
stopRecordingAudio();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outFile + fileName);
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
recorder.prepare();
recorder.start();
}
public void stopRecordingAudio() {
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private void vibrate() {
// TODO Auto-generated method stub
try {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int dp(float value) {
return (int) Math.ceil(1 * value);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
final String hms = String.format(
"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(updatedTime)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(updatedTime)),
TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime)));
long lastsec = TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime));
System.out.println(lastsec + " hms " + hms);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (recordTimeText != null)
recordTimeText.setText(hms);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
}
}
MessagesFragment.java
public class MessagesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public RecyclerView conversationList;
public ConversationsAdapter mConversationsAdapter;
public List<ConversationItem> mConversations = new ArrayList<ConversationItem>();
public Intent mIntent = null;
public int currentPage = 1;
public LinearLayoutManager layoutManager;
private View mView;
private SwipeRefreshLayout mSwipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_messages, container, false);
conversationList = (RecyclerView) mView
.findViewById(R.id.conversationsList);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_messages);
initializeView();
conversationList.setOnScrollListener(new HidingScrollListener(layoutManager) {
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onLoadMore(int currentPage) {
setCurrentPage(currentPage);
getConversations();
}
});
mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeMessages);
mSwipeRefreshLayout.setOnRefreshListener(this);
getConversations();
return mView;
}
public void initializeView() {
mConversationsAdapter = new ConversationsAdapter(getActivity(),
mConversations);
conversationList.setAdapter(mConversationsAdapter);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
conversationList.setLayoutManager(layoutManager);
}
public void getConversations() {
M.showLoadingDialog(getActivity());
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(getActivity()));
mChatAPI.getConversations(getCurrentPage(), new Callback<List<ConversationItem>>() {
#Override
public void success(List<ConversationItem> conversationItems, retrofit.client.Response response) {
M.L(response.getBody().mimeType());
mConversationsAdapter.setConversations(conversationItems);
M.hideLoadingDialog();
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
}
});
}
#Override
public void onRefresh() {
setCurrentPage(1);
getConversations();
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
WhatsApp is not instant check. It's is more like:
Screen off, check 10x after 30s, next 10x after 1m, next 3x after 5m and so on. and start again if the screen turns off again. WhatsApp is checkin in the background also when you close the app. They are using a service.
In my program, I have only 1 button. And first press the program will output a random string. If the user presses it again to stop, my program will slow random (delay) the same slot machine. How can I do it?
my code
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while (showRandom) {
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Ignoring the MediaPlayer part, I think it should be this way:
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Randomsentence.R;
public class Randomsentence extends Activity {
TextView txt;
int random;
public String[] myStrings;
Button bt1;
private static final int MESSAGE_RANDOM = 1;
private static final long MIN_INTERVAL = 500;
private static final long MAX_INTERVAL = 1500;
private static final long STEP = 60;
private long mInterval = 0;
private boolean mStarted = false;
private Random mRandom = new Random();
private Handler mHandler = new Handler() {
#Override
public void handleMessage (Message msg) {
if(msg.what == MESSAGE_RANDOM) {
showRandomString();
if(mStarted) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
} else {
if(mInterval <= MAX_INTERVAL) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
mInterval += STEP;
} else {
this.removeMessages(MESSAGE_RANDOM);
Toast.makeText(Randomsentence.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(mBt1OnClick);
myStrings = getResources().getStringArray(R.array.myArray);
}
private void showRandomString() {
final int index = mRandom.nextInt(myStrings.length - 1);
txt.setText(myStrings[index]);
}
private OnClickListener mBt1OnClick = new OnClickListener() {
#Override
public void onClick(View v) {
if(!mStarted) {
// Start
Toast.makeText(Randomsentence.this, "Started!", Toast.LENGTH_SHORT).show();
mStarted = true;
mInterval = MIN_INTERVAL;
mHandler.removeMessages(MESSAGE_RANDOM);
mHandler.sendEmptyMessage(MESSAGE_RANDOM);
} else {
// Stop
mStarted = false;
Toast.makeText(Randomsentence.this, "Stoping...", Toast.LENGTH_SHORT).show();
}
}
};
}