How to highlight words in TextView based on data - java

I want to highlight the text in the TextView that matches the data taken from the database. I use the code below but the text in the TextView doesn't change color.
Here's my code, but the setters and getters looks useless.
class getICT {
#SerializedName("eng")
private String eng;
#SerializedName("bhs")
private String bhs;
#SerializedName("kor")
private String kor;
public getICT(String eng, String bhs, String kor, String imageURL){
this.eng = eng;
this.bhs = bhs;
this.kor = kor;
}
/*
GETTERS N SETTERS
*/
public String getEng() {
return eng;
}
public String getBhs() {
return bhs;
}
public String getKor() {
return kor;
}
#Override
public String toString() {
return eng;
}
}
This is my interface, get from database
interface MyAPIService {
#GET("/ICT03/danger.php")
Call<getICT[]> getICT();
}
I write the code for highlight the text from here
ShowDetected.MyAPIService myAPIService = ShowDetected.RetrofitClientInstance.getRetrofitInstance().create(ShowDetected.MyAPIService.class);
Call<getICT[]> call = myAPIService.getICT();
call.enqueue(new Callback<getICT[]>() {
#Override
public void onResponse(Call<getICT[]> call, Response<getICT[]> response) {
getICT[] icts = response.body();
String s = showInput.getText().toString();
for(int i = 0; i < icts.length; i++) {
if (icts[i].equals(s)) {
showInput.setText(s);
showInput.setTextColor(Color.RED);
} else {
showInput.setTextColor(Color.BLACK);
}
}
}
#Override
public void onFailure(Call<getICT[]> call, Throwable t) {
Toast.makeText(ShowDetected.this, ""+t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});

Your code is incorrect, try this
boolean isHighlight = false
for(int i = 0; i < icts.length; i++) {
if (icts[i].equals(s)) {
isHighlight = true;
break;
}
}
showInput.setTextColor(isHighlight ? Color.RED : Color.BLACK);

Related

Realm does not save attributes, object is not managed although copied to Realm

I have an issue with realm. I receive a custom object from an API. I assign this object to a POJO object using retrofit. Within this object I have an ArrayList of the ToDoItemobject which extends RealmObject.
I receive the data correctly with all attributes, everything gets correctly assigned. I run it through my synchronization algorithm and save it to realm in a writing transaction. But when retrieving the data after realm.commit(); the attributes of the objects are all 0 or null.
The method isManaged()is always false, even after the writing transaction, which I don't understand because in the official documentation is states that a POJO can be converted to a managed object using the copyToRealm method.
I already tried a number of things: creating the GetItemResponseClass as RealmObject, but not possible since it has to extend JSONObject to correctly receive the data from the API. I also tried to write the whole list directly to realm but the result was the same.
As a side note, it can be that my method syncPendingLists has some logic errors, but I couldn't debug it yet, since the attributes were always o and null. Thanks for any help.
Here my code from the Activity:
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().name("myrealm.realm").build();
Realm.setDefaultConfiguration(config);
realm = Realm.getDefaultInstance();
RealmResults<Counter> counterList = realm.where(Counter.class).findAll();
//setting up counterObject
if (counterList.isEmpty()) {
counterObject = new Counter();
COUNTER = counterObject.getCounter();
} else {
counterObject = counterList.get(0);
COUNTER = counterObject.getCounter();
}
initializeLists();
//Adding the Fragment
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, new DoneListFragment(), "DoneListFragment");
ft.add(R.id.fragment_container, new PendingListFragment(), "PendingListFragment");
ft.commit();
RetrofitClient retrofitClient = new RetrofitClient();
Retrofit retrofit = retrofitClient.getClient();
mAPIInterface = retrofit.create(ToDoistAPIInterface.class);
}
public void getRemoteItems() {
final ArrayList<ToDoItem> onlineItems = new ArrayList<ToDoItem>();
JSONArray array = new JSONArray();
array.put("items");
String auxMessage = array.toString();
mAPIInterface.getItems(RetrofitClient.TOKEN, "*", auxMessage).enqueue(new Callback<GetItemsResponseClass>() {
#Override
public void onResponse(Call<GetItemsResponseClass> call, Response<GetItemsResponseClass> response) {
GetItemsResponseClass itemsResponseClass = new GetItemsResponseClass();
itemsResponseClass = response.body();
remoteItemsList = itemsResponseClass.getItems();
boolean test = remoteItemsList.get(0).isManaged(); //returns false
boolean test1 = remoteItemsList.get(0).isValid(); //returns true refers to singleton RealmObject
syncPendingLists(pendingItemList, remoteItemsList);
}
#Override
public void onFailure(Call<GetItemsResponseClass> call, Throwable t) {
Snackbar.make(floatingButton, "Ups - Couldn't sync items, next time, I promise", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private void initializeLists() {
RealmResults<ToDoItem> realmToDoItemPendingList = realm.where(ToDoItem.class).equalTo("checkedOffline", false).findAll();
initializingArrayListFromDB(realmToDoItemPendingList, pendingItemList);
RealmResults<ToDoItem> realmToDoItemDoneList = realm.where(ToDoItem.class).equalTo("checkedOffline", true).findAll();
initializingArrayListFromDB(realmToDoItemDoneList, doneItemList);
}
private void initializingArrayListFromDB(RealmResults<ToDoItem> realmToDoItemPendingList, ArrayList<ToDoItem> arrayList) {
int h;
for (h = 0; h < realmToDoItemPendingList.size(); h++) {
arrayList.add(realmToDoItemPendingList.get(h));
}
}
public void syncPendingLists(ArrayList<ToDoItem> offlinePendingList, ArrayList<ToDoItem> onlinePendingList) {
//is my sync algorithm, the important part is the for loop at the end of this method
boolean hasMatch = false;
boolean itemChanged = false;
Date offlineDate = null;
Date onlineDate = null;
if (!offlinePendingList.isEmpty()) {
for (ToDoItem item1 : offlinePendingList) {
if (item1.getId() < 10000) {
try {
createNewRemoteItem(item1);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
for (int i = 0; i < onlinePendingList.size(); i++) {
if (item1.getId() == onlinePendingList.get(i).getId()) {
hasMatch = true;
onlinePendingList.remove(onlinePendingList.get(i));
//Compare Fields
if (!item1.getContent().equals(onlinePendingList.get(i).getContent())) {
itemChanged = true;
}
if (item1.getPriority() != onlinePendingList.get(i).getPriority()) {
itemChanged = true;
}
if (!item1.getDate_string().equals(onlinePendingList.get(i).getDate_string())) {
itemChanged = true;
}
if (itemChanged == true) {
//Format edit dates to date
DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
try {
offlineDate = format.parse(item1.getDateAdded());
} catch (ParseException e) {
e.printStackTrace();
}
try {
onlineDate = format.parse(onlinePendingList.get(i).getDateAdded());
} catch (ParseException e) {
e.printStackTrace();
}
//compare dates to see which was last edited
if (offlineDate.compareTo(onlineDate) > 0) {
try {
deleteRemoteItem(onlinePendingList.get(i), "item_delete");
createNewRemoteItem(item1);
} catch (JSONException e) {
e.printStackTrace();
}
} else if (offlineDate.compareTo(onlineDate) < 0) {
addOrUpdateToDB(item1);
}
}
}
if (!hasMatch) {
deleteObjectFromDB(item1);
}
}
}
}
}
for (ToDoItem onlineItem1 : onlinePendingList) {
boolean isManaged1 = onlineItem1.isManaged(); //returns false, which is ok since it is not yet in the realm db
onlineItem1.setLocalId(counterObject.getCounter());
addOrUpdateToDB(onlineItem1);
boolean asdf = onlineItem1.isManaged(); //it returns false, but it should return true
incrementCounter(counterObject);
}
initializeLists();
getPendingListFragment().refreshFragment();
}
private void addOrUpdateToDB(ToDoItem newItem) {
boolean test2= newItem.isManaged(); //returns false
realm.beginTransaction();
realm.copyToRealmOrUpdate(newItem);
//realm.copyToRealm(newItem); //I tried this method as well, but no difference
realm.commitTransaction();
boolean test3= newItem.isManaged(); //returns false, and here is the problem, it should return true, shouldn't it?
assignValuesToToDoItem(itemWithValues, newItem);
saveCounterToDB(counterObject);
}
}
Here my class code of ToDoItem:
public class ToDoItem extends RealmObject implements Parcelable {
public static final Creator<ToDoItem> CREATOR = new Creator<ToDoItem>() {
#Override
public ToDoItem createFromParcel(Parcel in) {
return new ToDoItem(in);
}
#Override
public ToDoItem[] newArray(int size) {
return new ToDoItem[size];
}
};
#PrimaryKey
private long localId;
private String content;
private boolean checkedOffline = false;
private int priority;
private String date_string;
private String temp_id;
private long id;
private String date_added;
public ToDoItem(String name) {
this.content = name;
}
public ToDoItem() {
}
protected ToDoItem(Parcel in) {
localId = in.readLong();
content = in.readString();
checkedOffline = in.readByte() != 0;
priority = in.readInt();
date_string = in.readString();
temp_id = in.readString();
id = in.readLong();
date_added=in.readString();
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public boolean isCheckedOffline() {
return checkedOffline;
}
public void setCheckedOffline(boolean checkedOffline) {
this.checkedOffline = checkedOffline;
}
public Long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setRemote_id(Long remote_id) {
this.id = remote_id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isDone() {
return checkedOffline;
}
public String getDate_string() {
return date_string;
}
public void setDate_string(String date_string) {
this.date_string = date_string;
}
public long getLocalId() {
return this.localId;
}
public void setLocalId(long i) {
this.localId = i;
}
public String getTemp_id() {
return temp_id;
}
public void setTemp_id(String temp_id) {
this.temp_id = temp_id;
}
public String getDateAdded() {
return date_added;
}
public void setDateAdded(String dateAdded) {
this.date_added = dateAdded;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(localId);
dest.writeString(content);
dest.writeByte((byte) (checkedOffline ? 1 : 0));
dest.writeInt((priority));
dest.writeString(date_string);
dest.writeString(temp_id);
dest.writeLong(id);
dest.writeString(date_added);
}
#Override
public String toString() {
return "localId: " + localId + "; content: " + content;
}
}
And here the code for the GetItemsResponseClass:
public class GetItemsResponseClass extends JSONObject {
private String sync_token;
#SerializedName("temp_id_mapping")
private HashMap<String, Long> temp_id_mapping;
private boolean full_sync;
#SerializedName("items")
private ArrayList<ToDoItem> items;
public GetItemsResponseClass(){
}
public String getSync_token() {
return sync_token;
}
public void setSync_token(String sync_token) {
this.sync_token = sync_token;
}
public HashMap<String, Long> getTemp_id_mapping() {
return temp_id_mapping;
}
public void setTemp_id_mapping(HashMap<String, Long> temp_id_mapping) {
this.temp_id_mapping = temp_id_mapping;
}
public boolean isFull_sync() {
return full_sync;
}
public void setFull_sync(boolean full_sync) {
this.full_sync = full_sync;
}
public ArrayList<ToDoItem> getItems() {
return items;
}
public void setItems(ArrayList<ToDoItem> items) {
this.items = items;
}
}
EDIT: Apparently it is a desired behavior that the object does not get saved with its attributes. Consequently to assign the values you have to use getters and setters. I added the following method, however even when debugging with a watch, as stated in the official documentation the values do not get assigned:
private void assignValuesToToDoItem(ToDoItem itemWithValues, ToDoItem newItem) {
realm.beginTransaction();
newItem.setContent(itemWithValues.getContent()); //the content variable stays null
newItem.setCheckedOffline(itemWithValues.isDone()); //stays false
newItem.setPriority(itemWithValues.getPriority());
newItem.setDate_string(itemWithValues.getDate_string());
newItem.setTemp_id(itemWithValues.getTemp_id());
newItem.setId(itemWithValues.getId());
newItem.setDate_added(itemWithValues.getDate_added());
realm.commitTransaction();
}
I added this line assignValuesToToDoItem(itemWithValues, newItem); in the main activity in the method private void addOrUpdateToDB(ToDoItem newItem) {...}
Same result...
I found out 2 very important things:
The attributes are saved, however in the debugging window they appear to be 0, false or null
Even putting a Debugging Watch does not show the correct values.
To see the real value how it is in the database you have to add a Watch and put the watch directly on the getters of the object. In my case I added a Watch and typed in "newItem.getContent()". With this line I got the title of my object. However just putting a Watch with "newItem" shows "null".
copyToRealm() and copyToRealmOrUpdate() returns the managed proxy as a return value of the function you're calling.
realm.copyToRealmOrUpdate(newItem);
realm.commitTransaction();
boolean test3= newItem.isManaged(); //returns false, and it should return false
Should be
newItem = realm.copyToRealmOrUpdate(newItem);
realm.commitTransaction();
boolean test3= newItem.isManaged(); //returns true

Android java loop through object list

My code connects to an Api, takes all Json values and stores them all in a object list resultClass. How I loop through the list and display all name properties of the objects?
This is the code I am using. The JSON values are sent with the method call as parameter with name object. Then loops and takes all objects and stores them in a list.
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
resultClass.setData_id(resultsObject
.getInt("data_id"));
resultClass.setName(resultsObject
.getString("name"));
resultClass.setRarity(resultsObject
.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject
.getString("img"));
resultClass.setType_id(resultsObject
.getInt("type_id"));
resultClass.setSub_type_id(resultsObject
.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.total; i++) {
Log.i("gw2Log", resultClass.name[i]);
}
}
This is the Json response i am logging
Json Response{"total":6,"last_page":1,"results":[{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/01D07FABAE26C0E5240892B00DA7AF90AB0EA022\/455828.png","rarity":7,"type_id":16,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":19648,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Gift of Twilight","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/CE3AF0B7B9BB6244726779F5B6A930541BA6C15F\/456031.png","rarity":5,"type_id":18,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":49191,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight","min_sale_unit_price":0,"restriction_level":80,"sub_type_id":6},{"sale_availability":23,"offer_availability":20643,"img":"https:\/\/render.guildwars2.com\/file\/CE3AF0B7B9BB6244726779F5B6A930541BA6C15F\/456031.png","rarity":7,"type_id":18,"sale_price_change_last_hour":0,"max_offer_unit_price":27500000,"data_id":30704,"price_last_changed":"2015-04-20 20:17:57 UTC","offer_price_change_last_hour":0,"name":"Twilight","min_sale_unit_price":31959998,"restriction_level":80,"sub_type_id":6},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/D04EF6FDE3DBC26E7BB109EB4F52057FEAD8619E\/699325.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65578,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Armor Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/666209104CCB024D53359C0EA0A299076E610771\/65704.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65577,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Token Loot Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/2626184EDDC254B4F7634A04F878062C6B2AF20D\/780372.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65579,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Weapons Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0}],"count":6,"page":1}
When digging around for a solution and checking the actual error it says it expects and array but a string is given Log.i("gw2Log", resultClass.name[i]);
When I loop through this Log call Log.i("gw2Log", resultClass.name); it displays the last objects name property the amount it loops.
EDIT:
On request to include my resultClass.java:
public class resultClass {
public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;
public int count;
public int page;
public int last_page;
public int total;
public int getData_id() {
return data_id;
}
public void setData_id(int data_id) {
this.data_id = data_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRarity() {
return rarity;
}
public void setRarity(int rarity) {
this.rarity = rarity;
}
public int getRestriction_level() {
return restriction_level;
}
public void setRestriction_level(int restriction_level) {
this.restriction_level = restriction_level;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getSub_type_id() {
return sub_type_id;
}
public void setSub_type_id(int sub_type_id) {
this.sub_type_id = sub_type_id;
}
public String getPrice_last_changed() {
return price_last_changed;
}
public void setPrice_last_changed(String price_last_changed) {
this.price_last_changed = price_last_changed;
}
public int getMax_offer_unit_price() {
return max_offer_unit_price;
}
public void setMax_offer_unit_price(int max_offer_unit_price) {
this.max_offer_unit_price = max_offer_unit_price;
}
public int getMin_sale_unit_price() {
return min_sale_unit_price;
}
public void setMin_sale_unit_price(int min_sale_unit_price) {
this.min_sale_unit_price = min_sale_unit_price;
}
public int getOffer_availability() {
return offer_availability;
}
public void setOffer_availability(int offer_availability) {
this.offer_availability = offer_availability;
}
public int getSale_availability() {
return sale_availability;
}
public void setSale_availability(int sale_availability) {
this.sale_availability = sale_availability;
}
public int getSale_price_change_last_hour() {
return sale_price_change_last_hour;
}
public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
this.sale_price_change_last_hour = sale_price_change_last_hour;
}
public int getOffer_price_change_last_hour() {
return offer_price_change_last_hour;
}
public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
this.offer_price_change_last_hour = offer_price_change_last_hour;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLast_page() {
return last_page;
}
public void setLast_page(int last_page) {
this.last_page = last_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
try something like this
first make a new object something like MyObject
public class MyObject {
public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;
public int getData_id() {
return data_id;
}
public void setData_id(int data_id) {
this.data_id = data_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRarity() {
return rarity;
}
public void setRarity(int rarity) {
this.rarity = rarity;
}
public int getRestriction_level() {
return restriction_level;
}
public void setRestriction_level(int restriction_level) {
this.restriction_level = restriction_level;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getSub_type_id() {
return sub_type_id;
}
public void setSub_type_id(int sub_type_id) {
this.sub_type_id = sub_type_id;
}
public String getPrice_last_changed() {
return price_last_changed;
}
public void setPrice_last_changed(String price_last_changed) {
this.price_last_changed = price_last_changed;
}
public int getMax_offer_unit_price() {
return max_offer_unit_price;
}
public void setMax_offer_unit_price(int max_offer_unit_price) {
this.max_offer_unit_price = max_offer_unit_price;
}
public int getMin_sale_unit_price() {
return min_sale_unit_price;
}
public void setMin_sale_unit_price(int min_sale_unit_price) {
this.min_sale_unit_price = min_sale_unit_price;
}
public int getOffer_availability() {
return offer_availability;
}
public void setOffer_availability(int offer_availability) {
this.offer_availability = offer_availability;
}
public int getSale_availability() {
return sale_availability;
}
public void setSale_availability(int sale_availability) {
this.sale_availability = sale_availability;
}
public int getSale_price_change_last_hour() {
return sale_price_change_last_hour;
}
public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
this.sale_price_change_last_hour = sale_price_change_last_hour;
}
public int getOffer_price_change_last_hour() {
return offer_price_change_last_hour;
}
public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
this.offer_price_change_last_hour = offer_price_change_last_hour;
}
}
then make your resultClass look like this
public class resultClass {
public int count;
public int page;
public int last_page;
public int total;
public ArrayList<MyObject> myObjects = new ArrayList();
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLast_page() {
return last_page;
}
public void setLast_page(int last_page) {
this.last_page = last_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public MyObject getObject(int pos){
return myObjects.get(pos);
}
public void addObject(MyObject object)
{
myObjects.add(object);
}
}
then your response should be something like this
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
MyObject temp = new MyObject();
temp.setData_id(resultsObject
.getInt("data_id"));
temp.setName(resultsObject
.getString("name"));
temp.setRarity(resultsObject
.getInt("rarity"));
temp.setRestriction_level(resultsObject
.getInt("restriction_level"));
temp.setImg(resultsObject
.getString("img"));
temp.setType_id(resultsObject
.getInt("type_id"));
temp.setSub_type_id(resultsObject
.getInt("sub_type_id"));
temp.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
temp.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
temp.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
temp.setOffer_availability(resultsObject
.getInt("offer_availability"));
temp.setSale_availability(resultsObject
.getInt("sale_availability"));
temp.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
temp.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClass.addObject(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.total; i++) {
Log.i("gw2Log", resultClass.getObject(i).name);
}
}
You could try this code. You wanted to use table of objects, but you created just single object. Create arrayList of your resultClass and then use simplier 'for' for your list
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
List<resultClass> resultClassList = new ArrayList<resultClass>();
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
resultClass.setData_id(resultsObject
.getInt("data_id"));
resultClass.setName(resultsObject
.getString("name"));
resultClass.setRarity(resultsObject
.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject
.getString("img"));
resultClass.setType_id(resultsObject
.getInt("type_id"));
resultClass.setSub_type_id(resultsObject
.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClassList.add(resultClass);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(resultClass result : resultClassList) {
Log.i("gw2Log", result.name);
}
}
Ok, I'm pretty sure of several things:
Tomer Shemesh is right, you are overriding your resultClass object on every iteration.
You wanna make arrays out of your normal variables in the resultClass so you can actually store more than one Item.
About that error you're getting:
It occurs in the lower for loop, where you want to log the names, right?
resultClass.nameis a String variable, it holds exactly one string of characters. You are trying to get a string out of an array by saying something like resultClass.name[i]. For that to work youu need to decrlare it as a string array, holding several string like public String[] name;, and in the constructor initialize it with a given capactiy like name = new String[cap];. Or you use an ArrayList<String> instead, which grows dynmically, but uses own getters and setters instead of the easy name[index] functions of an array.
Sorry, but I don't really want to write the right code here, as pretty much the whole thing needs to be rewritten, I hope this will help you rewrite it yourself though.

Translating basic Actionscript game code into Java?

I have been trying to translate this tutorial into Java code, as I want to make a simple game with level/achievements in android (and haven't found as thorough/basic examples in java online, if you have one please share)
Please help me understand:
How can I link different file of classes together? in the example they don't seem to refer to each other? Basically how can I pass on the properties and settings from the tasks/games to these functions which are elsewhere in the code? do I just refer to the class several times throughout the code?
For example I am stuck in this part, could use help in understanding how this works in java code? (examples are most appreciated)
> private var mProps :Object; // dictionary of properties
private var mAchievements :Object; // dictionary of achievements
public function Achieve() {
mProps = { };
mAchievements = { };
}
public function defineProperty(theName :String, theInitialValue :int, theaActivationMode :String, theValue :int) :void {
mProps[theName] = new Property(theName, theInitialValue, theaActivationMode, theValue);
}
public function defineAchievement(theName :String, theRelatedProps :Array) :void {
mAchievements[theName] = new Achievement(theName, theRelatedProps);
}
Remember that each class must go to its own file.
public class Property {
private String mName;
private int mValue;
private String mActivation;
private int mActivationValue;
private int mInitialValue;
public Property(String theName, int theInitialValue, String theActivation, int theActivationValue) {
mName = theName;
mActivation = theActivation;
mActivationValue = theActivationValue;
mInitialValue = theInitialValue;
}
public int getValue() {
return mValue;
}
public void setValue(int n) {
mValue = n;
}
public boolean isActive() {
boolean aRet = false;
switch(mActivation) {
case Achieve.ACTIVE_IF_GREATER_THAN: aRet = mValue > mActivationValue; break;
case Achieve.ACTIVE_IF_LESS_THAN: aRet = mValue < mActivationValue; break;
case Achieve.ACTIVE_IF_EQUALS_TO: aRet = mValue == mActivationValue; break;
}
return aRet;
}
public String getActivation() {
return mActivation;
}
}
import java.util.ArrayList;
public class Achievement {
private String mName; // achievement name
private ArrayList<String> mProps; // array of related properties
private boolean mUnlocked; // achievement is unlocked or not
public Achievement(String theId, ArrayList<String> theRelatedProps) {
mName = theId;
mProps = theRelatedProps;
mUnlocked = false;
}
public boolean isUnlocked() {
return mUnlocked;
}
public void setUnlocked(boolean b) {
mUnlocked = b;
}
public ArrayList<String> getProps() {
return mProps;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Achieve {
// activation rules
public static final String ACTIVE_IF_GREATER_THAN = ">";
public static final String ACTIVE_IF_LESS_THAN = "<";
public static final String ACTIVE_IF_EQUALS_TO = "==";
private HashMap<String,Property> mProps; // dictionary of properties
private HashMap<String,Achievement> mAchievements; // dictionary of achievements
public Achieve() {
mProps = new HashMap<String,Property>();
mAchievements = new HashMap<String,Achievement>();
}
public void defineProperty(String theName, int theInitialValue, String theaActivationMode, int theValue) {
mProps.put(theName, new Property(theName, theInitialValue, theaActivationMode, theValue));
}
public void defineAchievement(String theName, ArrayList<String> theRelatedProps) {
mAchievements.put(theName, new Achievement(theName, theRelatedProps));
}
public int getValue(String theProp) {
Property p = mProps.get(theProp);
if (p != null) return p.getValue();
return 0;
}
public void setValue(String theProp, int theValue) {
Property p = mProps.get(theProp);
if (p == null) return;
switch(p.getActivation()) {
case Achieve.ACTIVE_IF_GREATER_THAN:
theValue = theValue > p.getValue() ? theValue : p.getValue();
break;
case Achieve.ACTIVE_IF_LESS_THAN:
theValue = theValue < p.getValue() ? theValue : p.getValue();
break;
}
p.setValue(theValue);
}
public void addValue(ArrayList<String> theProps, int theValue) {
for (int i = 0; i < theProps.size(); i++) {
String aPropName = theProps.get(i);
setValue(aPropName, getValue(aPropName) + theValue);
}
}
public ArrayList<Achievement> checkAchievements() {
ArrayList<Achievement> aRet = new ArrayList<Achievement>();
Iterator<Map.Entry<String,Achievement>> it = mAchievements.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String,Achievement> pair = it.next();
Achievement aAchievement = pair.getValue();
if (!aAchievement.isUnlocked()) {
int aActiveProps = 0;
ArrayList<String> props = aAchievement.getProps();
for (int p = 0; p < props.size(); p++) {
Property aProp= mProps.get(props.get(p));
if (aProp.isActive()) {
aActiveProps++;
}
}
if (aActiveProps == props.size()) {
aAchievement.setUnlocked(true);
aRet.add(aAchievement);
}
}
}
return aRet;
}
}

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

how to solve parser error in my application?

I parsed my xml file successfully, but now I am getting null value. so what mistake I make in my coding I don't know. I want to display my string value in my screen. Now I am trying to display that string value in text view format, but I am getting null value......
my xml file:
<Mobiles>
<Mobile>
<Phone>Nokia 1108</Phone>
<Network>GSM 900/1800 MHz</Network>
<Size>106x46x20 mm</Size>
<Ringtones>mono</Ringtones>
<SMS>yes</SMS>
<MMS>no</MMS>
<Email>no</Email>
<InstantMessaging >no</InstantMessaging>
</Mobile>
<Mobile>
<Phone>Nokia 1109</Phone>
<Network>GSM 900/1800 MHz</Network>
<Size>106x46x20 mm</Size>
<Ringtones>mono</Ringtones>
<SMS>yes</SMS>
<MMS>no</MMS>
<Email>no</Email>
<InstantMessaging >no</InstantMessaging>
</Mobile>
<Mobile>
<Phone>Nokia 1110</Phone>
<Network>GSM 900/1800 MHz</Network>
<Size>106x46x20 mm</Size>
<Ringtones>mono</Ringtones>
<SMS>yes</SMS>
<MMS>no</MMS>
<Email>no</Email>
<InstantMessaging >no</InstantMessaging>
</Mobile>
<Mobile>
<Phone>Nokia 1111</Phone>
<Network>GSM 900/1800 MHz</Network>
<Size>106x46x20 mm</Size>
<Ringtones>mono</Ringtones>
<SMS>yes</SMS>
<MMS>no</MMS>
<Email>no</Email>
<InstantMessaging >no</InstantMessaging>
</Mobile>
</Mobiles>
output:
Just briefly glancing at your code I'd say that the issue is the state transitions on your in_Mobiles variable. It will always be true from the start of the document to the end.
In your characters(char[], int, int) method, the very first conditional branch will thus consume all characters:
if (this.in_Mobiles) {
myParsedExampleDataSet.setMobiles(new String(ch, start, length));
The same behavior repeats in the use of in_Mobile, which if you fix the first one, will be the next culprit.
Edit:
Well, overall your parser implementation is kind of wonky. Try something like this instead:
First off, your ParsedExampleDataSet is a bit off.
Turn it into a List of Mobile objects instead, like this:
public class ParsedExampleDataSet extends ArrayList<Mobile>{
}
Next, make a bean class named Mobile, like this:
class Mobile {
private String Phone;
private String Network;
private String Size;
private String Ringtones;
private boolean SMS;
private boolean MMS;
private boolean Email;
private boolean InstantMessaging;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getNetwork() {
return Network;
}
public void setNetwork(String network) {
Network = network;
}
public String getSize() {
return Size;
}
public void setSize(String size) {
Size = size;
}
public String getRingtones() {
return Ringtones;
}
public void setRingtones(String ringtones) {
Ringtones = ringtones;
}
public boolean isSMS() {
return SMS;
}
public void setSMS(boolean sMS) {
SMS = sMS;
}
public boolean isMMS() {
return MMS;
}
public void setMMS(boolean mMS) {
MMS = mMS;
}
public boolean isEmail() {
return Email;
}
public void setEmail(boolean email) {
Email = email;
}
public boolean isInstantMessaging() {
return InstantMessaging;
}
public void setInstantMessaging(boolean instantMessaging) {
InstantMessaging = instantMessaging;
}
}
Finally, your DefaultHandler subclass needs to be reworked. Something like this ought to work.
class ExampleHandler extends DefaultHandler {
private ParsedExampleDataSet Mobiles;
private Mobile CurrentMobile;
private StringBuilder Characters;
public ParsedExampleDataSet getParsedExampleDataSet() {
return Mobiles;
}
public void startDocument() throws SAXException {
Mobiles = new ParsedExampleDataSet();
}
public void startElement(String namespaceUri, String localName, String qName, Attributes atts)
throws SAXException {
String name = localName.equals("") ? qName : localName;
if ("Mobile".equals(name)) {
CurrentMobile = new Mobile();
}
// Empty accumulated characters
Characters = null;
}
public void characters(char[] ch, int offset, int length) throws SAXException {
if (Characters == null) {
Characters = new StringBuilder(length);
}
Characters.append(ch, offset, length);
}
public void endElement(String namespaceUri, String localName, String qName) throws SAXException {
String name = localName.equals("") ? qName : localName;
if ("Mobile".equals(name)) {
Mobiles.add(CurrentMobile);
CurrentMobile = null;
} else if (CurrentMobile != null && Characters != null){
String value = Characters.toString();
if ("Phone".equals(name)) {
CurrentMobile.setPhone(value);
} else if ("Network".equals(name)) {
CurrentMobile.setNetwork(value);
} else if ("Size".equals(name)) {
CurrentMobile.setSize(value);
} else if ("Ringtones".equals(name)) {
CurrentMobile.setRingtones(value);
} else {
boolean yes = "yes".equalsIgnoreCase(value.trim());
if ("SMS".equals(name)) {
CurrentMobile.setSMS(yes);
} else if ("MMS".equals(name)) {
CurrentMobile.setMMS(yes);
} else if ("Email".equals(name)) {
CurrentMobile.setEmail(yes);
} else if ("InstantMessaging".equals(name)) {
CurrentMobile.setInstantMessaging(yes);
}
}
}
}
}
And, just running it like this should produce a result:
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
ExampleHandler handler = new ExampleHandler();
InputSource is = new InputSource(/* your XML goes here as an inputstream or reader*/);
parser.parse(is, handler);
ParsedExampleDataSet mobiles = handler.getParsedExampleDataSet();
for (Mobile mobile : mobiles) {
System.out.println(mobile.getPhone());
}
why do you have true in endElement method?
if (localName.equals("Mobiles")) {
this.in_Mobiles = true;
this could leads to always override mobiles and not setting correct field.

Categories

Resources