I am trying to view list elements on the same view however 6 at a time. To start with, a cursor is called which in turn populates an array list with all the items.
if (cursor.moveToFirst())
{
try {
do {
items.add(ChecklistItem.fromCursor(cursor));
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
}
}
Then that list is given to an adapter, which in turn handles vieweing the items on the current view.
if (items.size() > 0) {
if (mAdapter == null)
{
mAdapter = new RecipeDetailAdapter(this, items, this);
mRecyclerView.setAdapter(mAdapter);
}
else
{
mAdapter.updateItems(items);
}
}
On the view, there is a next button, which when clicked takes you to another view.
public void onClick(View view) {
switch (view.getId()) {
case R.id.next_button:
startActivity(new Intent(RecipeDetailActivity.this, RecipeTasksActivity.class)
.putExtra(RecipeTasksActivity.RECIPE_KEY, mRecipe.getRecipeId()));
finish();
break;
}
}
At the moment the view shows whatever items are in the list, could be 10, 30, 50, etc.
What I am trying to achieve is, assuming the list has 18 items, view the first 6 items in that list, then when the button "next" is clicked, view the other 6, and then when next is clicked, view the rest of the 6. Keeping in mind that I need to check if the list has 6 items or less, if less, view all of them, if more, spread them on two instances of the same view.
Any suggestions on how to approach this?
Yes you can do that by using the OFFSET & LIMIT in your query.
db.rawQuery("SELECT * FROM " + TABLE_NAME + " ORDER BY " + ORDER_BY + " LIMIT 0, 20", NULL);
Note : On above 0 is your OFFSET & 20 is your limit. in your case LIMIT would be 6. You can maintain offset by k * Limit where k would your pager number.
Related
I'm making a bedwars plugin in spigot 1.8_R3, I'm currently working on the shop system, when you click on an item to purchase it, 4 iron ingots should be removed from the players inventory.
inventory.remove(new ItemStack(getResource(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".type")), Integer.parseInt(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".cost"))));
However, this code only removes the iron if there are exactly 4 iron ingots. How would I make it so 4 iron ingots would be removed from different amounts such as 5?
Edit :
I tried to use this code :
public void removeItemFromInventory(Inventory inv, ItemStack currentItem, Player p) {
ItemStack item = new ItemStack(getResource(Main.plugin.getConfigValue("shop." + currentItem.getTypeId() + ".type")), Integer.parseInt(Main.plugin.getConfigValue("shop." + currentItem.getTypeId() + ".cost")));
if(inv.contains(item)) { // contains the exact item
inv.remove(item); // remove first time it find this item
} else { // doesn't contains this item
for(ItemStack invItem : inv.getContents()) {
if(invItem.getType().equals(item.getType())) { // if it's this type of item.
// You can add other check specially for ItemMeta ...
int amount = invItem.getAmount(); // amount of actual item
int stay = item.getAmount(); // keep amount
if(amount > stay) { // too many item, just change amount
invItem.setAmount(amount - stay); // change amount to remove it
break; // stop loop
} else if(amount < stay) { // not enough item
invItem.setAmount(0); // you can also remove the item by setting air to this slot
item.setAmount(stay - amount); // reduce amount of item to delete
}
}
}
}
FastShop shop = new FastShop(p );
p.closeInventory();
p.openInventory(shop.getInventory());
}
I'm currently getting a nullpointer error. I'm still need of help!
This part of code will search an item similar to "Iron Ingot x4". If it's not similar, it doesn't change what is it because it's just different.
You should do like that :
ItemStack item = new ItemStack(getResource(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".type")), Integer.parseInt(Main.plugin.getConfigValue("shop." + e.getCurrentItem().getTypeId() + ".cost")));
if(inv.contains(item)) { // contains the exact item
inv.remove(item); // remove first time it find this item
} else { // doesn't contains this item
for(ItemStack invItem : inv.getContents()) {
if(invItem != null && invItem.getType().equals(item.getType()) { // if it's this type of item.
// You can add other check specially for ItemMeta ...
int amount = invItem.getAmount(); // amount of actual item
int stay = item.getAmount(); // keep amount
if(amount > stay) { // too many item, just change amount
invItem.setAmount(amount - stay); // change amount to remove it
break; // stop loop
} else if(amount < stay) { // not enough item
invItem.setAmount(0); // you can also remove the item by setting air to this slot
item.setAmount(stay - amount); // reduce amount of item to delete
}
}
}
}
player.updateInventory();
This isn't exactly a full solution with code. However, you can do this.
Create an integer for the amount of iron required.
Create a for loop that iterates through a players inventory and if that slot contains iron then:
if the amount in the slot is greater than the iron integer, remove the iron
integer from that slot and give the item that is owed. else remove the amount in the slot from the iron integer and delete that slot.
I hope you can solve your issue from this.
I was writing a junit test where I wanted to know whether the view pager is at the last element or not. How can I do this. Actually I am a begineer at writing unit tests.
Thanks in advance :)
You can get current position from ViewPager usign getCurrentItem(). This value you can compare with number of the elements in ViewPager's adapter.
Remember that items in ViewPager are indexed from 0 (so 0, 1, 2, 3, ...), but number of items (in adapter) in amount of elements.
In kotlin:
val result = if (view_pager.adapter == null) {
// Adapter did not set
false
} else {
// Check if "current position" equal "number of elements
view_pager.currentItem == view_pager.adapter?.count?.minus(1)
}
In Java:
boolean result;
if (viewPager.getAdapter() == null) {
// Adapter did not set
result = false;
} else {
// Check if "current position" equal "number of elements
result = viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1;
}
When a user types in my searchbox I use onQueryTextChange so the text is filtered and either:
1) a "No Results" textbox should be shown - if nothing typed matches the items in my list.
2) The matching items are shown in my recyclerView.
For the most part it is working ok but sometimes it is like the onQueryTextChange is a step behind.
For example, "plumber" is one of the items in my list, the only item beginning with "p"
The user types "p" in searchbox, "plumber" appears in my recyclerView - yet I get the toast "mAdapter size is: 13". 13 is the whole number of items, mAdapter size should be just 1.
When I type "pl" the toast for mAdapter is correct, it shows 1.
When I type "plk" the toast for mAdapter is wrong, it still shows 1 - it should say, "mAdapter is 0, no item results" and instead of the recyclerView we should see the "No Results" textbox.
It's only when I type the next character, like "plke", that I see "mAdapter is 0, no item results" and the "No Results" textbox.
Here's my code:
#Override
public boolean onQueryTextChange(String query) {
//items is the complete list of the category names available to the logged-in user
items = new Gson().fromJson(the_response, new TypeToken<List<Category>>() {
}.getType());
//clear the list every time a key is pressed
categoryList.clear();
//was getting NullPointerException so put this here...
if (items != null && items.size() > 0) {
//adding categories to category list
categoryList.addAll(items);
}
mAdapter.getFilter().filter(query);
recyclerView.setAdapter(mAdapter);
if (mAdapter.getItemCount() < 1) {
//if there's nothing to show, hide recyclerView...
recyclerView.setVisibility(View.GONE);
//and show the "No Results" textbox
noResultsFoundView.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "mAdapter is 0, no item results", Toast.LENGTH_SHORT).show();
}
if (mAdapter.getItemCount() >= 1) {
recyclerView.setVisibility(View.VISIBLE);
noResultsFoundView.setVisibility(View.GONE);
//if there ARE category results for what is typed, with each key press...
Toast.makeText(getApplicationContext(), "mAdapter size is:" + mAdapter.getItemCount(), Toast.LENGTH_SHORT).show();
}
//if the searchView is empty
if (searchView.getQuery().length() == 0) {
//show the logged-in users reviews, not the searched categories
recyclerView.setAdapter(pAdapter);
pAdapter.notifyDataSetChanged();
//show the recyclerview, hide the noResults textview
recyclerView.setVisibility(View.VISIBLE);
noResultsFoundView.setVisibility(View.GONE);
}
// refreshing recycler view
mAdapter.notifyDataSetChanged();
return false;
}
I am having a bit of a dilemma at the moment with regards to the best way to target and use what the user has selected from a spinner (drop-down menu) in my application.
To give you some insight, say I have two activities, one called create line which is where the user selects their option from the spinner and the next called line details where I want to be able to work with what the user has selected.
I am currently successfully saving the users drop down selection to an SQLite database.
In my spinner the user can either select the options of 20 or 30. On the line details which is the second activity I want to be able to write an IF statement to tell my app to do something depending on whether they have selected 20 or 30?
What is the best method to get the users selections and prepare an IF statement?
Should I use a db.query to get what the user has selected and use it in an IF statement?
Should I store the selection in a Sharedpreference and target it that way?
Here is the spinner code:
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
quantity.setText("");
;
break;
case 1:
quantity.setText(PackageType20);
timeadded = 28;
duration.setText(timeadded + " Hours");
break;
case 2:
quantity.setText(PackageType30);
timeadded = 27;
duration.setText(timeadded + " Hours");
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
EDIT WITH ATTEMPTED METHOD:
CREATE LINE:
on create line I am storing the users selection in a public static variable:
public static spinnerSelection2 = String.valueOf(spinner2.getSelectedItem());
LINEDETAILS:
then I am referencing that string on the next activity and setting it to this variable in which I will use in the IF statement:
String spinnerSelection2 = CreateLine.spinnerSelection2;
if (spinnerSelection2.equals("20")) {
optimum20 = (int) (diffminutes * 0.383);
percentage20 = optimum20 / (648 * 100);
} else if (spinnerSelection2.equals("30"))
optimum30 = (int) (diffminutes * 0.373);
percentage30 = optimum30 / (605 * 100);
I am not quite sure of what method is the best to use and also unsure of how to do each.. any help would be great!
Thanks
To do that in your switch cases add following lines to go into new activity:
Intent intent = new Intent(getContext(),yourSecondActivity.class);
intent.putExtra("duration",duration);
intent.putExtra("PackageType", packageType);
In your second activity create two strings to store these values. And to import these values there in on create write this :
yourVariable = intent.getStringExtra("duration");
yourSecondVariable = intent.getStringExtra("packageType");
After that you can apply if else to check which condition satisfies and do operations there accordingly.
I didn't customize anything on RecyclerView so there's default animation on item added/removed. While I found the animation isn't working as I expected. When I removed item by the following code:
mComments.remove(position);
notifyItemRemoved(position);
I see on UI it always remove the wrong one, and the one should be removed already keeps showing up and overlay the others.
new CountDownTimer(60000, 1000) {
#Override
public void onTick(long l) {
for (int i = 0; i < mComments.size(); i++) {
RoomMessage item = mComments.get(i);
item.timeRemaining -= 1000;
if (item.timeRemaining <= 0) {
Log.v(TAG, "Going to remove no." + i + ". And the content = " + mComments.get(i).text);
removeAt(i);
}
}
}
#Override
public void onFinish() {
start();
}
}.start();
According to log, I did remove the right one. See as below.
02-16 15:26:38.274 21861-21861/com.xxxx.android V/ChatsAdapter: Going to remove no.0. And the content = 1
02-16 15:26:41.284 21861-21861/com.xxxx.android V/ChatsAdapter: Going to remove no.0. And the content = 2
02-16 15:26:42.284 21861-21861/com.xxxx.android V/ChatsAdapter: Going to remove no.0. And the content = 3
What did I do wrong?
btw I've set setisRecyclable(false)
Use only notifyItemRemoved(position);.You are using both. notifyItemRemoved which is for notifying that items previously located at position has been removed from the data set. While notifyItemRangeChanged(int positionStart, int itemCount) is used only when notify any registered observers that the itemCount items starting at position positionStart have changed. If you are adding single item use notifyItemInserted. If you have added more then one new items then use notifyItemRangeInserted(int positionStart, int itemCount). Any method ending with Changed states that the value or values of that particular item or row has changed.