How to increase speed of BLE scanning Android Studio? - java

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.

Related

Android Equalizer is not working after leaving the Equalizer Activity

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

Send data from Android to ESP32 with Bluetooth

I've searched many tutorials on stackoverflow but can't understand anything and no one has a similar code as me.
I just want to send an "a" when i click the OFF button and "A" when i click the "ON" button. I used the OutputStream.write method but it is not working.
Here is my code:
jetControl.java
package com.example.btjetski;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
public class jetControl extends AppCompatActivity {
Button buttonON1, buttonOFF1;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private final boolean isBtConnected = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jet_control);
Intent intent = getIntent();
address = intent.getStringExtra(Peripherique.EXTRA_ADDRESS); //recevoir l'adresse du périphérique BT
}
private void setOnClickListener() {
buttonON1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TurnOnJetski1();
}
});
buttonOFF1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TurnOffJetski1();
}
});
}
private void TurnOnJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("A".getBytes());
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
}
private void TurnOffJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("a".getBytes());
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
}
private void Disconnect() {
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
finish();
}
}
activity_jet_control.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".jetControl">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="4dp"
android:layout_marginTop="8dp"
android:text="Contrôle de JETSKI"
android:textSize="24dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="47dp"
android:layout_marginTop="95dp"
android:text="Jetski 1"
android:textSize="18sp" />
<Button
android:id="#+id/buttonON1"
android:layout_width="81dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="129dp"
android:backgroundTint="#12730C"
android:text="ON" />
<Button
android:id="#+id/buttonOFF1"
android:layout_width="77dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="86dp"
android:layout_marginTop="129dp"
android:backgroundTint="#FF0000"
android:text="OFF" />
</RelativeLayout>

Mapbox Fragment inside another activity

I'm trying to create an application that tracks a user's eyes while driving which will also show turn by turn navigation. There will be a camera preview on the same screen as the maps, similar to the image below, where the camera preview is in the top left and the maps is below
I have a MapBox activity working in a seperate file, MapsActivity.java. I want to run the Mapbox activity inside a fragment in an activty test.java which does the eye tracking.
I have looked at tutorials and online resources but cannot find out how to get it to work for my particular code. Apologies if this is a simple question, this is my first app.
MapsActivity.java
package com.example.drivesafely;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
// classes needed to initialize map
// classes needed to add the location component
// classes needed to add a marker
// classes to calculate a route
// classes needed to launch navigation UI
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, PermissionsListener {
// variables for adding location layer
private MapView mapView;
private MapboxMap mapboxMap;
// variables for adding location layer
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
// variables for calculating and drawing a route
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
// variables needed to initialize navigation
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_maps);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
mapboxMap.addOnMapClickListener(MapsActivity.this);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MapsActivity.this, options);
}
});
}
});
}
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
#SuppressWarnings( {"MissingPermission"})
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
activity_maps
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_cameraZoom="12" />
<Button
android:id="#+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="#color/mapboxGrayLight"
android:enabled="false"
android:text="Start navigation"
android:textColor="#color/mapboxWhite"
mapbox:layout_constraintStart_toStartOf="parent"
mapbox:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/background"
android:background="#fcfcfc"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
tools:context=".test">
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="400dp"
android:layout_height="300dp"
android:background="#f567"
mapbox:layout_constraintTop_toBottomOf="#+id/preview"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_cameraZoom="12" />
<Button
android:id="#+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="260dp"
android:layout_marginEnd="16dp"
android:background="#color/mapboxGrayLight"
android:enabled="false"
android:text="Start navigation"
android:textColor="#color/mapboxWhite"
tools:layout_constraintStart_toStartOf="parent"
tools:layout_constraintTop_toTopOf="parent" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:layout_alignParentBottom="true"
android:layout_weight="0"
android:background="#19b5fe"
android:gravity="center|center_horizontal"
android:weightSum="2">
<Button
android:id="#+id/button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginRight="5dp"
android:background="#E0E0E0"
android:text="#string/end" />
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="200dp"
android:layout_height="40dp"
android:background="#drawable/rounded_corners"
android:checked="false"
android:text="New ToggleButton"
android:textColor="#ffff"
android:textOff="#string/turn_preview_off"
android:textSize="12dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Status: "
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</RelativeLayout>
<com.example.drivesafely.CameraSourcePreview
android:id="#+id/preview"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_gravity="center_horizontal">
<com.example.drivesafely.GraphicOverlay
android:id="#+id/faceOverlay"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.drivesafely.CameraSourcePreview>
</androidx.constraintlayout.widget.ConstraintLayout>
It is not possible to run Activity inside another Activity, in your case you can't run MapsActivity in your TestActivity. This is possible with some other solutions but the easiest one for you is to use Fragments. What you can do is to convert your MakeActivity to Fragment and then place it inside TestActivity. Learn how Fragments and Activities work in Android since you'll be using them a lot.
Here are some links to read:
https://developer.android.com/reference/android/app/Fragment.html
https://developer.android.com/guide/fragments
You can put a Maps SDK for Android map fragment inside of your TestActivity or inside a separate fragment
https://docs.mapbox.com/android/maps/examples/support-map-fragment/
https://docs.mapbox.com/android/maps/examples/?search=fragment

Android Studio Beginner: Keep Getting NoSuchMethodException for android.graphics.FontFamily. <init> []

I keep getting this error whenever I run the application, which crashes every time I interact with it. The problem first occurred after I moved the original TextView around and altered the color and Font Style. I'm not sure why it's happening now, but it didn't happen before. I'm not exactly sure why this error is occurring either. Please help.
Below is the error message:
E/TypefaceCompatApi26Impl: Unable to collect necessary methods for class java.lang.NoSuchMethodException
java.lang.NoSuchMethodException: android.graphics.FontFamily.<init> []
This is the MainActivity class:
package com.example.exploreroptimizer;
import android.app.ActivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final Cleaner cleaner = new Cleaner();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cleanButton = findViewById(R.id.cleanButton);
final ProgressBar cleanBar = findViewById(R.id.progressBar);
final TextView progressUpdate = findViewById(R.id.progressUpdate);
System.out.println("success");
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Thread thread = new Thread() {
#Override
public void run() {
try {
final ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
final double a = mi.availMem / 0x100000L;
cleanBar.setProgress(20);
progressUpdate.setText("Cleaning Ram!");
Thread.sleep(1500);
cleanBar.setProgress(40);
progressUpdate.setText("Closing Unused Apps!");
Thread.sleep(1500);
cleanBar.setProgress(100);
progressUpdate.setText("Clearing Cache!");
Thread.sleep(1500);
Cleaner.deleteCache(getApplicationContext());
cleaner.killBackgroundProcesses(getApplicationContext(), getApplicationContext().getPackageManager());
cleaner.clearRAM();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "I have closed " + Cleaner.i + " apps, ", Toast.LENGTH_SHORT).show();
}
});
} catch (InterruptedException e) {
}
}
};
thread.start();
}
});
}
}
And this is the xml file code for the UI:
<?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=".MainActivity">
<Button
android:id="#+id/cleanButton"
android:layout_width="172dp"
android:layout_height="166dp"
android:background="#drawable/cleanbutton"
android:fontFamily="sans-serif"
android:text="Clean"
android:textColor="#FFFFFF"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="312dp"
android:layout_height="382dp"
android:indeterminate="false"
android:max="0"
android:progress="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/progressUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:text="TextView"
android:textColor="#0DB344"
android:textSize="18sp"
android:textStyle="normal|bold"
android:typeface="sans"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/progressBar" />
</androidx.constraintlayout.widget.ConstraintLayout>

XML files contain code, but preview is blank

so i have a project where im implementing a google sign in, i followed this tutorial on how to do that, but when i did, all my XML files appear blank. i made changes to the original MainActivity.java and the activity_main.xml file. i woudl think that only the activity_main.xml would be affected, but all of my XML files appear blank. when i try to run the app, i get
"Error:Content is not allowed in prolog.
" and
"Execution failed for task '.app:builderInfoDebugLoader'"
this is my activity main where i implement the google sign in:
package com.example.mayankthakur.personalprojecttrial2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.signin.SignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private LinearLayout prof_section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Picture;
private Button continueBut;
private static final int REQ_CODE = 9001;
String name;
Intent nameSave;
private GoogleApiClient mGoogleApiClient;
public static final String prefsName = "com.example.mayankthakur.personalprojecttrial2";
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
prof_section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.logoutBtn);
SignIn = (SignInButton) findViewById(R.id.gSignIn);
Name = (TextView) findViewById(R.id.nameSpace);
Email = (TextView) findViewById(R.id.emailSpace);
Prof_Picture = (ImageView) findViewById(R.id.profilePicture);
continueBut = (Button) findViewById(R.id.button2);
continueBut.setOnClickListener(this);
SignOut.setOnClickListener(this);
SignIn.setOnClickListener(this) ;
prof_section.setVisibility(View.GONE);
continueBut.setVisibility(View.GONE);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
#Override
public void onClick (View v) {
switch (v.getId()) {
case R.id.gSignIn:
signIn();
break;
case R.id.logoutBtn:
signOut();
break;
/*// This is the shared preference
SharedPreferences.Editor prefs = getSharedPreferences(prefsName, MODE_PRIVATE).edit();
//adding a value to the preference
prefs.putString("name", name);
prefs.apply();
nameSave = new Intent(MainActivity.this, Activity2.class);
MainActivity.this.startActivity(nameSave);
*/
}
}
#Override
public void onConnectionFailed (#NonNull ConnectionResult connectionResult){
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQ_CODE );
}
private void signOut(){
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleReuslt(GoogleSignInResult result){
if(result.isSuccess())
{
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
String imgUrl = acct.getPhotoUrl().toString();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Name.setText(personName);
Email.setText(personEmail);
Glide.with(this).load(imgUrl).into(Prof_Picture);
updateUI(true);
}
else
{
updateUI(false);
}
}
private void updateUI(boolean isLogin){
if(isLogin)
{
prof_section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
}
else
{
prof_section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleReuslt(result);
}
}
}
this is my XML file where i added the buttons and stuff for the google sign in:\
<?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:id="#+id/activity_main"
android:orientation="vertical"
tools:context="com.example.mayankthakur.personalprojecttrial2.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/prof_section"
android:layout_marginLeft="20dp"
android:layout_marginTop = "50dp"
android:weightSum="1">
<ImageView
android:id="#+id/profilePicture"
android:layout_width="90dp"
android:layout_height="100dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:src="#drawable/photo"
android:layout_weight="0.25" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp">
<TextView
android:id="#+id/nameSpace"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name Display"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/emailSpace"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Email Display"
android:textSize="14dp"
android:textStyle="bold" />
<Button
android:id="#+id/logoutBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/gSignIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp">
</com.google.android.gms.common.SignInButton>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please Sign in in order to make use of all of the features of the app"
android:textAlignment="center"
android:textSize="20dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Continue"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"/>
</LinearLayout>
any help would be greatly appreciated, and if any of you require any more code please do ask
thanks in advance!

Categories