how can i change imagebuttons automatically after what users want? - java

I making an app which you can use to start other apps like Netflix on. I have four imagebuttons on the first XML file which is going to be the "Favorites". When you click on any of these imagebuttons you start the intent for the app you wanted to start. Then the app gets opened. How can I make it so that the Favorites changes automatically after what the user uses.
Here is my Java Code:
package com.carlo_projekt.tvprograms;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Locale;
' public class MainActivity extends AppCompatActivity {
ImageButton speakBtn;
Button CategoriesBtn;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speakBtn = (ImageButton) findViewById(R.id.SpeakImageBtn);
CategoriesBtn = (Button) findViewById(R.id.CategoriesBtn);
text = (TextView) findViewById(R.id.textView);
}
public void OpenGame(View view) {
Intent intent = new Intent(this, MoreActivity.class);
startActivity(intent);
}
public void Speak(View view)
{
Intent recognizeIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizeIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
recognizeIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
recognizeIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi! Which app do you want to start?");
try {
startActivityForResult(recognizeIntent, 1);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(MainActivity.this, "Sorry! Your device doesn't support this function!", Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int request_Code, int result_Code, Intent recognizeIntent)
{
super.onActivityResult(request_Code, result_Code, recognizeIntent);
switch (request_Code)
{
case 1: if(result_Code == RESULT_OK && recognizeIntent != null)
{
ArrayList<String> result = recognizeIntent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(int i = 0; i<result.size(); i++)
{
result.set(i, result.get(i).toLowerCase());
if(result.get(i).compareTo("start netflix") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.netflix.mediaclient");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start youtube") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.youtube");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start viafree") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.viafree.android");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start tvfour") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.tv4.tv4playtab");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start dplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.kanal5play");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start viaplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.viaplay.android");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start svtplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.svt.android.svtplay");
startActivity(NetflixIntent);
}
/**text.setText(result.get(i));*/
}
}
}
}
public void OpenApps(String packageName)
{
if(getPackageManager().getLaunchIntentForPackage(packageName) != null)
{
Intent tv4PlayIntent = getPackageManager().getLaunchIntentForPackage(packageName);
startActivity(tv4PlayIntent);
}
else
{
String marketAppPackageName = "market://details?id="+ packageName;
MessageBox(marketAppPackageName);
}
}
public void NetflixFunction(View view)
{
String netflixPackageName = new String("com.netflix.mediaclient");
OpenApps(netflixPackageName);
}
public void ViafreeFunction(View view)
{
String viafreePackageName = new String("se.viafree.android");
OpenApps(viafreePackageName);
}
public void YoutubeFunction(View view)
{
String youtubePackageName = new String("com.google.android.youtube");
OpenApps(youtubePackageName);
}
public void Tv4PlayFunction(View view)
{
String tv4playPackageName = new String("se.tv4.tv4playtab");
OpenApps(tv4playPackageName);
}
public void LayoutsShow(View view)
{
RelativeLayout layoutShow = findViewById(R.id.LayoutShow);
if (layoutShow.getVisibility() == View.GONE) {
layoutShow.setVisibility(View.VISIBLE);
}
else if (layoutShow.getVisibility() == View.VISIBLE) {
layoutShow.setVisibility(View.GONE);
}
}
public void MessageBox(final String uriIntent)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Couldn't find this app");
String messageText = "We cant find this app, do you want to download it?";
alertDialog.setMessage(messageText);
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent MarketIntent = new Intent(Intent.ACTION_VIEW);
MarketIntent.setData(Uri.parse(uriIntent));
startActivity(MarketIntent);
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}}
This is my XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:background="#color/backgroundColor"
tools:context="com.carlo_projekt.tvprograms.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<Button
android:id="#+id/CategoriesBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:background="#drawable/round_corners"
android:onClick="OpenGame"
android:text="Categories"
android:textAllCaps="false" />
<ImageButton
android:id="#+id/NetflixImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/CategoriesBtn"
android:onClick="NetflixFunction"
app:srcCompat="#drawable/netflix" />
<ImageButton
android:id="#+id/YoutubeImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignTop="#+id/NetflixImageBtn"
android:layout_toEndOf="#+id/CategoriesBtn"
android:onClick="YoutubeFunction"
app:srcCompat="#drawable/youtube" />
<ImageButton
android:id="#+id/ViafreeImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignStart="#+id/NetflixImageBtn"
android:layout_below="#+id/NetflixImageBtn"
android:layout_marginTop="52dp"
android:onClick="ViafreeFunction"
app:srcCompat="#drawable/viafree" />
<ImageButton
android:id="#+id/Tv4PlayImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignEnd="#+id/YoutubeImageBtn"
android:layout_alignTop="#+id/ViafreeImageBtn"
android:onClick="Tv4PlayFunction"
app:srcCompat="#drawable/tv4" />
<ImageButton
android:id="#+id/SpeakImageBtn"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="Speak"
app:srcCompat="#drawable/microphone" />
<ImageButton
android:id="#+id/imageButton19"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
app:srcCompat="#drawable/sweden" />
<ImageButton
android:id="#+id/imageButton24"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton19"
app:srcCompat="#drawable/great_britain" />
<ImageButton
android:id="#+id/imageButton22"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton24"
app:srcCompat="#drawable/germany" />
<ImageButton
android:id="#+id/imageButton23"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton22"
app:srcCompat="#drawable/france" />
<ImageButton
android:id="#+id/imageButton25"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton23"
app:srcCompat="#drawable/spanish" />
<TextView
android:id="#+id/textView"
android:layout_width="193dp"
android:layout_height="33dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="217dp"
android:layout_marginEnd="90dp"
android:text="TextView"
android:textColor="#ff00" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
`
I'm pretty new with stack overflow so I hope you understand what I'm trying to do.

Get SharedPreferences object:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Create a click listener that will update the click count for the appropriate button:
View.OnClickListener myClickListener= new View.OnClickListener() {
public void onClick(View v) {
String tag = (String) v.getTag();
sharedPref
.edit()
.putInt(tag, shardPref.getInteger(tag) + 1)
.apply();
}
};
Now for each of your buttons, you will want to set both the click listener and a tag for naming purposes:
Button btn = findViewById(R.id.NetflixImageBtn);
btn.setTag("netflix");
btn.setOnClickListener(myClickListener);
Now when you click a button, it will increment the count associated with the tag. You can use that information however you wish.

Related

I want to make a search bar for this code to search by buttons (between btn1 and btn2 and btn3) and hide the non-matched results

I am trying to add a search bar that enables me to search by buttons, search between btn1 and btn2 and btn3. I tried a lot of codes but all of them were focused on TextView and not on buttons. So hope to help me and if I missed details please let me know to describe more.
The two files (.java and .xml) are typed below. thank you.
file.java
package com.example.myapp1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
SearchView sv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("My First App");
Button btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}});
Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity3.class);
startActivity(intent);
}});
Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity4.class);
startActivity(intent);
}});
List<Button> buttonList = new ArrayList<>();
buttonList.add(view.findViewById(R.id.btn1));
buttonList.add(view.findViewById(R.id.btn2));
buttonList.add(view.findViewById(R.id.btn3));
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
for(int i = 0; i < buttonList.size(); i++) {
String buttonText = (String) buttonList.get(i).getText();
if(buttonText.toLowerCase(Locale.ROOT).equals(s.toLowerCase())) {
buttonList.get(i).setVisibility(View.VISIBLE);
} else {
buttonList.get(i).setVisibility(View.INVISIBLE);
}
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s.isEmpty()) {
for(int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.VISIBLE);
}
}
return false;
}
});
}
}
file.xml
<?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"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginHorizontal="10dp"
android:orientation="vertical"
android:weightSum="2">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Absolute Pressure" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Acoustic Flowmeter" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/btn3"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Bernoulli Number" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
What do you mean by search by buttons? Are you looking to search the text that is held within the button?
Here is a way you can go about this:
Make a list that contains all the instances of your buttons.
List(findViewById(R.id.btn1), etc)
List<Button> buttonList = new ArrayList<>();
buttonList.add(view.findViewById(R.id.button_search1));
buttonList.add(view.findViewById(R.id.button_search2));
buttonList.add(view.findViewById(R.id.button_search3));
We are going to use the listeners available to the search view to do the work.
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// You can use this for when the submit is clicked
#Override
public boolean onQueryTextSubmit(String s) {
// We loop over the button list
for(int i = 0; i < buttonList.size(); i++) {
// We get the text of the button
String buttonText = (String) buttonList.get(i).getText();
// We turn both the button text and search result to lowercase
// So that results are not case sensitive
// If they match
if(buttonText.toLowerCase(Locale.ROOT).equals(s.toLowerCase())) {
// We make button visible
buttonList.get(i).setVisibility(View.VISIBLE);
} else {
// If it doesn't, we make invisible
buttonList.get(i).setVisibility(View.INVISIBLE);
}
}
return false;
}
// You can use this when the text is changing.
#Override
public boolean onQueryTextChange(String s) {
// If text is empty, reset results
if(s.isEmpty()) {
for(int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.VISIBLE);
}
}
return false;
}
});

Android java audio player playing in background

I am creating a audio player, for Android mobile application, writed in Java langauge. I am struggling with adding to my mobile app possiblity to play audio in background. When I get back during playing audio in player to menu or minimalize app audio stops.
I searched for solution in net but I can't find how to do this in my player.
I will accept any help. Many thanks for any suggestions.
Audio player code:
package com.mc.englishlearn.audioplayer;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.mc.englishlearn.R;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PlayerActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
Button play, replay, open;
SeekBar seekBar;
TextView title, elapse;
String duration;
ScheduledExecutorService timer;
public static final int PICK_FILE =99;
boolean isRepeat = false;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
play = (Button)findViewById(R.id.play);
replay = (Button) findViewById(R.id.replay);
open = (Button) findViewById(R.id.open);
seekBar = (SeekBar) findViewById(R.id.seekBar);
title = (TextView) findViewById(R.id.title);
elapse = (TextView) findViewById(R.id.elapsed);
//Otwieranie pliku dzwiękowego
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, PICK_FILE);
}
});
//odtwarzanie pliku
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaPlayer != null){
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
play.setText("PLAY");
timer.shutdown();
}else{
mediaPlayer.start();
play.setText("PAUSE");
timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
if (!seekBar.isPressed()) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
}
},10,10, TimeUnit.MILLISECONDS);
}
}
}
});
//linia dzwięku
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mediaPlayer != null){
int millis = mediaPlayer.getCurrentPosition();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
elapse.setText(mins + ":" + secs + " / " + duration);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
mediaPlayer.seekTo(seekBar.getProgress());
}
}
});
//Pętla
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//repeat = false
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
Toast.makeText(PlayerActivity.this, "Repeat is OFF", Toast.LENGTH_SHORT).show();
}else{
isRepeat = true;
mediaPlayer.setLooping(true);
Toast.makeText(PlayerActivity.this, "Repeat is ON", Toast.LENGTH_SHORT).show();
}
//mediaPlayer.setLooping(true);
// Toast.makeText(PlayerActivity.this, "Repeat if ON", Toast.LENGTH_SHORT).show();
}
});
play.setEnabled(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE && resultCode == RESULT_OK){
if (data != null){
Uri uri = data.getData();
createMediaPlayer(uri);
}
}
}
//Stwórz odtwarzacz dzwiękowy
public void createMediaPlayer(Uri uri){
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
title.setText(getNameFromUri(uri));
play.setEnabled(true);
int millis = mediaPlayer.getDuration();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
duration = mins + ":" + secs;
elapse.setText("00:00 / " + duration);
seekBar.setMax(millis);
seekBar.setProgress(0);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
} catch (IOException e){
title.setText(e.toString());
}
}
#SuppressLint("Range")
public String getNameFromUri(Uri uri){
String fileName = "";
Cursor cursor = null;
cursor = getContentResolver().query(uri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
if (cursor != null) {
cursor.close();
}
return fileName;
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
public void releaseMediaPlayer(){
if (timer != null) {
timer.shutdown();
}
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
play.setEnabled(false);
elapse.setText("TITLE");
elapse.setText("00:00 / 00:00");
seekBar.setMax(100);
seekBar.setProgress(0);
}
}
Xml file code:
<?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">
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/guideline3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline2" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="195dp"
android:layout_marginTop="178dp"
android:layout_marginEnd="216dp"
app:layout_constraintBottom_toTopOf="#+id/guideline4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/elapsed"
android:layout_width="74dp"
android:layout_height="34dp"
android:layout_marginStart="177dp"
android:layout_marginEnd="196dp"
android:text="00-00"
app:layout_constraintBottom_toTopOf="#+id/guideline2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.25"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline4"
app:layout_constraintVertical_bias="0.625" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="271dp" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="339dp" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="93dp"
android:layout_height="108dp"
android:layout_marginStart="160dp"
android:layout_marginEnd="158dp"
android:layout_marginBottom="118dp"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#+id/replay"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline3">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/green"
android:text="|>" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Otwórz plik" />
</LinearLayout>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="213dp" />
<Button
android:id="#+id/replay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="powtórz"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline5" />
<Button
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:text="start"
app:layout_constraintBottom_toBottomOf="#+id/end"
app:layout_constraintEnd_toStartOf="#+id/guideline8"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline5" />
<Button
android:id="#+id/end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="80dp"
android:text="koniec"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="#+id/guideline8"
app:layout_constraintTop_toTopOf="#+id/guideline5" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="515dp" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="205dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Use a Service and implement all your Media Player logic there, like for example:
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (intent.getAction().equals(ACTION_PLAY)) {
mediaPlayer = ... // initialize it here
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
Then from your Main Activity start the service like so:
Context context = getApplicationContext();
Intent intent = new Intent(...); // Build the intent for the service
context.startForegroundService(intent);

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.

Problem in translation display in translation app on android studio

Hello eveyone i hope you are all doing good. I have a little problem and I couldn't find the solution. I have a translation app and after the user input his phrase by a record, the translation message doesn't appear. So I hope that someone could help me.
Here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<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">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:id="#+id/idBtnTranslateLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TransledText"
android:layout_centerInParent="true"
android:text="Translate language" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:layout_marginTop="128dp"
android:background="#color/white"
android:padding="40dp"
android:src="#drawable/ic_baseline_mic_24" />
<TextView
android:id="#+id/TransledText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edittext"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:gravity="center_horizontal"
android:text="Translated language"
android:textAlignment="center"
android:textSize="20sp"
tools:ignore="UnknownId" />
</RelativeLayout>
And my main code:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;
public class MainActivity extends AppCompatActivity {
private static final int CodeSpeechInput =100;
private TextView EditText;
private ImageButton SpeakButton;
private TextView TransledText;
FirebaseTranslator englishFrenshTranslator;
private Button translateLanguageBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseTranslatorOptions options =
new FirebaseTranslatorOptions.Builder()
.setSourceLanguage(FirebaseTranslateLanguage.EN)
.setTargetLanguage(FirebaseTranslateLanguage.FR)
.build();
englishFrenshTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options);
EditText = (TextView) findViewById(R.id.edittext);
SpeakButton = (ImageButton) findViewById(R.id.button);
TransledText = (TextView) findViewById(R.id.TransledText);
translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage);
translateLanguageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = EditText.getText().toString();
downloadModal(string);
}
private void downloadModal(String input) {
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build();
englishFrenshTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// this method is called when modal is downloaded successfully.
Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show();
// calling method to translate our entered text.
translateLanguage(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show();
}
});
}
private void translateLanguage(String input) {
englishFrenshTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String result) {
TransledText.setText(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show();
}
});
}
});
SpeakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
try {
startActivityForResult(intent, CodeSpeechInput);
} catch (ActivityNotFoundException a) {
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CodeSpeechInput : {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
EditText.setText(result.get(0));
}
break;
}
}
}
}
I also use firebase if that could help you.

How to fix activity not showing when run

I am creating a chat app in which you can create groups. to create groups I have created a new activity. it shows up in preview but won't show up when I run the app and open the activity. I tried on another phone and only the CircleImageView showed up. but it's OnClickListner won't work. there are no errors while compiling, logging or debbugging.
I have even tried breakpoints to check the error, but no output. Exept for the ad shows up. tried changing layouts but nothing shows up.
I don't know the error so I am pasting the CreateGroupActivity.java file as well as activity_create_group.xml
CreateGroupActivity.java:
package com.satyamedh.chitchatmessenger;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import de.hdodenhof.circleimageview.CircleImageView;
public class CreateGroupActivity extends AppCompatActivity
{
private CircleImageView circleImageView;
private EditText editText;
private Button buttonconf, buttoncanc;
private final static int chosenProfileImage = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
initializeFields();
buttoncanc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(CreateGroupActivity.this, MainActivity.class);
startActivity(profileIntent);
}
});
buttonconf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText.getText())){
Toast.makeText(CreateGroupActivity.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
}
});
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, chosenProfileImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == chosenProfileImage && resultCode == RESULT_OK && data != null)
{
Uri imageUri = data.getData();
CropImage
.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK) {
assert result != null;
Uri resultUri = result.getUri();
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
Intent settingsIntent = new Intent(CreateGroupActivity.this, chooseUserActivity.class);
String key = rootref.push().getKey();
settingsIntent.putExtra("groupKey", key);
settingsIntent.putExtra("groupImage", resultUri);
settingsIntent.putExtra("groupName", editText.getText().toString());
startActivity(settingsIntent);
}
}
}
private void initializeFields()
{
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.my_adView_createGroup);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
circleImageView = findViewById(R.id.create_group_image);
editText = findViewById(R.id.create_group_name);
buttonconf = findViewById(R.id.confirm_button);
buttoncanc = findViewById(R.id.cancel_button);
}
}
activity_create_group.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=".CreateGroupActivity">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="51dp"
android:layout_marginTop="87dp"
android:layout_marginEnd="259dp"
android:layout_marginBottom="551dp"
android:src="#drawable/profile_image"
android:id="#+id/create_group_image"/>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="167dp"
android:layout_marginTop="88dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="596dp"
android:background="#drawable/inputs"
android:id="#+id/create_group_name"
android:inputType="text"
android:hint="Group name here"/>
<Button
android:id="#+id/confirm_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="168dp"
android:layout_marginTop="141dp"
android:layout_marginEnd="156dp"
android:layout_marginBottom="542dp"
android:text="Confirm"
android:background="#drawable/buttons"/>
<Button
android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="263dp"
android:layout_marginTop="140dp"
android:layout_marginEnd="60dp"
android:layout_marginBottom="546dp"
android:text="Cancel"
android:background="#drawable/buttons"/>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/my_adView_createGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
android phone(redmi 2) screenshot:
https://drive.google.com/file/d/18MMzLvcdIi8iLog1nR_NrJPcJf-NZG51/view?usp=sharing
pc android studio screenshot:
https://drive.google.com/file/d/1E3Suy967AS3aQS9TEkUlAh5kPjWr86u-/view?usp=sharing
I am newbie to stackoverflow so I can't attach images. sorry.
no errors also.
it's normal because you used so much alignment value and attribute which made your layout not responsive , please use the xml below and don't forget to add the image:src and background you wanted
<?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=".CreateGroupActivity">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="20dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="#+id/create_group_image"/>
<EditText
android:layout_toRightOf="#id/create_group_image"
android:layout_width="250dp"
android:layout_marginTop="20dp"
android:layout_height="wrap_content"
android:id="#+id/create_group_name"
android:inputType="text"
android:hint="Group name here"/>
<Button
android:layout_below="#id/create_group_name"
android:layout_toRightOf="#id/create_group_image"
android:id="#+id/confirm_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Confirm"/>
<Button
android:layout_below="#id/create_group_name"
android:layout_toRightOf="#id/confirm_button"
android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"/>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/my_adView_createGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</RelativeLayout>

Categories