In my program i am using ListView and in each and every row i am showing one of the image icon (Yes/No) based on condition i am playing with, and using below code to get total number of item(s) in a list (includes both :- Yes & No) Icons.
String totalNumberOfItemsInAList = ""+ lstView.getAdapter().getCount();
Toast.makeText(getApplicationContext(), "Total number of Items are:" + totalNumberOfItemsInAList, Toast.LENGTH_LONG).show();
But what if i only want to know total number of items in a list which contains Yes Icon, my code looks like this:
private SparseBooleanArray flags = new SparseBooleanArray();
// to upload whole list
for(int position = 0; position < lstView.getAdapter().getCount(); position++)
{
flags.put(position, true);
}
((BaseAdapter) lstView.getAdapter()).notifyDataSetChanged();
}
});
/*** Get Images from SDCard ***/
listSDCardImages = fetchSDCardImages();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listSDCardImages);
lstView.setAdapter(new ListSDCardImagesAdapter(this));
Toast.makeText(getApplicationContext(), "Total number of Items are:" + String.valueOf(position), Toast.LENGTH_LONG).show();
}
Condition, i am using to show Yes/No icons is something like this:
if(resultAvailable)
{
holder.colView.setImageResource(R.drawable.icon_yes);
}
else
{
holder.colView.setImageResource(R.drawable.icon_no);
}
Use
yesImagesCount=0;
variable in your activity and increment this count in this code as
if(resultAvailable)
{
holder.colView.setImageResource(R.drawable.icon_yes);
yesImagesCount++;
}
else
{
holder.colView.setImageResource(R.drawable.icon_no);
}
And Finally display toast as
Toast.makeText(getApplicationContext(), "Total number of Yes Icons are:" + String.valueOf(yesImagesCount), Toast.LENGTH_LONG).show();
Related
I have a json array of all names and contacts on my phone, looks something like this:
[{"name":"andy","phone_number":"+123"},{"name":"bob","phone_number":"+456"},{"name":"chris","phone_number":"+789"}]
I check the phone numbers against phone numbers in a db, if there's a match I want to show the name in the recycler view, if no match, then show just the number.
For example, +123, yes, it is in the db, so show andy in the cell in recyclerview. +789 is not in the db, so show +789 in the cell.
Here's what I'm working with so far: it works when there is a match, the if part, but I don't know how to deal with the else part (for when there is no match). If I uncomment my else code it always jumps straight to there.
public void onResponse(String response) {
try {
//name our JSONObject User_Private_Public_Obj, which is response from server
//the response from server will be like:
//{"private_review_ids":[{"reviewid":7,"username":"+123"},{"reviewid":14,"username":"+456"}]}
JSONObject User_Private_Public_Obj = new JSONObject(response);
//Now break up the response from server
//We want the JSON Array part, "private_review_ids"
JSONArray private_ids = User_Private_Public_Obj.getJSONArray("private_review_ids");
for
//get the number of objects in User_Private_Public_Obj
(int i = 0; i < private_ids.length(); i++)
{
//for each object in the array private_ids, name it obj
//each obj will consist of reviewid and username
JSONObject obj = private_ids.getJSONObject(i);
Review review = new Review();
//get the string from sharedpreferences, AllPhonesandNamesofContacts,
//it will be like [{"phone_number":"+123","name":"andy"}, etc...]
//we want this so we can display phone name in recyclerView, if it's a contact
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("AllPhonesandNamesofContacts", "0");
//convert the string above into a json array
JSONArray jsonArray = new JSONArray(json_array);
//set a string to the phone number from the DB,
//the phone number of the person who made the review
phoneNoInDB = obj.getString("username");
//set the setter to the phone number string, the string is
//the phone number of the person who made the review
review.setPhoneNumberofUserFromDB(phoneNoInDB);
//jsonArray is our All Phones and Names of Contacts array
int matching = jsonArray.length();
for (int n = 0; n < matching; n++) {
try {
//for every object in "All Phones and Names of Contacts" array...
JSONObject object = jsonArray.getJSONObject(n);
//if the review maker is a contact...that is,
//if the phone_number in AllPhonesandNamesofContacts equals
//the phone number in the DB
if (object.getString("phone_number").equals(phoneNoInDB)) {
//just for testing purposes...
Toast.makeText(NewActivity.this, object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
//then rip out the other part of the object, the name in
// AllPhonesandNamesofContacts
//of the person who made the review
review.setphoneNameonPhone(object.getString("name"));
//add the review to the sharedReviewList
reviewList.add(review);
}
/* else {
//just for testing...
Toast.makeText(NewActivity.this, " should be green" + object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
review.setphoneNameonPhone(object.getString("phone_number"));
//add the review to the sharedReviewList
//reviewList.add(review);
}*/
} catch (JSONException e) {
System.out.println("error in if else");
//Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//set the adapter to show the random reviews
recyclerView.setAdapter(uAdapter);
I'm creating an android chat app.. The main screen will be a list of messages.. I get the messages and the friends from the database then show it in my list which contains two textviews and 1 imageview.. every thing works fine, but when i get my friends from database(not the same size of messages) and I need to get Imagepath of each friend.. that works fine also when i log it.. but when I try to get it in the adapter i get my list with only one unit..
messages_iv = (ImageView) row.findViewById(R.id.imageView1);
final String name = items.get(position).getTitle();
final String photoUrl = friends.get(1).getPhotoUrl();
new Thread(new Runnable() {
public void run() {
Log.d("Button Clicked", "Name: " + name);
Log.d("Button Clicked", "URL: " + photoUrl);
getPhoto(messages_iv, photoUrl);
}
}).start();
when I try friends.get(0) it works fine.. but when I try friends.get(1) I get :
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
Any Idea ??
Thanks.
I found out a common way to store data is Android's SharedPreferences. So I went out and tried to implement it with my application.
What I want to do:
My application retrieves weather details from the users current location, if the user desires he/she can add the location by pressing add to favorites. They can have up to 10 favorite locations. So I want to store the location description (exp: Dayton, OH), the latitude and longitude (So I may fetch the details when they want to see that weather). So Shared Preferences seem to fit my need.
What I did:
- I created a loop that would cycle through 10 keys (for 10 locations) an as long as the keys were null the location information would be saved. If the key was not null, it means the key has already been created.
My code:
public void writeNewLocation(String stringLat, String stringLon, String location) {
this.latitude = stringLat;
this.longitude = stringLon;
this.location = location;
pref = mContext.getSharedPreferences("favoritelocations", 0); // 0 - for private mode
Editor editor = pref.edit();
//Loop through all the favorite keys to find an open spot:
for(int i = 1; i <= 10; i++) {
//Test for current favorite key:
String value = pref.getString("favorite"+ i +"_location",null);
if (value == null) {
//The key does not exist so it can be created and written to:
//First write the location description:
editor.putString("favorite" + i + "_location", location);
//Next the write the latitude and lonitude values:
editor.putString("favorite" + i + "_latitude", latitude);
editor.putString("favorite" + i + "_longitude", longitude);
editor.commit();
i = 11;
} else {
//If at end of loop; Inform user:
if(i == 10) {
//Display an error:
//Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//Create the AlertDialog characteristics:
builder.setMessage("You can only have up to 10 favorite locations. Delete some to make room.");
builder.setTitle("Message");
//Show the AlertDialog:
msgDialog = builder.create();
editor.commit();
i = 11;
} else {
//Back to top of loop.
}
}
}
//Commit to changes:
editor.commit(); // commit changes
}
So I loop through ten possible keys, if it hits 10, and all spots are taken, I alert the user. But when I call this method to create a favorite location, then call 1 of the 10 getters to display the information that should've been saved, I get a null. :( Is it too early in the morning over here or am I doing something wrong...
Thanks c:
I am getting an array from parse.com. I am using an array, to retrieve an array:
fightList.whereContainedIn("objectId", itemListCard);
fightList.findInBackground(new FindCallback<ParseObject>() ....
My first array; itemListCard is in a specific order. After I findInBackground, my array from online, (objectId), is completely out of order. This is because I am getting it from Parse.com, so it is added to the array as it is retrieved. I need to:
1. Re-order array objectId to match itemListCard or
2. Retrieve objectId in order of itemListCard
Java code:
HomeItemList = new ArrayList<HomeItem>();
fightList.whereContainedIn("objectId", itemListCard);
fightList.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objectId, ParseException e) {
if (e == null) {
for (int i = 0; i < objectId.size(); i = i + 2) {
HomeItem homeItem = new HomeItem();
homeItem.setHomeItemID(k);
k++;
//set Red Array
homeItem.setHomeItemRedName(objectId.get(i).getString("Name"));
homeItem.setHomeItemRedAge(objectId.get(i).getString("Age"));
homeItem.setHomeItemRedRecord(objectId.get(i).getString("Record"));
homeItem.setHomeItemRedHeight(objectId.get(i).getString("Height"));
homeItem.setHomeItemRedWeight(objectId.get(i).getString("Weight"));
homeItem.setHomeItemRedCity(objectId.get(i).getString("Location"));
homeItem.setHomeItemRedExp(objectId.get(i).getString("Experience"));
//set blue Array
homeItem.setHomeItemBlueName(objectId.get(i+1).getString("Name"));
homeItem.setHomeItemBlueAge(objectId.get(i+1).getString("Age"));
homeItem.setHomeItemBlueRecord(objectId.get(i+1).getString("Record"));
homeItem.setHomeItemBlueHeight(objectId.get(i+1).getString("Height"));
homeItem.setHomeItemBlueWeight(objectId.get(i+1).getString("Weight"));
homeItem.setHomeItemBlueCity(objectId.get(i+1).getString("Location"));
homeItem.setHomeItemBlueExp(objectId.get(i+1).getString("Experience"));
HomeItemList.add(homeItem);
}
HomeListAdapter = new HomeListAdapter(getApplicationContext(), 0, HomeItemList);
adapter.addSection(" Fight Card ", HomeListAdapter);
} else {
progressDialog.dismiss();
Log.d("Display Card", "Error parsing Card");
Log.d("Card Error:", e.getMessage());
Toast.makeText(databaseFightCard.this, "Could not retrieve parse info. Try again later", Toast.LENGTH_LONG).show();
}
listView.setAdapter(adapter);
progressDialog.dismiss();
}
});
Note
The for loop is counting by 2 because this is the structure I am going for:
objectId[0] vs objectId[1]
objectId[2] vs objectId[3]
objectId[4] vs objectId[5]
objectId[6] vs objectId[7]
....and so on
Hence the need for a specific order.
You can control the order in which the items are returned using orderByAscending() and orderByDescending().
In your case:
fightList.whereContainedIn("objectId", itemListCard);
fightList.orderByAscending("objectId");
fightList.findInBackground(new FindCallback<ParseObject>() ....
See Query Constraints section of the the Parse Android Guide.
I have an application that has 2 screens. The first screen has a ListView of movies with a row consisting of 3 Elements: Title, Date and Gross declared in strings.xml. The user has the option of adding a movie by clicking the menu button, which sends him to another screen. The second screen has 3 Edit texts that correspond to Title Date and Gross, which is alphabetically sorted straight away when it returns to screen 1.
Similarly, the user can also Edit/Delete entries by long clicking a row thatbrings up a context menu. The Edit function works like this:
a.) User long clicks Titanic and chooses Edit
b.) Row gets deleted, and user is brought to screen 2
c.) Edit texts are populated with the initial data from the deleted Row
d.) When user edits data, new movie is added at the bottom of the ListView.
The problem arises when the user deletes this new movie at the bottom of the ListView. Logcat gives a
java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50
Here is my code (Take note I am using Perst to persist data, but I don;t think that won't really matter with my problem):
case R.id.contextedit:
Lab9_082588FetchDetails row = (Lab9_082588FetchDetails) getListView()
.getItemAtPosition(info.position);
Intent editData = new Intent(MovieList.this, Lab9_082588Edit.class);
String startTitle = row.getTitle();
String startGross = row.getGross();
String startDate = row.getDate();
editData.putExtra(Lab9_082588Edit.TITLE_STRING, startTitle);
editData.putExtra(Lab9_082588Edit.GROSS_STRING, startGross);
editData.putExtra(Lab9_082588Edit.DATE_STRING, startDate);
startActivityForResult(editData, MovieList.EDIT_MOVIE);
int posEdit = info.position;
String editTitle = results.get(info.position).getTitle();
results.remove(posEdit);
adapter.notifyDataSetChanged();
//Perst
Index<Lab9_082588FetchDetails> rootEdit = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootEdit.remove(editTitle, results.get((int) info.id));
db.setRoot(rootEdit);
return true;
Edit Class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection using item.getItemId()
switch (item.getItemId()) {
case R.id.edit:
next();
break;
}
return true;
}
private void next() {
// TODO Auto-generated method stub
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String title = movieTitle.getText().toString();
String gross = movieGross.getText().toString();
String date = movieDate.getText().toString();
if ((title.length() > 0) && (gross.length() > 0)
&& (date.length() == 4)) {
Intent hobby = getIntent();
hobby.putExtra(Lab9_082588Edit.TITLE_STRING, title);
hobby.putExtra(Lab9_082588Edit.GROSS_STRING, gross);
hobby.putExtra(Lab9_082588Edit.DATE_STRING, date);
setResult(RESULT_OK, hobby);
finish();
}
}
Delete function:
int posDelete = info.position;
String deleteTitle = results.get(
info.position).getTitle();
results.remove(posDelete);
adapter.notifyDataSetChanged();
Index<Lab9_082588FetchDetails> rootDelete = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootDelete.remove(deleteTitle,
results.get(info.position));
db.setRoot(rootDelete); //Perst
return;
OnActivityResult (Edit):
case EDIT_MOVIE:
Lab9_082588FetchDetails edittedMovie = new Lab9_082588FetchDetails();
NumberFormat formatterEdit = new DecimalFormat("###,###,###");
edittedMovie.setTitle(data
.getStringExtra(Lab9_082588Add.TITLE_STRING));
edittedMovie.setGross("$"
+ formatterEdit.format(Double.parseDouble(data
.getStringExtra(Lab9_082588Add.GROSS_STRING))));
edittedMovie.setDate(data
.getStringExtra(Lab9_082588Add.DATE_STRING));
results.add(edittedMovie);
adapter.notifyDataSetChanged();
Populating the Listview:
for (int i = 0; i < items.size(); i++) {
Lab9_082588FetchDetails sr = new Lab9_082588FetchDetails();
sr.setTitle(items.get(i).getTitle());
sr.setGross(items.get(i).getGross());
sr.setDate(items.get(i).getDate());
results.add(sr);
Collections.sort(results, ignoreCaseStart);
}
How do I remedy this?
This problem occurs because in your delete function, you first remove the element from the results collection("results.remove(posDelete);"), and then, a few lines later, you call "results.get(info.position)" to fetch a parameter for the rootDelete.remove call, but which is already removed.
If the element is the last element of your collection, let's say the 50th element, the value for "info.position" is 50. You remove one element, so the number of elements is now 49. In the rootDelete.remove line you call results.get(50), which produces the error.