image are not showing in image view after selecting from gallery intent - java

I'm trying to select images from the gallery and upload them to firebase storage but after selecting the image it doesn't show in the image view and the app get crash
Note I'm using a fragment and not an activity
Here is the Error Message
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
Here is my MainActivity.xml
<?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"
android:background="#color/black">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar" />
<include
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/fragment_container"
android:layout_below="#+id/tool_bar"
android:layout_above="#id/bottom_navigation_view" />
<include
android:id="#+id/bottom_navigation_view"
layout="#layout/bottom_navigation_view" />
</RelativeLayout>
Here is my fragment_upload.XML file
<?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:background="#color/black">
<ImageView
android:id="#+id/upload_image_view"
android:layout_width="match_parent"
android:layout_height="600dp"
app:layout_constraintBottom_toTopOf="#+id/done_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/done_button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:backgroundTint="#color/grey"
android:text="#string/done"
android:textColor="#color/white"
app:layout_constraintBottom_toTopOf="#+id/upload_image_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/upload_image_button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:backgroundTint="#color/grey"
android:text="#string/upload"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home_Fragment()).commit();
Window window = this.getWindow();
window.setStatusBarColor(this.getResources().getColor(R.color.black));
}
private final BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
item -> {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new Home_Fragment();
break;
case R.id.nav_following:
selectedFragment = new Following_Fragment();
break;
case R.id.nav_upload:
selectedFragment = new Upload_Fragment();
break;
case R.id.nav_notification:
selectedFragment = new Notification_Fragment();
break;
case R.id.nav_profile:
selectedFragment = new Profile_Fragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
};
}
Here is Upload_Fragment.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myappnotfinal.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
public class Upload_Fragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 1;
private Button choseImageButton;
private Button uploadImageButton;
private ImageView uploadImageView;
private Uri imageUri;
private FirebaseStorage storage;
private StorageReference storageReference;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_upload, container, false);
Button chooseImageButton = view.findViewById(R.id.upload_image_button);
Button uploadImageButton = view.findViewById(R.id.done_button);
uploadeImageView = view.findViewById(R.id.upload_image_view);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
chooseImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadToFirebase();
}
});
return view;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
imageUri = data.getData();
uploadImageView.setImageURI(imageUri);
}
}
private void uploadToFirebase() {
if (imageUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/" + UUID.randomUUID().toString());
ref.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}

From what I can understand is that your image_view is null rather than your URI since you have already put a check for that, and after reading your code inside the onCreateView() method, there is this line
uploadeImageView = view.findViewById(R.id.upload_image_view);
This might just be a typo, there is an extra 'e' at the end while your top variable is
private ImageView uploadImageView;
and even later when you are setting it you are using following
uploadImageView.setImageURI(imageUri);

Related

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.

Search filter on list view returns wrong result on clicking

Problem
I am creating music player using android studio.
Everything was fine until I added search filter to search songs.
Search filter returns the song right but when I click on searched result wrong music file is opened however the music name shown on player activity is right but the song played is first song of list every time .
Example
There are 4 song items named: A,B,C,D
When searched C ,filtered result C is shown. But when Clicked on it Song name C is shown but Song A is played.
This is really frustrating.
Main Activity.java
package com.example.musicplayer2;
import android.Manifest;
import android.content.Intent;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static boolean shuffleBol = false;
static boolean loopBol = false;
ListView listView;
String[] items;
ArrayAdapter<String> myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySongs();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
if (files != null){
for (File singlefile : files)
{
if (singlefile.isDirectory() && !singlefile.isHidden())
{
arrayList.addAll(findSong(singlefile));
}
else
{
if (singlefile.getName().endsWith(".mp3") && !singlefile.getName().startsWith("."))
{
arrayList.add(singlefile);
}
}
}
}
return arrayList;
}
void displaySongs()
{
ArrayList<File> mysongs;
mysongs = findSong(Environment.getExternalStorageDirectory());
items = new String[mysongs.size()];
for (int i=0; i < mysongs.size(); i++)
{
items[i] = mysongs.get(i).getName().replace(".mp3","");
}
// ArrayAdapter<String> myAdapter;
myAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String songName = (String) listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)
.putExtra("songs",mysongs)
.putExtra("songname",songName)
.putExtra("position",position));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
main activity.xml
<?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">
<ListView
android:id="#+id/listViewSong"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="8dp"
>
</ListView>
</RelativeLayout>
PlayerActivity.java
package com.example.musicplayer2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import static com.example.musicplayer2.MainActivity.loopBol;
import static com.example.musicplayer2.MainActivity.shuffleBol;
public class PlayerActivity extends AppCompatActivity {
ImageView btnplay,btnnext,btnprev,btnshuffle,btnloop;
TextView txtsname,txtstart,txtstop;
SeekBar seekmusic;
String sname;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList<File> mySongs;
Thread updateseekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Player");
btnprev = findViewById(R.id.btnprev);
btnnext = findViewById(R.id.btnnext);
btnplay = findViewById(R.id.playbtn);
btnshuffle = findViewById(R.id.btnshuffle);
btnloop = findViewById(R.id.btnloop);
txtsname = findViewById(R.id.txtsn);
txtstart = findViewById(R.id.txtstart);
txtstop = findViewById(R.id.txtstop);
seekmusic = findViewById(R.id.seekbar);
// if a media player is already running then.
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList)bundle.getParcelableArrayList("songs");
String songName = i.getStringExtra("songname");
position = bundle.getInt("position",0);
txtsname.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString());
sname = mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
mediaPlayer.start();
updateseekbar = new Thread()
{
#Override
public void run() {
int totalDuration = mediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition<totalDuration)
{
try {
sleep(500);
currentPosition = mediaPlayer.getCurrentPosition();
seekmusic.setProgress(currentPosition);
}
catch (InterruptedException | IllegalStateException e)
{
e.printStackTrace();
}
}
}
};
seekmusic.setMax(mediaPlayer.getDuration());
updateseekbar.start();
seekmusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime = createTime(mediaPlayer.getCurrentPosition());
txtstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
// click Listener ON PLAY button
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying())
{
btnplay.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
else
{
btnplay.setBackgroundResource(R.drawable.pause);
mediaPlayer.start();
}
}
});
// click Listener ON next button
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol)
{
position=((position+1)%mySongs.size());
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click Listener ON previous button
btnprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol){
position=((position-1)<0)?(mySongs.size()-1):(position-1);
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click listener for shuffle btn
btnshuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (shuffleBol){
shuffleBol=false;
btnshuffle.setImageResource(R.drawable.shuffle_off);
}
else {
shuffleBol=true;
btnshuffle.setImageResource(R.drawable.shuffle_on);
}
}
});
// click listener for loop btn
btnloop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (loopBol){
loopBol=false;
btnloop.setImageResource(R.drawable.loop_off);
}
else {
loopBol=true;
btnloop.setImageResource(R.drawable.loop_on);
}
}
});
// next Listener ON song completion
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnnext.performClick();
}
});
}
public String createTime(int duration)
{
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10)
{
time+="0";
}
time+=sec;
return time;
}
private int getRandom(int i) {
Random random= new Random();
return random.nextInt(i+1);
}
}
PlayerActivity.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="wrap_content"
android:background="#drawable/bg"
android:orientation="vertical"
android:weightSum="10"
tools:context=".PlayerActivity"
android:baselineAligned="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="7"
android:gravity="center"
android:orientation="vertical"
tools:ignore="Suspicious0dp,UselessParent">
<TextView
android:id="#+id/txtsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="#string/song_name"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="italic">
</TextView>
<ImageView
android:id="#+id/imageview"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginBottom="8dp"
android:src="#drawable/logo">
</ImageView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<SeekBar
android:id="#+id/seekbar"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:layout_marginBottom="40dp">
</SeekBar>
<TextView
android:id="#+id/txtstart"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="-17dp"
android:layout_toLeftOf="#+id/seekbar"
android:text="0:00"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
<TextView
android:id="#+id/txtstop"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="false"
android:layout_centerInParent="true"
android:layout_marginLeft="-14dp"
android:layout_marginRight="20dp"
android:layout_toRightOf="#+id/seekbar"
android:text="#string/_4_10"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="98dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/playbtn"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:background="#drawable/pause" />
<ImageView
android:id="#+id/btnnext"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/playbtn"
android:background="#drawable/next" />
<ImageView
android:id="#+id/btnprev"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/playbtn"
android:background="#drawable/previous" />
<ImageView
android:id="#+id/btnshuffle"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/btnprev"
android:layout_marginTop="85dp"
android:layout_marginRight="35dp"
android:background="#drawable/shuffle_off"/>
<ImageView
android:id="#+id/btnloop"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/btnnext"
android:layout_marginTop="85dp"
android:layout_marginLeft="35dp"
android:background="#drawable/loop_off"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
In above image, you see that you are sending the position of filtered array and sending the songs list (mysongs) which is not filtered. That's why it's happening.
So you need to do is that either send the filtered array. Or add some logic to get the correct position from songs list. that's it.
if you can not figure out then let me know I will update appropriate logic.

My fragment_profile.xml doesnt show. Whats wrong with my program?

I created a new fragment which is ProfileFragment.java and also created fragment_profile.xml.
The program does not give any error but my layout doesnt show. What is wrong?
My ProfileFragment.java :
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class ProfileFragment extends Fragment {
//firebase auth
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//layout views
ImageView avatar;
TextView nameTxt, emailTxt, phoneTxt;
public ProfileFragment() {
//boş public constructor gerekli
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
//init firebase
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
//init layout views
avatar = view.findViewById(R.id.avatar);
nameTxt = view.findViewById(R.id.nameTxt);
emailTxt = view.findViewById(R.id.emailTxt);
phoneTxt = view.findViewById(R.id.phoneTxt);
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak çekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak çekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak için
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
phoneTxt.setText(phone);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return view;
}
}
and my fragment_profile.xml :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:background="#F1EDED"
tools:context=".ProfileFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#2ECC71">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="horizontal"
android:layout_marginTop="100dp">
<ImageView
android:id="#+id/avatar"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/add_photo_foreground"
android:layout_marginStart="20dp"
android:background="#6AE493"
android:padding="5dp">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nameTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textSize="25dp"
android:textColor="#FFFFFF"></TextView>
<TextView
android:id="#+id/emailTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#FFFFFF"></TextView>
<TextView
android:id="#+id/phoneTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#FFFFFF"></TextView>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
I want to create a user profile page using firebase realtime database. The user details come from using email for current signed user. But my profile layout file does not work. How can I fix this problem? Whats wrong in my code?
My DasboardAvtivity.java -> For fragment transaction.
package com.gamze.pawsbook;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class DashboardActivity extends AppCompatActivity {
//FirebaseAuth
FirebaseAuth firebaseAuth;
//Actionbar
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//ActionBar ve başlığı
actionBar = getSupportActionBar();
actionBar.setTitle("Profile");
//profileTxt = findViewById(R.id.profileTxt);
firebaseAuth = FirebaseAuth.getInstance();
//Bottom navigation
BottomNavigationView navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(selectedListener);
//Home Fragment'ı boş default fragment olarak ayarlanması
actionBar.setTitle("Home"); //ActionBar başlığını değiştirme
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content, homeFragment, "");
ft.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener selectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//itemlere tıklanma özelliği ekleme
switch (item.getItemId()){
case R.id.action_home:
//home fragment değişimi
actionBar.setTitle("Home"); //ActionBar başlığını değiştirme
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ftHome = getSupportFragmentManager().beginTransaction();
ftHome.replace(R.id.content, homeFragment, "");
ftHome.commit();
return true;
case R.id.action_map:
//map fragment değişimi
actionBar.setTitle("Map"); //ActionBar başlığını değiştirme
MapFragment mapFragment = new MapFragment();
FragmentTransaction ftMap = getSupportFragmentManager().beginTransaction();
ftMap.replace(R.id.content, mapFragment, "");
ftMap.commit();
return true;
case R.id.action_users:
//users fragment değişimi
actionBar.setTitle("Users"); //ActionBar başlığını değiştirme
UsersFragment usersFragment = new UsersFragment();
FragmentTransaction ftUsers = getSupportFragmentManager().beginTransaction();
ftUsers.replace(R.id.content, usersFragment, "");
ftUsers.commit();
return true;
case R.id.action_profile:
//profile fragment değişimi
actionBar.setTitle("Profile"); //ActionBar başlığını değiştirme
ProfileFragment profileFragment = new ProfileFragment();
FragmentTransaction ftProfile = getSupportFragmentManager().beginTransaction();
ftProfile.replace(R.id.content, profileFragment, "");
ftProfile.commit();
return true;
}
return false;
}
};
private void checkUserStatus() {
//mevcut kullanıcıyı al
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//kullanıcı giriş yapmışsa burada kal
//giriş yapan kullanıcının email i
//profileTxt.setText(user.getEmail());
}
else{
//kullanıcı giriş yapmamışsa main activity'e git
Intent intent = new Intent(DashboardActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onStart() {
//uygulamanın başlangıcını konrtol et
checkUserStatus();
super.onStart();
}
//options menu dahil etme
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menuyu dahil etme
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//menu itemlerine onClick özelliği aktifleştirme
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
//itemlerin id'lerini al
int id = item.getItemId();
if (id == R.id.action_logout){
//hesaptan çıkış yap
firebaseAuth.signOut();
checkUserStatus();
}
return super.onOptionsItemSelected(item);
}
}
activity_dashboard.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=".DashboardActivity">
//FrameLayout fragmentlerin üstüste gelebilmesi için daha kullanışlıdır
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp">
</FrameLayout>
//BottomNavigationBar
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottombar_menu">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
This is what is showing from fragment_profile.xml.
Your question doesn't give information whether you are getting an empty view like above or you are not getting any view. I will try to answer on two ansumption.
Empty View
No View at all
Empty View
If you are getting empty view then you must put some Logs statement in your database responce, check if that database is returning some value.
public class ProfileFragment extends Fragment {
//Log Statment
private static final String TAG = "ProfileFragment";
......
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak için
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
phoneTxt.setText(phone);
Log.d(TAG, "onDataChange: \nName: "+name+" email: "+ email);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
}
Log.d(TAG, "onDataChange: Data is empty");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: "+error);
}
}
}
.........
You can use breakpoints as well to further investigation.
No View at all
If view is not changing on ProileFragment then you must check how you are starting ProfileFragment.
getSupportFragmentManager().beginTransaction().replace(R.id.frgment_container, new ProfileFragment()).commit();
If you are using Navigation Component then make sure you are navigating to correct destination.
I will also suggest you to strcture the code in following format under Profile Fragment -
public class ProfileFragment extends Fragment {
//firebase auth
............
//layout views
..............
public ProfileFragment() {
//boş public constructor gerekli
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//init firebase
.................
//init layout views
.......................
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak çekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak çekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
.................
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
...............
}
});
}
}
Edit (activity_dashboard.xml)
Try following layout file for activity_dashboard.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DashboardActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottombar_menu"/>
</RelativeLayout>
I am using ?attr/actionBarSize, which is the standard action bar size for android.
Happy Coding !

Navigation drawer is under other widgets

I'm trying to add fragment with Navigation drawer to the main activity, where are two buttons. However, when Navigation drawer is opened, buttons are above it. Moreover, Navigation drawer is not clickable, but buttons are.
Screenshot of opened Navigation drawer
Here is my code.
XML File implementing Navigation Drawer - MainActivity.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"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
tools:context=".MainActivity">
<Button
android:id="#+id/mainTestsButton"
android:layout_width="112dp"
android:layout_height="105dp"
android:layout_alignParentEnd="true"
android:layout_marginTop="334dp"
android:layout_marginEnd="167dp"
android:onClick="goTest"
android:text="Button2"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/mainLearningButton"
android:layout_width="114dp"
android:layout_height="102dp"
android:layout_alignParentEnd="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="108dp"
android:layout_marginEnd="175dp"
android:layout_marginBottom="118dp"
android:onClick="goLearn"
android:text="Button1"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="#+id/fragmentList"
android:name="com.chemistryApps.NavigationDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_navigation_drawer" />
</RelativeLayout>
Navigation Drawer XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
tools:context=".NavigationDrawer">
<android.support.constraint.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</android.support.constraint.ConstraintLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_layout" />
</android.support.v4.widget.DrawerLayout>
Navigation Drawer Fragment Java class
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
public class NavigationDrawer extends Fragment {
private DrawerLayout mDrawerLayout;
NavigationView navigationView;
private OnFragmentInteractionListener mListener;
public NavigationDrawer() {
// Required empty public constructor
}
public static NavigationDrawer newInstance(String param1, String param2) {
NavigationDrawer fragment = new NavigationDrawer();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("buttonClicked", "onCreateView");
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerLayout = view.findViewById(R.id.drawer_layout);
navigationView = view.findViewById(R.id.nav_view);
mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View view, float v) {
Log.i("buttonClicked", "onDrawerOpened");
}
#Override
public void onDrawerOpened(#NonNull View view) {
Log.i("buttonClicked", "onDrawerOpened");
navigationView.bringToFront();
mDrawerLayout.requestLayout();
}
#Override
public void onDrawerClosed(#NonNull View view) {
Log.i("buttonClicked", "onDrawerOpened");
}
#Override
public void onDrawerStateChanged(int i) {
Log.i("buttonClicked", "onDrawerOpened");
}
});
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// set item as selected to persist highlight
Log.i("buttonClicked", "onNavigationItemSelected()" + menuItem.toString());
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
switch (menuItem.getItemId()){
case R.id.learning:
Intent intent = new Intent(getActivity(), LearningActivity.class);
startActivity(intent);
return true;
case R.id.test:
Intent intent2 = new Intent(getActivity(), TestActivity.class);
startActivity(intent2);
return true;
case R.id.settings:
return true;
case R.id.help:
return true;
default:
return false;
}
}
});
return inflater.inflate(R.layout.fragment_navigation_drawer, container,
false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Thank you in advance for an answer.
EDIT:
I am attaching the main activity code
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity implements
NavigationDrawer.OnFragmentInteractionListener {
public void goLearn (View view){
Log.i("buttonClicked", "goLearn");
final Intent intent = new Intent(this, LearningActivity.class);
startActivity(intent);
}
public void goTest (View view){
Log.i("buttonClicked", "goTest");
final Intent intent = new Intent(this, TestActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onFragmentInteraction(Uri uri) {
return;
}
}

How to display selected installed applications in grid view

**I have this code to show the installed applications in Android. I also want to display the selected applications by the user in Grid view. How can I do that in this code?
And is there always a need for adapter for grid-view also?**
This is my first activity:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Startup extends Activity {
Button bIns, bSel;
ArrayList<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bIns = (Button) findViewById(R.id.bList);
bSel = (Button) findViewById(R.id.bGrid);
}
public void viewList(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public void viewGrid(View view) {
myList = (ArrayList<String>) getIntent().getSerializableExtra("mySelectedList");
Intent intent = new Intent(getApplicationContext(), Last.class);
intent.putExtra("mySelectedList",myList);
startActivity(intent);
}
}
This is my second activity:
package com.abhi.test;
import java.util.ArrayList;
import com.abhi.test.ApplicationAdapter;
import java.util.List;
import com.example.applist.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
Button button;
Bundle bundle;
CheckBox checkbox;
ArrayList<ApplicationInfo> selectedapplication = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
button = (Button) findViewById(R.id.button);
checkbox = (CheckBox) findViewById(R.id.cb_app);
new LoadApplications().execute();
//Intent intent = new Intent(this,Last.class);
}
public void selectedApps(View view) {
//new ApplicationAdapter().selApps();
selectedapplication = ApplicationAdapter.finalList;
Intent intent = new Intent(MainActivity.this, Startup.class);
intent.putExtra("mySelectedList",selectedapplication);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (packageManager.getLaunchIntentForPackage(info.packageName) != null)
{
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.row, applist);
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
}
}
Array adapter for second activity:
package com.abhi.test;
import java.util.ArrayList;
import java.util.List;
import com.example.applist.R;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
int position1;
CheckBox checkBox;
private PackageManager packageManager;
public ArrayList<Boolean> checkList = new ArrayList<Boolean>();
private OnCheckedChangeListener listener;
public static ArrayList<ApplicationInfo> finalList = null;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
for (int i = 0; i < appsList.size(); i++)
{
checkList.add(false);
}
}
#Override
public int getCount() {
if (appsList != null) {
return appsList.size();
} else {
return 0;
}
}
#Override
public ApplicationInfo getItem(int position) {
if (appsList != null) {
return appsList.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override //ibuilt function getView()--responsinle for making views
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if ( view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Understand
view = layoutInflater.inflate(R.layout.row, null);
}
ApplicationInfo data = appsList.get(position);
if (data != null) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
position1=position;
checkBox = (CheckBox) view.findViewById(R.id.cb_app); //understand
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
checkBox.setChecked(checkList.get(position)); // set the status as we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
/* if(checkBox.isChecked())
{
finalList.add(data);
Toast.makeText(getContext(), "App Added", Toast.LENGTH_LONG).show();
}*/
}
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
}
};
}
This is the last activity in which I want to show the selected applications by the user:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class Last extends Activity{
GridView gridview;
ArrayList<ApplicationInfo> appList;
String[] appName = new String[100];
String[] appPack = new String[100];
String[] appComp = new String[100];
ArrayList<String> appInfo = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.last);
gridview = (GridView) findViewById(R.id.gridview);
appList = (ArrayList<ApplicationInfo>) getIntent().getSerializableExtra("mylist");
for(int i=0;i<appList.size();i++)
{
appName[i] = appList.get(i).name;
appPack[i] = appList.get(i).packageName;
appComp[i] = appName[i]+appPack[i];
appInfo.add(appComp[i]);
}
/* ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<ApplicationInfo>(this,
android.R.layout.simple_list_item_1, appInfo);
gridview.setAdapter(adapter);*/
}
}
XML for the first activity:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<Button
android:id="#+id/bList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewList"
android:text="#string/bInstalledApps" />
<Button
android:id="#+id/bGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewGrid"
android:text="#string/bSelectedApps" />
</LinearLayout>
XML for the second activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="selectedApps"
android:text="Done"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/button" />
</RelativeLayout>
row.xml for adapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/appdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cb_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:scaleX="1.50"
android:scaleY="1.50" />
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp" >
<TextView
android:id="#+id/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_paackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
XML for the last activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</LinearLayout>
A GridView is a collection of views in a grid. The Android system doesn't magically know what views you want to be in it. This is where the adapter comes in. By setting an adapter for a GridView, you tell the GridView several things about how you want it to display views including how many views there are and what each view looks like. So yes, all GridViews need adapters.

Categories