Android Equalizer is not working after leaving the Equalizer Activity - java

Hope you are doing well.
I am tryring to create a Music Player Application where i am using the below pre-created equalizer package from GitHub.
https://github.com/bullheadandplato/AndroidEqualizer
The issue is,as soon as i am leaving the Equalizer activity, music is playing in normal way and equalizer effetcs are stopping.
I tried to created a service but no luck.
My code for Music Player View
package com.subhrajit.omegamusicplayer;
import static com.subhrajit.omegamusicplayer.AllTracksAdapter.convertTimeMMSS;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.audiofx.AudioEffect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bullhead.equalizer.DialogEqualizerFragment;
import com.bullhead.equalizer.EqualizerFragment;
import com.bumptech.glide.Glide;
import com.chibde.visualizer.BarVisualizer;
import com.chibde.visualizer.SquareBarVisualizer;
import java.io.IOException;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class MusicPlayerView extends AppCompatActivity {
SquareBarVisualizer barVisualizer;
Toolbar playerToolBar;
LinearLayout mainPlayer;
ImageView pausePlay, next, previous,repeat,shuffle,lovedSong;
CircleImageView albumArt;
TextView songName,songStart,songTotalTime;
SeekBar songDuration;
ArrayList<Song> songList=new ArrayList<>();
Song currentSong;
static MediaPlayer mediaPlayer=PlayerInstance.getInstance();
int x=0; //To set Rotation
Context context;
Song nowPlaying;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player_view);
context=getApplication().getApplicationContext();
//Top Parent ViewGroup
mainPlayer=findViewById(R.id.playerMainLayout);
//Toolbar of Play Activity
playerToolBar=findViewById(R.id.musicPlayerToolBar);
//Album Art of Song
albumArt=findViewById(R.id.imgAlbumArt);
//Loved Song
lovedSong=findViewById(R.id.lovedSong);
//AllButtons
pausePlay=findViewById(R.id.btnPlayPause);
next=findViewById(R.id.btnNext);
previous=findViewById(R.id.btnBack);
repeat=findViewById(R.id.btnRepeat);
shuffle=findViewById(R.id.btnShuffle);
shuffle.setSelected(false);
//Song Seekbar
songDuration=findViewById(R.id.songProgress);
//Text Views to show Song information while playing
songName=findViewById(R.id.songName);
songName.setSelected(true);
songTotalTime=findViewById(R.id.songTotalTime);
songStart=findViewById(R.id.songStartTime);
//Visualizer Position Set
barVisualizer=findViewById(R.id.barVisualizer);
// set custom color to the line.
barVisualizer.setColor(ContextCompat.getColor(this, R.color.secondary_color));
// define custom number of bars you want in the visualizer between (10 - 256).
barVisualizer.setDensity(18);
// Set Spacing
barVisualizer.setGap(5);
//Setting Player Activity Toolbar
setSupportActionBar(playerToolBar);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//Fetching Data From Adapter to this activity
songList=((ArrayList<Song>)getIntent().getSerializableExtra("Songs"));
if (songList!=null){
setDataWithMusic();
}else{
Toast.makeText(this,"Null Data",Toast.LENGTH_LONG).show();
}
//Setting Selected Song Part
lovedSong.setOnClickListener(v->{
if (!songList.get(PlayerInstance.currentIndex).isLoved()){
songList.get(PlayerInstance.currentIndex).setLoved(true);
lovedSong.setImageResource(R.drawable.after_heart);
}else{
songList.get(PlayerInstance.currentIndex).setLoved(false);
lovedSong.setImageResource(R.drawable.before_heart);
}
});
//Declaring New Thread so that Seekbar and progress value can be changed realtime
MusicPlayerView.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer!=null){
songDuration.setProgress(mediaPlayer.getCurrentPosition());
songStart.setText(convertTimeMMSS(String.valueOf(mediaPlayer.getCurrentPosition())));
albumArt.setRotation(x++);
if (mediaPlayer.isPlaying()){
pausePlay.setImageResource(R.drawable.pause);
}else{
pausePlay.setImageResource(R.drawable.play);
albumArt.setRotation(0);
}
}
new Handler().postDelayed(this,100);
}
});
//Setting Music Seekbar to work
songDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser){
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public int setDataWithMusic() {
currentSong = songList.get(PlayerInstance.currentIndex);
nowPlaying=songList.get(PlayerInstance.currentIndex);
//Setting AlbumArt
byte[]art=getAlbumArt(currentSong.getPath());
if (art!=null){
Glide.with(context.getApplicationContext()).asBitmap()
.load(art)
.into(albumArt);
}else{
Glide.with(getApplicationContext()).asBitmap()
.load(R.drawable.default_albumart)
.into(albumArt);
}
songName.setText(currentSong.getTitle());
songTotalTime.setText(convertTimeMMSS(currentSong.getDuration()));
songStart.setText("00:00");
pausePlay.setOnClickListener(v->pausePlayMusic());
previous.setOnClickListener(v->previousMusic());
next.setOnClickListener(v->nextMusic());
repeat.setOnClickListener(v->{
if (mediaPlayer.isLooping()){
repeat.setImageResource(R.drawable.before_repeat);
mediaPlayer.setLooping(false);
}else{
repeat.setImageResource(R.drawable.after_repeat);
mediaPlayer.setLooping(true);
}
});
shuffle.setOnClickListener(v->{
});
try{
playMusic();
}catch (Exception ex){
Log.e("Error",ex.toString());
}
return PlayerInstance.currentIndex;
}
//AlbumArt Retriever Method
public byte[] getAlbumArt(String uri){
MediaMetadataRetriever retriever=new MediaMetadataRetriever();
retriever.setDataSource(uri);
byte[]art=retriever.getEmbeddedPicture();
retriever.release();
return art;
}
private void playMusic() throws IOException {
mediaPlayer.reset();
mediaPlayer.setDataSource(currentSong.getPath());
mediaPlayer.prepare();
mediaPlayer.start();
songDuration.setProgress(0);
songDuration.setMax(mediaPlayer.getDuration());
//To play songs after completion if available
mediaPlayer.setOnCompletionListener(v->{
nextMusic();
});
barVisualizer.setPlayer(mediaPlayer.getAudioSessionId());
}
private void nextMusic() {
if (PlayerInstance.currentIndex==songList.size()-1 || mediaPlayer.isLooping()){
return;
}
PlayerInstance.currentIndex+=1;
mediaPlayer.reset();
setDataWithMusic();
}
private void previousMusic() {
if (PlayerInstance.currentIndex==0 || mediaPlayer.isLooping()){
return;
}
PlayerInstance.currentIndex-=1;
mediaPlayer.reset();
setDataWithMusic();
}
private void pausePlayMusic() {
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}else{
mediaPlayer.start();
}
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.music_player_toolbar_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.showEQ:
startService(new Intent(getApplicationContext(),EqualizerService.class));
getSupportFragmentManager().beginTransaction()
.replace(R.id.eqFrame,new EqualizerService().getEqualizerFragment())
.commit();
//startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
My code to implement Equalizer as a service
package com.subhrajit.omegamusicplayer;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import androidx.annotation.Nullable;
import com.bullhead.equalizer.EqualizerFragment;
public class EqualizerService extends Service {
EqualizerFragment equalizerFragment;
public EqualizerFragment getEqualizerFragment(){
equalizerFragment = EqualizerFragment.newBuilder()
.setAccentColor(Color.parseColor("#4caf50"))
.setAudioSessionId(PlayerInstance.getInstance().getAudioSessionId())
.build();
return equalizerFragment;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getEqualizerFragment();
return START_STICKY;
}
}
MusicPlayerView.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/playerMainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/black"
tools:context=".MusicPlayerView">
<include layout="#layout/music_player_toolbar" />
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/eqFrame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/songName"
android:layout_width="match_parent"
android:layout_height="60dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="TextView"
android:textColor="#color/white"
android:textSize="30dp"
android:textStyle="italic" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imgAlbumArt"
android:layout_width="wrap_content"
android:layout_height="234dp"
android:layout_margin="20dp"
android:src="#drawable/profile"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp" />
<ImageView
android:id="#+id/lovedSong"
android:layout_width="match_parent"
android:layout_height="43dp"
app:srcCompat="#drawable/before_heart" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:layout_gravity="center_vertical"
android:layout_marginTop="30dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/btnShuffle"
android:layout_width="70dp"
android:layout_height="match_parent"
android:defaultFocusHighlightEnabled="true"
app:srcCompat="#drawable/shuffle" />
<ImageView
android:id="#+id/btnBack"
android:layout_width="70dp"
android:layout_height="match_parent"
android:defaultFocusHighlightEnabled="true"
app:srcCompat="#drawable/back" />
<ImageView
android:id="#+id/btnPlayPause"
android:layout_width="70dp"
android:layout_height="match_parent"
android:defaultFocusHighlightEnabled="true"
app:srcCompat="#drawable/pause" />
<ImageView
android:id="#+id/btnNext"
android:layout_width="70dp"
android:layout_height="match_parent"
android:defaultFocusHighlightEnabled="true"
app:srcCompat="#drawable/next" />
<ImageView
android:id="#+id/btnRepeat"
android:layout_width="70dp"
android:layout_height="match_parent"
android:defaultFocusHighlightEnabled="true"
app:srcCompat="#drawable/before_repeat" />
</LinearLayout>
<SeekBar
android:id="#+id/songProgress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="10dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginStart="14dp"
android:orientation="horizontal">
<TextView
android:id="#+id/songStartTime"
android:layout_width="147dp"
android:layout_height="49dp"
android:layout_marginEnd="110dp"
android:textColor="#color/white"
android:layout_weight="5"
android:textStyle="bold"
android:text="TextView"
android:textSize="20dp" />
<TextView
android:id="#+id/songTotalTime"
android:layout_width="wrap_content"
android:layout_height="49dp"
android:layout_weight="5"
android:textSize="20dp"
android:textColor="#color/white"
android:textStyle="bold"
android:text="TextView" />
</LinearLayout>
<com.chibde.visualizer.SquareBarVisualizer
android:id="#+id/barVisualizer"
android:layout_width="match_parent"
android:layout_height="250dp" >
</com.chibde.visualizer.SquareBarVisualizer>
</LinearLayout>
</ScrollView>
</LinearLayout>
Please help me here

Related

How to increase speed of BLE scanning Android Studio?

I want make some application, it will scanning nearby BLE and sending to server via MQTT. But the scanning proccess to slow. I want to increase the speed of scanning.
mainActivity.java
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
handler.postDelayed(this, 1000);
}
}, 1000);
final Handler handlerStop = new Handler();
handlerStop.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothAdapter.cancelDiscovery();
handlerStop.postDelayed(this, 2000);
}
}, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
bluetoothAdapter.startDiscovery();
}
}
}else {
bluetoothAdapter.cancelDiscovery();
}
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
mqttActivity.java
package com.example.mqtt_active;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MqttActivity extends AppCompatActivity {
private EditText server,port,id;
private Button save;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqtt);
server = findViewById(R.id.serverMQTT);
id = findViewById(R.id.mqttTopic);
port = findViewById(R.id.mqttPort);
save = findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.mqtt_id = id.getText().toString();
MainActivity.mqtt_port = port.getText().toString();
MainActivity.mqtt_server = server.getText().toString();
startActivity(new Intent(MqttActivity.this,MainActivity.class));
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/turnon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.452" />
<Button
android:id="#+id/mqttSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set MQTT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.511"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/turnon"
app:layout_constraintVertical_bias="0.073" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.524"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mqttSet"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_mqtt.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/serverMQTT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Server"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="MQTT SERVER"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="MQTT TOPIC"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/serverMQTT" />
<EditText
android:id="#+id/mqttTopic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Topic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="MQTT PORT"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mqttTopic" />
<EditText
android:id="#+id/mqttPort"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Port"
app:layout_constraintBottom_toTopOf="#+id/saveButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/textView3"
app:layout_constraintVertical_bias="0.298" />
</androidx.constraintlayout.widget.ConstraintLayout>
How to increase speed of scanning nearby BLE? i expect from this forum, i can increase speed of scanning nearby BLE.

Getting duplicated cardviews using SwipeRefresh Layout

So here is my problem, I got an API that gives me the lastest news of many sources. Each one of them goes with a cardview. The problem here is, while I'm using the swipeRefresh, it gets duplicated cardViews with the same news, like if I have 10 news, it duplicates to 20 with the same ones.
Here is my code where I apply the swipeRefresh:
package com.example.newsapp4;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.newsapp4.Model.Articles;
import com.example.newsapp4.Model.Headlines;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class bbcnews extends AppCompatActivity {
Adapter adapter;
Intent intencion;
RecyclerView recyclerView;
public static String source = "My Source";
public static String API_KEY = "My API Key";
SwipeRefreshLayout srl;
List<Articles> articles = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bbcnews);
srl = findViewById(R.id.swipeRefresh);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(source, API_KEY);
}
});
recyclerView = findViewById(R.id.recyclerView1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(bbcnews.this,articles);
recyclerView.setAdapter(adapter);
retrieveJson(source, API_KEY);
}
public void retrieveJson(String source, String apiKey){
srl.setRefreshing(true);
Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(source, apiKey);
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if(response.isSuccessful() && response.body().getArticles() != null){
srl.setRefreshing(false);
articles.clear();
articles = response.body().getArticles();
adapter.setArticles(articles);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
srl.setRefreshing(false);
Toast.makeText(bbcnews.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
public void aPerfil(View vista){
intencion = new Intent(this, profile_activity.class);
startActivity(intencion);
}
}
I don't think that I need to put the xml code with the progressbar and the swipeRefresh but here are both:
This one is the Items.xml where I created the cardView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardElevation="4dp"
android:id="#+id/cardView"
app:cardCornerRadius="10dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/loader"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/image"
android:scaleType="centerCrop"
android:src="#drawable/img"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="20dp"
android:padding="10dp"
android:fontFamily="#font/g_bold"
android:textColor="#color/white"
android:id="#+id/tvTitle"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Source"
android:textSize="16dp"
android:padding="10dp"
android:ems="15"
android:fontFamily="#font/g_light"
android:textColor="#color/white"
android:id="#+id/tvSource"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/g_light"
android:gravity="right"
android:text="Date"
android:textColor="#color/white"
android:padding="10dp"
android:textSize="16dp"
android:id="#+id/tvDate"/>
</LinearLayout>
</FrameLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And here the one with the swipeRefresh in the recyclerView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
tools:context=".bbcnews">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DINGO BBC NEWS"
android:textColor="#color/black"
android:textSize="20sp"
android:fontFamily="#font/g_bold"
android:background="#color/white"
android:padding="10dp"
android:textAlignment="center"/>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:columnCount="2"
android:paddingLeft="20dp"
android:paddingRight="5dp"
android:background="#drawable/black_background"
android:rowCount="2">
<EditText
android:id="#+id/editTextTextPersonName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Search"
android:textColor="#color/grey"
android:textColorHint="#color/grey"
android:padding="5dp"
android:layout_column="0"
android:background="#drawable/black_background"
android:layout_row="0"
android:layout_columnWeight="1"
android:inputType="textPersonName" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:background="#drawable/black_background"
android:drawableRight="#drawable/ic_baseline_search_24"
android:layout_column="1"
android:layout_row="0"/>
</GridLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipeRefresh">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:id="#+id/recyclerView1"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
Also this is my adapter.java code:
package com.example.newsapp4;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.newsapp4.Model.Articles;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
holder.tvTitle.setText(a.getTitle());
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(a.getPublishedAt());
Picasso.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return articles.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle,tvSource,tvDate;
ImageView imageView;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
}
}
public void setArticles(List<Articles> articles) {
this.articles.addAll(articles);
int count = getItemCount();
notifyItemRangeInserted(count, count + articles.size());
}
}
Thanks for your time!
// Clear adapter list before add to list.
public void setArticles(List<Articles> articles) {
if(this.articles!=null && this.articles.size()>0)
this.articles.clear();
this.articles.addAll(articles);
int count = getItemCount();
notifyItemRangeInserted(count, count + articles.size());
}
From what I can understand in your code is on the success of API call after Swipe Refresh which is this section here
articles.clear();
articles = response.body().getArticles();
adapter.setArticles(articles);
You are here clearing the article inside your activity, but the thing is inside your Adapter there is already another list of articles, you are not clearing them.
And then when you make the adapter.setArticles(articles); call, inside the following function, your articles get added to the already existing list of articles and thus, the duplicate list.
public void setArticles(List<Articles> articles) {
this.articles.addAll(articles);
int count = getItemCount();
notifyItemRangeInserted(count, count + articles.size());
}
To fix this you can make the following modifications to your function.
public void setArticles(List<Articles> articles, boolean clearAll) {
if(clearAll){ this.articles.clear(); }
this.articles.addAll(articles);
notifyDataSetChanged();
}
And then modify your function call as follows
adapter.setArticles(articles, true);
That way when the Boolean is true, it will clear the existing list. Also I would suggest you to replace the insert call with data set change call. Else you can make a separate function all together for adding elements and for clearing existing elements.

It doesn't send the data from Activity to Fragment

I have lots of layouts and activites and fragments. There are tabs in one activity called Hastane1 and it has four tabs in it. They don't have any problem but one of them has. I wanted to send a data from one Activity to a Fragment. They are seperate. Fragment is in Hastane1 activity but Haberlesme1 activity is in another place. It supposed to send the numbers which i entered in the activity called Haberlesme1 to the textView in the fragment called Hastane1Tab3Frag which is a tab of Hastane1.
The Android Studio itself doesn't have any errors but when i run the app on my phone, it stops when i pressed the button called "Gönder" (#id/button8).
Haberlesme1 (Activity):
package com.example.projev021.İllerPackage.KocaeliPackage.GebzePackage.GebzeFragments.Hastane1Fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.projev021.HaberlesmePackage.Haberlesme1;
import com.example.projev021.R;
public class Hastane1Tab3Frag extends Fragment {
Button goster;
TextView sonucText;
int sayi=0;
Haberlesme1.Ogrenci ogr;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.hastane1_tab3,container,false);
goster=(Button)v.findViewById(R.id.button13);
sonucText = (TextView)v.findViewById(R.id.textView3);
goster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sonucText.setText(sayi);
}
});
return v;
}
public void sendData(int birinciSayi) {
this.sayi=birinciSayi;
}
public void sendOgrenci(Haberlesme1.Ogrenci ogrenci) {
this.ogr=ogrenci;
}
}
haberlesme1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:fontFamily="#font/lineto_circular_black"
android:text="#string/kackisivar"
android:textSize="50sp"/>
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:ems="10"
android:inputType="number"
android:text="" />
<Button
android:id="#+id/button8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:background="#drawable/buttonshape"
android:fontFamily="#font/lineto_circular_black"
android:text="#string/gonder"
android:textColor="#FFC107"
android:textSize="30sp"
android:onClick="calistir"/>
</LinearLayout>
Hastane1Tab3Frag (Fragment):
package com.example.projev021.İllerPackage.KocaeliPackage.GebzePackage.GebzeFragments.Hastane1Fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.projev021.HaberlesmePackage.Haberlesme1;
import com.example.projev021.R;
public class Hastane1Tab3Frag extends Fragment {
Button goster;
TextView sonucText;
int sayi=0;
Haberlesme1.Ogrenci ogr;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.hastane1_tab3,container,false);
goster=(Button)v.findViewById(R.id.button13);
sonucText = (TextView)v.findViewById(R.id.textView3);
goster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sonucText.setText(sayi);
}
});
return v;
}
public void sendData(int birinciSayi) {
this.sayi=birinciSayi;
}
public void sendOgrenci(Haberlesme1.Ogrenci ogrenci) {
this.ogr=ogrenci;
}
}
hastane1tab3.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginStart="10dp"
android:fontFamily="#font/lineto_circular_black"
android:text="#string/kisisayisi_"
android:textSize="50sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:fontFamily="#font/lineto_circular_black"
android:text=""
android:textSize="100sp"
android:textColor="#000000" />
<Button
android:id="#+id/button13"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:background="#drawable/buttonshape"
android:fontFamily="#font/lineto_circular_black"
android:text="#string/goster"
android:textColor="#FFC107"
android:textSize="30sp"/>
</LinearLayout>
</FrameLayout>
And the screenshots:

Android Studio RecyclerView wont show my data when i add toolbar at my `layout.xml` file

I created a page where it will show the firebase data in a RecyclerView. It work but I decided to put a toolbar at the top of the page to have a back function. After I put the toolbar in my layout file, the RecyclerView is not showing any data anymore. I think that my layout XML file is wrong. Thanks in advance for anyone helping.
Actity file
package com.example.attendanceappvqyfyp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
import com.example.attendanceappvqyfyp.Common.Common;
import com.example.attendanceappvqyfyp.Model.LecturerClass;
import com.example.attendanceappvqyfyp.Model.News;
import com.example.attendanceappvqyfyp.Model.Timetable;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.attendanceappvqyfyp.Common.Common;
public class LecturerClassList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference lecturerclass;
DatabaseReference news;
FirebaseRecyclerAdapter<LecturerClass,LecturerClassViewHolder> adapter;
TextView newscourse, newsclass;
EditText newsdescription;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecturer_class_list);
//Firebase
database = FirebaseDatabase.getInstance();
lecturerclass = database.getReference("Class");
news = database.getReference("News");
recyclerView = (RecyclerView)findViewById(R.id.recycler_lecturerclass);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Toolbar code
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Class List");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
loadLecturerClass(Common.currentLecturer.getName());
}
private void loadLecturerClass(String Lecturer) {
adapter = new FirebaseRecyclerAdapter<LecturerClass, LecturerClassViewHolder>(LecturerClass.class, R.layout.lecturerclass_item, LecturerClassViewHolder.class, lecturerclass.orderByChild("lecturer").equalTo(Lecturer)) {
#Override
protected void populateViewHolder(LecturerClassViewHolder lecturerClassViewHolder, LecturerClass lecturerClass, int i) {
lecturerClassViewHolder.lclasstitle.setText("Class :" + adapter.getRef(i).getKey());
lecturerClassViewHolder.ldate.setText("Day :" + lecturerClass.getDay());
lecturerClassViewHolder.ltime.setText("Time :" + lecturerClass.getTime());
lecturerClassViewHolder.lclassroom.setText("Classroom :" + lecturerClass.getClassroom());
lecturerClassViewHolder.lcourse.setText(lecturerClass.getCourse());
lecturerClassViewHolder.setItemClickListener(new itemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//code later
}
});
}
};
recyclerView.setAdapter(adapter);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.News))
{
showNewsDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
}
return super.onContextItemSelected(item);
}
private void showNewsDialog(final String course, final LecturerClass item) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LecturerClassList.this);
alertDialog.setTitle("Make Announcement");
alertDialog.setMessage("Make announcement about this class.");
LayoutInflater inflater = this.getLayoutInflater();
View lecturer_make_news = inflater.inflate(R.layout.activity_lecturer_make_news, null);
newscourse = lecturer_make_news.findViewById(R.id.NewsCourse);
newsclass = lecturer_make_news.findViewById(R.id.NewsClass);
newsdescription = lecturer_make_news.findViewById(R.id.NewsDescription);
newscourse.setText("Course: "+item.getCourse());
newsclass.setText("Subject: " + course);
alertDialog.setView(lecturer_make_news);
alertDialog.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(newsdescription.getText().toString().isEmpty()){
Toast.makeText(LecturerClassList.this, "Post cancel, description cannot be empty.", Toast.LENGTH_SHORT).show();
}
else {
News lnews = new News(
item.getCourse(),
course,
newsdescription.getText().toString()
);
news.child(String.valueOf(System.currentTimeMillis())).setValue(lnews);
Toast.makeText(LecturerClassList.this, "Announcement post successfully.", Toast.LENGTH_SHORT).show();
finish();
}
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();;
}
});
alertDialog.show();
}
}
Activity file for viewholder
package com.example.attendanceappvqyfyp;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import com.example.attendanceappvqyfyp.Common.Common;
import androidx.recyclerview.widget.RecyclerView;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
public class LecturerClassViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener {
public TextView lclasstitle, ldate, ltime, lclassroom, lcourse;
private itemClickListener itemClickListener;
public LecturerClassViewHolder(View itemView) {
super(itemView);
lclasstitle = (TextView)itemView.findViewById(R.id.lclasstitle);
ldate = (TextView)itemView.findViewById(R.id.ldate);
ltime = (TextView)itemView.findViewById(R.id.ltime);
lclassroom = (TextView)itemView.findViewById(R.id.lclassroom);
lcourse = (TextView)itemView.findViewById(R.id.lcourse);
itemView.setOnCreateContextMenuListener(this);
itemView.setOnClickListener(this);
}
public void setItemClickListener(itemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select");
menu.add(0,0,getAdapterPosition(), Common.News);
}
}
Layout file for recyclerview
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LecturerClassList">
<android.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:theme="#style/ThemeOverlay.AppCompat.Dark" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_lecturerclass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout file for itemview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="160dp"
app:cardElevation="4dp"
android:layout_marginBottom="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lclasstitle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ldate"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/lclasstitle"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ltime"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/ldate"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lclassroom"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lcourse"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:visibility="invisible"
android:textColor="#android:color/black"
android:textSize="20sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Thanks to ZeePee for giving this link Display Back Arrow on Toolbar, although the toolbar didnt work for me, i change it back to actionbar and use the code from the link and it work.
Try adding horizontal constraints for Toolbar and Recycler View. After that you need to specify where do you want your single item widgets in Relative layout

Android ,thread id=1 thread exiting with uncaught exception

I am new to android development, was following a tutorial in order to get a better understanding about fragments, but after completing the tutorial when it comes to testing I encountered this particular problem after removing a few syntax errors. In the logcat I get "threadid=1: thread exiting with uncaught exception (group=0x40a7193" I've spent almost an entire working day on it, I've looked but it seems like the solution to this problem is dependent upon the source code, I've been on a number of links but everywhere there's some source code provided and I haven't found a solution for my problem so far, any help will be much appreciated. Here is My Code:
MainActivity.java:
package com.example.fragmentsexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements ToolbarFragments.ToolbarListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onButtonClick(int fontsize, String text) {
TextFragment textFragment =
(TextFragment) getSupportFragmentManager().findFragmentById(R.id.text_fragment);
textFragment.changeTextProperties(fontsize, text);
}
}
Here is TextFragment.java:
package com.example.fragmentsexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
private static TextView textview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.text_fragment, container,false);
textview=(TextView) view.findViewById(R.id.textView1);
return view;
}
public void changeTextProperties(int fontsize, String text){
textview.setTextSize(fontsize);
textview.setText(text);
}
}
Here is ToolbarFragments.java
package com.example.fragmentsexample;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolbarFragments extends Fragment {
private static int seekvalue=10;
private static EditText editText;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
activityCallback=(ToolbarListener) activity;
}
catch (Exception e){
throw new ClassCastException(activity.toString()+ "must implement ToolbarListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle SavedInstanceState){
View view=inflater.inflate(R.layout.toolbar_fragment, container, false);
editText=(EditText) view.findViewById(R.id.editText1);
final SeekBar seekbar=(SeekBar) view.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this);
final Button button=(Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked(View v){
activityCallback.onButtonClick(seekvalue,editText.getText().toString());
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
seekvalue=progress;
}
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
Here is the activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/toolbar_fragment"
android:name="com.example.fragmentexample.ToolbarFragments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/toolbar_fragment" />
<fragment
android:id="#+id/text_fragment"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/text_fragment" />
</RelativeLayout>
Here is the text_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/fragtwo"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Here is the toolbar_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="#string/button"/>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:layout_marginTop="14dp" />
</RelativeLayout>
Any help any sort of help will be appreciated it is my second post here i apologize for a messy post

Categories