Phone directories in Android and problems with getting anything from them - java

Hi Stackoverflow community!
At first I want to say that I am a rookie in programming. Recently I tried to get photos from my phone directories by my app. It seems pretty hard to do, because I have only succeded in displaying my Camera directory, but not for example Download or Screenshots. It is really strange that Android Studio cannot resolve DOWNLOAD word in the line directories.add(filePaths.DOWNLOAD);
What is wrong with my code??? Or with me and my lack of experience...
My code:
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = (ImageView) view.findViewById(R.id.galleryImageView);
gridView = (GridView) view.findViewById(R.id.gridView);
directorySpinner = (Spinner) view.findViewById(R.id.spinnerDirectory);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = (ImageView) view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
getActivity().finish();
}
});
TextView nextScreen = (TextView) view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if (isRootTask()) {
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
} else {
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
init();
return view;
}
private boolean isRootTask() {
if (((ShareActivity) getActivity()).getTask() == 0) {
return true;
} else {
return false;
}
}
private void init() {
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
directories.add(filePaths.DOWNLOAD);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory) {
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try {
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " + e.getMessage());
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append) {
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
FilePaths sorry for not formatting
public class FilePaths {
//"storage/emulated/0"
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String PICTURES = ROOT_DIR + "/Pictures";
public String CAMERA = ROOT_DIR + "/DCIM/camera";
public String FIREBASE_IMAGE_STORAGE = "photos/users/";
}

Well, the reason is simple. It's because you haven't defined the variable DOWNLOAD in the FilePaths.class. You also shouldn't point to the path like this, instead of that, use one or more of this variables:
Environment.getDataDirectory()
Environment.getDownloadCacheDirectory()
Environment.getExternalStorageDirectory()
Environment.getRootDirectory()
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES)
So your FilePaths should looks like this:
public class FilePaths {
//"storage/emulated/0"
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String DOWNLOADS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
public String PICTURES = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
public String CAMERA = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
public String ALARMS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);
public String DOCUMENTS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
public String MOVIES = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
public String MUSIC = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
public String NOTIFICATIONS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS);
public String PODCASTS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);
public String RINGTONES = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES);
public String FIREBASE_IMAGE_STORAGE = "photos/users/";
}

It is in general not a good idea to use class names for your own class that are similar to java classes! Calling your class FilePaths will lead to confusion.
Change the name of your class to MyFilePaths (or something else!).
Then you can make the java file "MyFilePaths.java". Make the class public and make your variables static final:
public class MyFilePaths {
//"storage/emulated/0"
public static final String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public static final String PICTURES = ROOT_DIR + "/Pictures";
public static final String CAMERA = ROOT_DIR + "/DCIM/camera";
public static final String FIREBASE_IMAGE_STORAGE = "photos/users/";
}
Now you can do this:
directories.add(MyFilePaths.CAMERA);
Edit
In your code you call:
FilePaths filePaths = new FilePaths();
But your FilePaths class does not have a public constructor.

Related

How to load pdf files to recycler view in fragment?

ello guys good day I'm trying to make an app using android java but I'm stuck any idea would be appreciated
I'm trying to access all pdf files in android device using the media store and cursor but it's not working the aim is to display all pdf files in a recycler view on a fragment the issue here is that it never displays meaning maybe the data wasn't passed because when the arraylist is populated manually it displays otherwise non I've checked the log but I can't seem to find anything.
This my fragment code
public class AllFragment extends Fragment {
View view;
private static final String TAG = "MyActivity";
ArrayList<String> pdfList;
private final int STORAGE_PERMISSION_CODE = 1;
private Activity mActivity;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mActivity = (Activity) context;
}
public void checkPermission(){
if ((ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
{
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(mActivity)
.setTitle("Permission needed")
.setMessage("Allow "+getResources().getString(R.string.app_name)+" to access your storage?")
.setPositiveButton("ok", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
)
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
Toast.makeText(mActivity, "Please allow this permission!", Toast.LENGTH_SHORT).show();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
}
//checkPermission();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.AllFragment, container, false);
//pdfList = getPdfList();
//buildData();
//LinearLayoutManager
//pdfList = new String[] {"one", "two", "three", "fou4", "five", "six"};
getPdfList();
initRecyclerView(view);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermission();
}
//RecyclerView
public void initRecyclerView(View view){
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.allPdfsRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
AllPdfAdapter adapter = new AllPdfAdapter(pdfList);
recyclerView.setAdapter(adapter);
}
public ArrayList<String> getPdfList() {
pdfList = new ArrayList<>();
Uri collection;
final String[] projection = new String[]{
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
}else{
collection = MediaStore.Files.getContentUri("external");
}
try (Cursor cursor = getActivity().getContentResolver().query(collection, projection, selection, selectionArgs, sortOrder)) {
assert cursor != null;
if (cursor.moveToFirst()) {
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
//ArrayList pdfList = new ArrayList<>();
do {
pdfList.add((cursor.getString(columnData)));
System.out.println(cursor.getString(columnData));
Log.d(TAG, "getPdf: " + cursor.getString(columnData));
//you can get your pdf files
} while (cursor.moveToNext());
}
}
return pdfList;
}
}
This my adapter code
public class AllPdfAdapter extends RecyclerView.Adapter<AllPdfAdapter.My_ViewHolder>
{
private ArrayList<String> data;
public AllPdfAdapter(ArrayList<String>data){
this.data = data;
}
#Override
public AllPdfAdapter.My_ViewHolder onCreateViewHolder(ViewGroup p1, int p2)
{
LayoutInflater li = LayoutInflater.from(p1.getContext());
View v = li.inflate(R.layout.allList,p1,false);
// TODO: Implement this method
return new My_ViewHolder(v);
}
#Override
public void onBindViewHolder(AllPdfAdapter.My_ViewHolder holder, int position)
{
// TODO: Implement this method
String title = data.get(position);
holder.ttt.setText(title);
}
#Override
public int getItemCount()
{
// TODO: Implement this method
return data.size();
}
public class My_ViewHolder extends RecyclerView.ViewHolder{
ImageView iii;
TextView ttt;
public My_ViewHolder (View v){
super(v);
iii = (ImageView) v.findViewById(R.id.img);
ttt = (TextView) v.findViewById(R.id.title);
}
}
}
Your answers will be appreciated.

Java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 Android

I have been getting this error for DAYS maybe a week and I still can't fix it and no one can help me .
I am using a Instagram clone app to create an app like Instagram . I have these errors I have been getting and I can't fix it and no one on here seems to be able to either .
07-09 11:48:43.307 19532-19532/tabian.com.hash E/AndroidRuntime: FATAL EXCEPTION: main
Process: tabian.com.hash, PID: 19532
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at tabian.com.hash.Share.GalleryFragment.setupGridView(GalleryFragment.java:159)
at tabian.com.hash.Share.GalleryFragment.access$300(GalleryFragment.java:38)
at tabian.com.hash.Share.GalleryFragment$3.onItemSelected(GalleryFragment.java:134)
The file has no errors or even warnings or typos . I only get this when I try to access my camera in my phone . I tried changing code, moving code and adding code and nothing worked . I tried reducing the targetSdkVersion and the minSdkVersion and I still get the error .
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
Objects.requireNonNull(getActivity()).finish();
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if(isRootTask()){
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
}else{
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
Objects.requireNonNull(getActivity()).finish();
}
}
});
init();
return view;
}
private boolean isRootTask(){
return ((ShareActivity) Objects.requireNonNull(getActivity())).getTask() == 0;
}
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders inside "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
}catch (ArrayIndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append){
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
Can someone please help me . This is very important to me .
EDITTT !!
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs =
FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
if (imgURLs.isEmpty()) {
// Array list is empty, handle accordingly
} else {
//set the first image to be displayed when the activity fragment view is inflated
try {
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " + e.getMessage());
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
}
The errors I see
This line:
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
is returning an empty ArrayList, i.e. no file paths were returned. Because you are not checking for imgURLs.isEmpty(), you are attempting to get() index 0 of that imgURLs, which does not exist. Because of this, an IndexOutOfBoundsException is thrown.
You can avoid this crash by checking if imgURLs contains at least one item before continuing. For example:
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
...
if (imgURLs.isEmpty()) {
// Array list is empty, handle accordingly
} else {
//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
} catch (IndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}
}
...
}

get and set global variables from CustomListViewAdapter

Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}

My Viewpager can not display my second image in database

In my project I use View pager to show my pics from database.In my database I have two page that every page has one pics.
I can get the first pic in my first page but view pager doesn't show my second pic from next page. I know the reason and the reason is that my state don't go to the second page.
I don't know where I jump to second page.
here is my code:
public class main_matn2 extends Activity {
private database db;
private String sea;
private String name;
private int Page1;
public int Page2 = 1;
private SharedPreferences sp;
TextView Lesson_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main_matn2);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.matn_title);
Lesson_Name = (TextView) findViewById(R.id.lesson_name);
db = new database(this);
Bundle ex = getIntent().getExtras();
sea = ex.getString("sea");
name = ex.getString("name");
Page1 = Integer.parseInt(ex.getString("page"));
Lesson_Name.setText(name);
Typeface type = Typeface.createFromAsset(getAssets(), "font/font_bold.ttf");
Lesson_Name.setTypeface(type);
load(sea, name, Page2);
}
private void load(String sea, String Name, int page3) {
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(page3, Name);
viewPager.setAdapter(adapter);
db.open();
}
#Override
public void onBackPressed() {
sp = getApplicationContext().getSharedPreferences("user", 0);
Editor ed = sp.edit();
ed.putString("name", name);
ed.putString("sea", sea);
ed.putInt("page", Page1);
ed.commit();
finish();
}
#Override
protected void onPause() {
sp = getApplicationContext().getSharedPreferences("user", 0);
Editor ed = sp.edit();
ed.putString("name", name);
ed.putString("sea", sea);
ed.putInt("page", Page1);
ed.commit();
super.onPause();
}
public class ImagePagerAdapter extends PagerAdapter {
int img_count;
String Name;
public ImagePagerAdapter(int count, String Name) {
img_count = count;
this.Name = Name;
}
#Override
public int getCount() {
return img_count;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = main_matn2.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
String p = db.getpic("content", sea, Name, img_count + "");
if (p != null) {
int ImageResource = getResources().getIdentifier(p, "drawable", getPackageName());
imageView.setImageResource(ImageResource);
}
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
my load method before I add the view pager was like this:
private void load(String sea, String Name, int page3) {
db.open();
String p = db.getpic("content", sea, Name, page3 + "");
if (p != null) {
int ImageResource = getResources().getIdentifier(p, "drawable", getPackageName());
img.setImageResource(ImageResource);
} else {
img.setVisibility(View.GONE);
}
db.close();
}
and I had one button to change my pages .(I could go to the second page by this button.
here is my button (But now I need view pager and I dont need this button anymore)
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (Page1 == Page2) {
Toast.makeText(getApplicationContext(), "last page", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(main_matn1.this, CustomTabActivity.class);
startActivity(intent);
} else {
Page2++;
load(sea, name, Page2);
}
}
});
any help?
I am new with android and now I'm very confused.
Can you change onCreate method this line
load(sea, name, Page2);
with this
load(sea, name, 2);
and in adapter instantiateItem() method change your code
String p = db.getpic("content", sea, Name, img_count + "");
with this code
String p = db.getpic("content", sea, Name, position + "");

OnItemClicklistener on list adapter that populate its items from database

I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter

Categories