My Viewpager can not display my second image in database - java

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 + "");

Related

How to pass data from RecyclerView to activity

I'm really struggling with this, what I need is when the user clicks on the recipe image, which comes from the ArrayList listRecipe put into the RecyclerView, the value from myTextView1 should be passed to the CreateMealPlan activity so it can be saved along with the date to an SQLite database.
Hope I've made this clear, thanks in advance for any help.
Activity
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
SQLiteDatabase db;
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
adapterRecipe = new RecipeListAdapter(this, listRecipe);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
recipeList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Recipe name is", recipe_name);
}
});
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d_name = new Date(day, month, year);
String dayOfTheWeek = sdf.format(d_name);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void ListRecipes() {
listRecipe.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
}
RecyclerAdapter
public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {
private List<Category> listRecipe;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public RecipeListAdapter(Context context, List<Category> data) {
this.mInflater = LayoutInflater.from(context);
this.listRecipe = data;
}
// inflates the row layout from xml when needed
#Override
public com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.cardview_recipe, parent, false);
return new com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
holder.myTextView1.setText(listRecipe.get(position).getRecipe_name());
holder.myTextView2.setText(listRecipe.get(position).getCategory_name());
String image2 = listRecipe.get(position).getImage2();
Bitmap myBitmap = BitmapFactory.decodeFile(image2);
if (myBitmap != null)
holder.imgImage.setImageBitmap(myBitmap);
else
holder.imgImage.setImageResource(listRecipe.get(position).getImage());
}
// total number of rows
#Override
public int getItemCount() {
return listRecipe.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView1;
TextView myTextView2;
ImageView imgImage;
ViewHolder(View itemView) {
super(itemView);
myTextView1 = itemView.findViewById(R.id.txtName);
myTextView2 = itemView.findViewById(R.id.txtCategory);
imgImage = itemView.findViewById(R.id.imgImage);
myTextView1.setOnClickListener(this);
myTextView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String recipe_name = myTextView1.getText().toString();
}
});
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecipeListAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
You should:
Define an interface that will be used to handle click events (similar to your ItemClickListener);
Implement this interface as an anonymous class or by extending your Activity;
Pass that instance of the new interface to your adapter;
Set click listener, handle click events and pass data back into your Activity.
Step 1: define an interface
Sample interface:
interface OnRecipeClickListener {
void onRecipeClicked(int position, String someString);
}
Step 2: implement the interface
This part is located inside of your Activity class:
new OnRecipeClickListener() {
public void onRecipeClicked(int position, String someString) {
Log.d(CreateMealPlan.class.getSimpleName(), "Here is the data: " + someString);
}
}
Step 3: passing this interface to the adapter
public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {
...
private OnRecipeClickListener clickListener;
// data is passed into the constructor
public RecipeListAdapter(Context context, List<Category> data, OnRecipeClickListener clickListener) {
...
this.clickListener = clickListener;
}
...
}
Step 4: setting click listeners to view holders
public class RecipeListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder> {
...
#Override
public void onBindViewHolder(#NonNull com.stu54259.plan2cook.Adapters.RecipeListAdapter.ViewHolder holder, int position) {
...
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickListener.onRecipeClicked(position,
holder.textView1.getText().toString());
}
});
}
...
}
Code from Step 2 can be used like that:
OnRecipeClickListener listener = new OnRecipeClickListener() {
public void onRecipeClicked(int position, String someString) {
Log.d(CreateMealPlan.class.getSimpleName(), "Here is the data: " + someString);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);

How to pass the SharedPreferences data from the settingActivity to the MainAdapter?

I created a shopping cart app, and it has a menu item. Then it has another activity called "SettingActivity", for this settingActivity will have a TextView to show "Primary language, secondary language and both language".
I got the SharedPreferences data in the SettingActivity. How can I pass those data to the MainAdapter?
Because when I click the secondary language in the SettingActivity, then the menu will change to secondary language or show both languages.
So, how can I get the SettingActivity's SharedPreference data in the MainAdapter?
SettingActivity:
public class SettingActivity extends AppCompatActivity {
LinearLayout languageModeLinearLayout;
TextView languageModeTextView;
SharedPreferences settingPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
languageModeLinearLayout = findViewById(R.id.setting_language_mode_linearLayout);
languageModeTextView = findViewById(R.id.setting_language_mode_textView);
settingPreferences = getSharedPreferences("setting", MODE_PRIVATE);
updateUI();
languageModeLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String[] language = getResources().getStringArray(R.array.setting_language_mode);
AlertDialog.Builder languageMode = new AlertDialog.Builder(v.getContext());
languageMode.setTitle("Select Language Mode");
languageMode.setItems(language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
SharedPreferences.Editor editor = settingPreferences.edit();
editor.putInt("language", position);
editor.apply();
updateUI();
}
});
languageMode.create().show();
}
});
}
private String getLanguage(){
String[] language = getResources().getStringArray(R.array.setting_language_mode);
int position;
position = settingPreferences.getInt("language", 0);
return language[position];
}
private void updateUI(){
languageModeTextView.setText(getLanguage());
}
MainAdapter:
public class MainAdapter extends ArrayAdapter<MenuItem> implements Serializable {
private TextView mCartCounterTextView;
public MainAdapter(Context context, List<MenuItem> menuItems) {
super(context, 0, menuItems);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View itemView = convertView;
final ViewHolder viewHolder;
if (itemView == null) {
itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_main, parent, false);
viewHolder = new ViewHolder(itemView);
itemView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) itemView.getTag();
}
final MenuItem currentMenuItem = getItem(position);
viewHolder.nameTextView.setText(currentMenuItem.getPrimaryName());
viewHolder.nameTextView.setText(currentMenuItem.getSecondaryName());
viewHolder.addToCartButton.setText(getFormattedPriceTextToButton(currentMenuItem));
viewHolder.addToCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Main.getAddedItems().add(currentMenuItem);
Toast.makeText(v.getContext(), "Item had added to cart", Toast.LENGTH_SHORT).show();
mCartCounterTextView.setText(String.valueOf(Main.getAddedItems().size()));
mCartCounterTextView.setVisibility(View.VISIBLE);
}
});
return itemView;
}
private String getFormattedPriceTextToButton(MenuItem currentMenuItem) {
return "+ $" + currentMenuItem.getPrice();
}
private class ViewHolder {
TextView nameTextView;
TextView priceTextView;
Button addToCartButton;
public ViewHolder(View itemView) {
nameTextView = itemView.findViewById(R.id.main_name_textView);
priceTextView = itemView.findViewById(R.id.main_price_textView);
addToCartButton = itemView.findViewById(R.id.main_add_to_cart_button);
}
}
public void setData(TextView cartCounter){
mCartCounterTextView = cartCounter;
}
private void getSharedPreferencesLanguage(){
// SharedPreferences.Editor editor = getContext().getSharedPreferences("setting", MODE_PRIVATE).edit();
SharedPreferences language = getContext().getSharedPreferences("setting", MODE_PRIVATE);
}
MenuItem:
public class MenuItem {
private String mPrimaryName;
private String mSecondaryName;
private double mPrice;
public MenuItem(String primaryName, String secondaryName, double price){
mPrimaryName = primaryName;
mSecondaryName = secondaryName;
mPrice = price;
}
public String getPrimaryName(){
return mPrimaryName;
}
public String getSecondaryName(){
return mSecondaryName;
}
public double getPrice(){
return mPrice;
}
Just pass your context to the function and get the value from sharedpref
public static String getLan(Context cont) {
SharedPreferences settingPreferences=settingPreferences =cont.getSharedPreferences("setting", MODE_PRIVATE);
String[] language = getResources().getStringArray(R.array.setting_language_mode);
int posi =settingPreferences.getInt("language",0);
return language[pos];
}
I think you are doing well on
SharedPreferences language = getContext().getSharedPreferences("setting", MODE_PRIVATE);
But now if you want to get the data (language int in this case) you just have to do the following:
int lang_int = language.getInt("language",0);

Is it possible to pass only String to a custom listview adapter?

I am passing through a while loop which has different Strings for my adapter. But it doesn't show anything, however if I pass an array it works. I don't know if I can pass only a String and if the return of the overridden methods are correct.
public class ReportAdapter extends BaseAdapter {
private Context context;
private String debtor;
private String receiver;
private BigDecimal difference;
private String groupName;
LayoutInflater inflater;
public ReportAdapter(Context applicationContext, String debtor, String receiver, BigDecimal difference, String groupName) {
this.context = applicationContext;
this.debtor = debtor;
this.receiver = receiver;
this.difference = difference;
this.groupName = groupName;
inflater = LayoutInflater.from(applicationContext);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return 0;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
DecimalFormat df = new DecimalFormat("##.00");
SharedPreferences sharedPrefs = context.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPrefs.edit();
convertView = inflater.inflate(R.layout.report_list_view, null);
TextView debtor = convertView.findViewById(R.id.debtor_tv);
TextView receiver = convertView.findViewById(R.id.receiver);
TextView difference = convertView.findViewById(R.id.difference_tv);
final CardView paidCard = convertView.findViewById(R.id.paid_cardview);
final Switch paidSwitch = convertView.findViewById(R.id.paid_switch);
debtor.setText(debtor.toString());
receiver.setText(receiver.toString());
difference.setText(String.valueOf(df.format(difference) + "€"));
paidSwitch.setChecked(sharedPrefs.getBoolean(groupName + "_checkValue" + position, false));
if (paidSwitch.isChecked()) {
// Set green background
paidCard.setCardBackgroundColor(Color.parseColor("#FF2E7D32"));
}
paidSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Set green background
paidCard.setCardBackgroundColor(Color.parseColor("#FF2E7D32"));
editor.putBoolean(groupName + "_checkValue" + position, isChecked);
editor.commit();
} else {
// Set red background
paidCard.setCardBackgroundColor(Color.parseColor("#FFB71C1F"));
editor.putBoolean(groupName + "_checkValue" + position, isChecked);
editor.commit();
}
}
});
return convertView;
}
The listview doesn't appear. Could it be that the constructor accepts only Array type? Or I can pass a String? The getCount() and the getItem() methods, have to return 0? Because with an ArrayList I return the arraylist.get(position), but with a String, what should I return?
Certainly you can pass String values to your ListView. My question would be: Why use a ListView for a single entry? A ListView generates a lot of overhead.
Why the ListView is not showing any values is because the method getCount()dictates how many rows are displayed in your list.
A better solution would be to create a custom class--maybe Transactions that contains getters and setters for debtor and receiver. Add a new Transactions to an ArrayList for each row to be displayed in the ListView...even if it is only one row.
Possible solution::
public class MyListAdapter extends ArrayAdapter<Transaction> {
private static final String TAG = MyListAdapter.class.getSimpleName();
public MyListAdapter(Context context, ArrayList<Transaction> transactionList) {
super(context, 0, transactionList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
Transaction transactionData = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout_2, parent, false);
}
TextView textView1 = (TextView) convertView.findViewById(R.id.textView1);
TextView textView2 = (TextView) convertView.findViewById(R.id.textView2);
String debtor = transactionData.getDebtor();
String receiver = transactionData.getReceiver();
textView1.setText(debtor);
textView2.setText(receiver);
return convertView;
}
}
The custom Transaction class could look like this:
public class Transaction {
private String debtor = "";
private String receiver = "";
public Transaction(){
}
public Transaction(String debtor, String receiver){
this.debtor = debtor;
this.receiver = receiver;
}
public void setDebtor(String debtor){ this.debtor = debtor; }
public void setReceiver(String receiver){ this.receiver = receiver; }
public String getDebtor(){ return this.debtor; }
public String getReceiver() { return this.receiver; }
}
Now you can simply populate the list:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// There would of course be a better way to populate the data!!
ArrayList<> transactionList = new ArrayList<>();
transactionList.add(new Transaction("Mike","Bob"));
MyListAdapter theAdapter = new MyListAdapter(this, arrayDriverListData);
ListView transaction_list = (ListView) findViewById(R.id.transaction_list);
transaction_list.setAdapter(theAdapter);
}
NOTE:
I typed this in a standard TextEditor (no auto-correct) ... so there might be a few errors.

Phone directories in Android and problems with getting anything from them

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.

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();
}
}

Categories