How to set drawable on an imageview using rxjava and rxandroid - java

I am able to use text using rxjava and rxandroid in my code using Textview. Now i m thinking of replacing the textview with imageview and displaying the drawable on the imageview. But I m getting errors. Since, I m new to rxjava, I m probably sure that I m missing something. An help would be really gr8!
Since to show a text, we used the parameter as String...So I thought for a drawable, I thought I might need the parameter as a Drawable...But its giving error..
package com.prajwal.rxjava_rxandroid;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
ImageView textView;
Observable<Integer> stringObservable;
DisposableObserver<Drawable> disposableObserver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview);
stringObservable = Observable.just(R.drawable.ic_launcher_background);
disposableObserver = new DisposableObserver<Drawable>() {
#Override
public void onNext(Drawable drawable) {
Glide.with(getApplicationContext()).load(drawable).into(textView);
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
};
stringObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(disposableObserver);
}
#Override
protected void onDestroy() {
super.onDestroy();
disposableObserver.dispose();
}
}
Error: Cannot resolve method subscribe(Drawable)

Find out the solution:
package com.prajwal.rxjava_rxandroid;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
ImageView textView;
Observable<Integer> stringObservable;
DisposableObserver<Integer> disposableObserver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview);
stringObservable = Observable.just(R.drawable.ic_launcher_background);
/*
stringObserver = new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String s) {
textView.setText(s); //emitted data is set to textview.
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
};
*/
disposableObserver = new DisposableObserver<Integer>() {
#Override
public void onNext(Integer integer) {
Glide.with(getApplicationContext()).load(integer).asBitmap().into(textView);
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
};
stringObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(disposableObserver);
}
#Override
protected void onDestroy() {
super.onDestroy();
disposableObserver.dispose();
}
}
I was passing the parameter as Drawable whereas I needed to pass the
parameter as an Integer since .load() of Glide doesnt take Drawable as
a parameter.

Related

Admob Interstitial the ad does not appear, what is wrong?

even putting the test id does not appear, I've made countless attempts, I found that it can be linked to mInterstitialAd.isLoaded (), but I can't solve it
I also tried to make modifications to the mInterstitialAd.setAdListener, nothing else happens, can someone help me?
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
public class SplashActivity extends Activity {
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener()
{
#Override
public void onAdClosed() {
super.onAdClosed();
doFunc();
}
}
);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(mInterstitialAd.isLoaded())
{
mInterstitialAd.show();
}else
{
doFunc();
}
}
},5000);
}
private void doFunc() {
startActivity(new Intent(SplashActivity.this,MainActivity.class));
//
}
}

Exo player Activity

please can exo player a hls stream like this
http://m3ulink.com:7899/gtZcA8Ugs/po5dA7Vm07/111804
I can play hls links with this .m3u8 file extension but I cant play those without the .m3u8 file extension
If anyone could help i will be grateful. Please i am at the beginner level so if someone can help me look into this thanks
//code
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
public class VideoPlayerActivity extends AppCompatActivity {
private PlayerView videoPlayer;
private SimpleExoPlayer simpleExoPlayer;
private static final String FILE_URL = "";
ProgressBar progressBar;
ImageView btFullScreen;
boolean flag = false;
private Handler mainHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_video_player);
videoPlayer = findViewById(R.id.exo_player);
progressBar = findViewById(R.id.progress_bar);
btFullScreen = videoPlayer.findViewById(R.id.bt_fullscreen);
setUpExoplayer(getIntent().getStringExtra("url"));
simpleExoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_BUFFERING) {
progressBar.setVisibility(View.VISIBLE);
} else if (playbackState == Player.STATE_READY) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
btFullScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (flag) {
btFullScreen.setImageDrawable(getResources().getDrawable(R.drawable.ic_fullscreen));
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
flag = false;
} else {
btFullScreen.setImageDrawable(getResources().getDrawable(R.drawable.ic_fullscreen_exit));
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
flag = true;
}
}
});
}
private void setUpExoplayer(String url) {
new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new
AdaptiveTrackSelection.Factory();
TrackSelector trackSelector = new
DefaultTrackSelector(videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
Handler mainHandler = new Handler();
simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
videoPlayer.setPlayer(simpleExoPlayer);
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,"");
MediaSource mediaSource = new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(url),mainHandler,null );
videoPlayer.setKeepScreenOn(true);
simpleExoPlayer.prepare(mediaSource);
simpleExoPlayer.setPlayWhenReady(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
simpleExoPlayer.release();
}
#Override
protected void onPause() {
super.onPause();
simpleExoPlayer.setPlayWhenReady(true);
simpleExoPlayer.getPlaybackState();
}
#Override
protected void onRestart() {
super.onRestart();
simpleExoPlayer.setPlayWhenReady(true);
simpleExoPlayer.getPlaybackState();
}
}

Continuously outputting index of an array

I have an array that I want to output each index continuously and randomly
here is my code :
package com.example.testtingskripsi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public String [] ArrayA ={"80","81","82","83","84","85"};
public TextView mViewLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
int rando =(int) ((Math.random())*ArrayA.length);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewLabel = (TextView) findViewById(R.id.textChanger);
Button startHeartbeat = (Button) findViewById(R.id.start);
Button stopHeartbeat = (Button) findViewById(R.id.stop);
startHeartbeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
for(int mIfCounter = 0;mIfCounter<ArrayA.length-1;mIfCounter++){
mViewLabel.setText(ArrayA[mIfCounter]);
}
}
}, 1000);
}
});
}
}
the output doesn't change only showing one index and doesn't change to the next index
edit:
it does work but on the output, it only shows the last index but still doesn't change
edit 2:
Okay so I fixed it with new code and try some of you guys help
this is new code
package com.example.testtingskripsi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
public String [] ArrayA ={"80","81","82","83","84","85"};
public TextView mViewLabel;
boolean continueThread=true;
int count =0;
Thread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewLabel = (TextView) findViewById(R.id.textChanger);
List<String> list = Arrays.asList(ArrayA);
Collections.shuffle(list);
t = new Thread(){
#Override
public void run() {
while(continueThread){
try{
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(count<=6){
count++;
}else{
count--;
}
mViewLabel.setText(list.get(count));
}
});
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
public void BtnStart(View view){
t.start();;
}
public void BtnStop(View view){
continueThread=false;
}
}
it stop at end of array, so i want it to doing the loop until i pressed stop button any help
Already figured it out so okay thank you all for helling me
You probably need to add some delay inside the for loop.
Try Thread.sleep inside the loop.
The device changes 60 fps so its hard to view the changes for a small loop

Why is my app not displaying recorded message?

So, I am creating an AI music player app. Everything seems fine but whenever I give it some voice command, it does not display the required message.
I have tried using different emulators and using different android versions. None of those worked.
package com.learning.intelligentmusicplayer;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private RelativeLayout parentRelativeLayout;
private SpeechRecognizer speechRecognizer;
private Intent speechRecogniserIntent;
private String keeper="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkVoiceCommandPermission();
parentRelativeLayout = findViewById(R.id.parentRelativeLayout);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(MainActivity.this);
speechRecogniserIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecogniserIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM );
speechRecogniserIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> matchesFound = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matchesFound!=null)
{
keeper = matchesFound.get(0);
Toast.makeText(MainActivity.this, "Result = "+keeper, Toast.LENGTH_LONG).show();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
parentRelativeLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
speechRecognizer.startListening(speechRecogniserIntent);
keeper="";
break;
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
break;
}
return false;
}
});
}
private void checkVoiceCommandPermission()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(!(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO)==PackageManager.PERMISSION_GRANTED))
{
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package: "+getPackageName()));
startActivity(intent);
finish();
}
}
}
}
There is no error message. I hear the beep sound for recording message but it does not display the message on screen.
Downloading Google voice assistant fixed my problem!

Error with InitLoader again

I want to create a loader for my list view but got
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, context)
know this error is very common but tried to import different library still error. Really appreciate if someone can point out why. Thanks in advance!
my code:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.app.Fragment;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.Activity;
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
//showNoteList();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
//String ds = note_database.getData();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.noteListAdapter);
getLoaderManager().initLoader(0, null, context);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context, note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context,data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
// THE LOADER
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_note_items;
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
this.loader_db = db;
}
#Override
protected void onStartLoading() {
if (loader_note_items != null) {
deliverResult(loader_note_items); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open(); // Query the database
ArrayList<NoteItems> note_items = loader_db.getNote_items();
loader_db.close();
return loader_note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
loader_note_items = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_note_items = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_note_items = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}

Categories

Resources