Android - How to create a basic class and use it? - android

I have defined a class that contains properties of a specific answer object
The class look like this and is defined inside the class that is trying to use it
protected class Answer {
String QuestionId = "";
String AnswerValue = "";
String Correct = "";
public String getQuestionId() {
return QuestionId;
}
public void setQuestionId(String arg) {
QuestionId = arg;
}
public String getAnswerValue() {
return AnswerValue;
}
public void setAnswerValue(String arg) {
AnswerValue = arg;
}
public String getCorrect() {
return Correct;
}
public void setCorrect(String arg) {
Correct = arg;
}
}
Not sure if the above is OK
When I try to use the class I get null pointer errors
I'm using it like this
ArrayList<Answer> answerList = new ArrayList<Answer>();
for(int a=0;a<answers.getLength(); a++){
Element eAnswer = (Element) answers.item(a);
Answer anAnswer = new Answer;
NodeList answer_nodes = eAnswer.getChildNodes();
for (int ian=0; ian<answer_nodes.getLength(); ian++){
Node ans_attr = answer_nodes.item(ian);
String tag_name = ans_attr.getNodeName();
if(tag_name.equalsIgnoreCase("answer")){
anAnswer.setAnswerValue(ans_attr.getTextContent());
}
}
answerList.add(anAnswer);
}
Answer anAnswer = new Answer; gives a compilation error
All I'm trying to do is to create a list of answers which have a name value pair for a number of properties
Any guidance on this greatly appreciated - Especially if there is a better way

Answer anAnswer = new Answer();

Related

cannot find symbol type token in android studio?

private void loadFromAndToPlaceValues() {
String str = loadJSONFromAsset();
this.places = (List)new Gson().fromJson(str, newTypeToken<List<BusEntity>>().getType());
if (this.places != null && this.places.size() > 0) {
this.places_array = new String[this.places.size()];
for (int i = 0; i < this.places_array.length; i++) {
this.places_array[i] = ((BusEntity) this.places.get(i)).getValue();
}
}
}
You've missed {} braces. Change it like following.
this.places = (List)new Gson().fromJson(str, new TypeToken<List<BusEntity>>(){}.getType());
On a different note, question should be more constructive and descriptive. Posting plain code likely won't yield good answer most of the time.
It may help you :
Option 1 - implement java.lang.reflect.ParameterizedType yourself and pass it to Gson.
private static class ListParameterizedType implements ParameterizedType {
private Type type;
private ListParameterizedType(Type type) {
this.type = type;
}
#Override
public Type[] getActualTypeArguments() {
return new Type[] {type};
}
#Override
public Type getRawType() {
return ArrayList.class;
}
#Override
public Type getOwnerType() {
return null;
}
// implement equals method too! (as per javadoc)
}
Then simply:
Type type = new ListParameterizedType(clazz);
List<T> list = gson.fromJson(json, type);
This will work too, at least with Gson 2.2.4.
Type type = com.google.gson.internal.$Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, clazz);

Getting Nested JsonObjects & Arrays Using Retrofit Library

I got tired using this library, this is my first time using it and made a lot of success ways, but i'm a bit confused in getting the following Json :
{
"Guides":
{
"English": {"ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
,"Arabic": {"EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
}
}
Googled and saw a lot of guides and answered, and made my List like this :
public class PostItem {
List<PostItemArabic> Arabic;
List<PostItemEnglish> English;
}
class PostItemArabic{
private String ArabicSony;
private String ArabicNexus;
private String ArabicSamsung;
private String ArabicHTC;
public String getArabicSony() {
return ArabicSony;
}
public void setArabicSony(String arabicSony) {
ArabicSony = arabicSony;
}
public String getArabicNexus() {
return ArabicNexus;
}
public void setArabicNexus(String arabicNexus) {
ArabicNexus = arabicNexus;
}
public String getArabicSamsung() {
return ArabicSamsung;
}
public void setArabicSamsung(String arabicSamsung) {
ArabicSamsung = arabicSamsung;
}
public String getArabicHTC() {
return ArabicHTC;
}
public void setArabicHTC(String arabicHTC) {
ArabicHTC = arabicHTC;
}
}
class PostItemEnglish{
private String EnglishSony;
private String EnglishNexus;
private String EnglishSamsung;
private String EnglishHTC;
public String getEnglishSony() {
return EnglishSony;
}
public void setEnglishSony(String englishSony) {
EnglishSony = englishSony;
}
public String getEnglishNexus() {
return EnglishNexus;
}
public void setEnglishNexus(String englishNexus) {
EnglishNexus = englishNexus;
}
public String getEnglishSamsung() {
return EnglishSamsung;
}
public void setEnglishSamsung(String englishSamsung) {
EnglishSamsung = englishSamsung;
}
public String getEnglishHTC() {
return EnglishHTC;
}
public void setEnglishHTC(String englishHTC) {
EnglishHTC = englishHTC;
}
}
My Model :
private class Model {
private List<PostItem> Guides;
public List<PostItem> getGuides() {
return Guides;
}
public void setGuides(List<PostItem> roms_center) {
this.Guides = roms_center;
}
}
And printing the result like this :
List<PostItem> Guides = response.body().getGuides();
for(int i = 0 ; i < Guides.size() ; i ++ ) {
for (int b = 0; b < Guides.get(i).English.size() ; b++){
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishHTC());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishNexus());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSamsung());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSony());
}
for (int b = 0; b < Guides.get(i).Arabic.size() ; b++){
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicHTC());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicNexus());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSamsung());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSony());
}
}
My work isn't correct, and getting a lot of errors,
Here's the last error i got :
`Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 3 column 18 path $.Guides
What's the way to make it correct ? `
Based on your models when you try to get the guides list your telling retrofit to populate an array. Retrofit is then getting the data and finding that it is a single object and not array. So you need to update your model to reflect the data returned. For example:
class PostItem {
List<Language> mLanguages;
}
class Language{
String mLanguageTitle; //for example english
List<String> mData; //for this is your list of data
}
Then in your activity instead of getting guides you would get just a post item for example:
response.body().getPostItem();
Hope it helps !
First of all, you can use the retrofit Gson library.
You can handle this in two ways:
Option 1: reformat your languages in your json to be an array like Doug says.
{
"Guides":
[
{"Lang":"English","ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
, {"Lang":"Arabic","EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
]
}
Then you will need to redesign your class to reflect this structure.
Like Doug sayd:
class PostItem {
List<Language> mLanguages;
}
Option 2: Create a custom json desirializer in your class. this will take the Json and break it down into whatever structure you want it to be.
public class PostItem implements JsonDeserializer
#Override
public MyDesirializer deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jarabic = (JsonObject) json.get("Arabic");
//whatever manipulations you want to do (fill with your own code)
PostItem item = new PostItem();
item.arabic = jarabic;
...
...
return item;
}

Android AWS DynamoDB "No hash key condition"

I have a DynamoDB table that has some data. There is a hashkey of "class_id" and a rangekey of "message_timestamp".
In my android code I am attempting to query for messages that are newer than the last message received.
int lastMessageTimestamp = GetNewestTimestamp();
DynamoChatData messagesToFind = new DynamoChatData();
Log.i(TAG,String.valueOf(class_id));
messagesToFind.SetClassId(class_id); // Set to 2 in the debugger at runtime
Condition rangeKeyCondition = new Condition();
rangeKeyCondition.withComparisonOperator(ComparisonOperator.GT.toString());
AttributeValue attributeValue = new AttributeValue();
attributeValue.withN(String.valueOf(lastMessageTimestamp));
rangeKeyCondition.withAttributeValueList(attributeValue);
DynamoDBQueryExpression<DynamoChatData> query = new DynamoDBQueryExpression<>();
query.withHashKeyValues(messagesToFind);
query.withRangeKeyCondition("message_timestamp", rangeKeyCondition);
query.withConsistentRead(false);
PaginatedQueryList result = objectMapper.query(DynamoChatData.class, query);
The DynamoChatData class:
#DynamoDBTable(tableName = "scriyb_chat")
public class DynamoChatData {
private int class_id;
private int message_timestamp;
private String user_name;
private String user_full_name;
private String message_content;
private int message_visible;
private int message_underage;
#DynamoDBRangeKey(attributeName = "message_timestamp")
public int GetMessageTimestamp(){
return message_timestamp;
}
public void SetMessageTimestamp(int _message_timestamp){
message_timestamp = _message_timestamp;
}
#DynamoDBHashKey(attributeName = "class_id")
public int GetClassId(){
return class_id;
}
public void SetClassId(int _class_id){
class_id = _class_id;
}
#DynamoDBAttribute(attributeName = "user_name")
public String GetUsername(){
return user_name;
}
public void SetUsername(String _user_name){
user_name = _user_name;
}
#DynamoDBAttribute(attributeName = "user_full_name")
public String GetUserFullName(){
return user_full_name;
}
public void SetUserFullName(String _user_full_name){
user_full_name = _user_full_name;
}
#DynamoDBAttribute(attributeName = "message_content")
public String GetMessageContent(){
return message_content;
}
public void SetMessageContent(String _message_content){
message_content = _message_content;
}
#DynamoDBAttribute(attributeName = "message_visible")
public int GetMessageVisible(){
return message_visible;
}
public void SetMessageVisible(int _message_visible){
message_visible = _message_visible;
}
#DynamoDBAttribute(attributeName = "message_underage")
public int GetMessageUnderage(){
return message_underage;
}
public void SetMessageUnderage(int _message_underage){
message_underage = _message_underage;
}
}
I followed the basic example outlined here and have read a bunch of posts on this site as well. Not sure why I get the
java.lang.IllegalArgumentException: Illegal query expression: No hash key condition is found in the query
error.
Any insight is appreciated.
Try using refactoring your getter/setter names so that they start with a lowercase letter as is standard Java convention. I believe the mapper looks for getters as methods that start with "get" and I think it's missing yours since they start with a capitol G.
Let me know if this resolves your problem!
Weston

When passing 2 identical Parcable Classes, 1 is null

i have a weird issue.
I'm trying to pass 2 parcable classesfrom one activity to another.
I define both of them the exact same way, but of them is null.
The parcable class :
class Friends implements Parcelable {
private ArrayList<Integer> ids = new ArrayList<Integer>();
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<Bitmap> images = new ArrayList<Bitmap>();
public void addId(Integer id)
{
ids.add(id);
}
public void addName(String name){
names.add(name);
}
public void addImage(Bitmap img){
images.add(img);
}
public ArrayList<Integer> getIds() {
return ids;
}
public ArrayList<String> getNames() {
return names;
}
public ArrayList<Bitmap> getImages() {
return images;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(ids);
dest.writeList(names);
dest.writeList(images);
}
public static final Parcelable.Creator<Friends> CREATOR = new Parcelable.Creator<Friends>() {
public Friends createFromParcel(Parcel in) {
return new Friends(in);
}
public Friends[] newArray(int size) {
return new Friends[size];
}
};
public Friends(Parcel in){
in.readList(ids, null);
in.readList(names, null);
in.readList(images, null);
}
public Friends(Integer id, String name, Bitmap img) {
ids.add(id);
names.add(name);
images.add(img);
}
public Friends(){
}
The Sending part :
for(Integer position : selectedIds)
{
String name = a.getItem(position).getFriendName();
int id = a.getItem(position).getFriendId();
Bitmap img = a.getItem(position).getFriendImage();
Log.e("ID",String.valueOf(id));
selectedFriends.addId(new Integer(id));
selectedFriends.addName(name);
selectedFriends.addImage(img);
}
for(int position=0;position<list.getCount(); position++)
{
String name = a.getItem(position).getFriendName();
int id = a.getItem(position).getFriendId();
Bitmap img = a.getItem(position).getFriendImage();
Log.e("All IDs",String.valueOf(id));
allFriends.addId(new Integer(id));
allFriends.addName(name);
allFriends.addImage(img);
}
b.putParcelable("selecet_friends", selectedFriends);
b.putParcelable("all_friends", allFriends);
data.putExtras(b);
Both of the loops are being runned ( i can see the logs), all variables you don't see are being initialized correctly, everything is fine.
The Reciving part :
i define both as null :
private Friends selectedFriends = null;
private Friends allFriends = null;
And handle the onResult like this :
Log.e("Result","yessss");
Friends all_friends = (Friends)data.getParcelableExtra("all_friends");
Friends selected_friends = (Friends)data.getParcelableExtra("selected_friends");
allFriends = all_friends;
selectedFriends = selected_friends;
if(selectedFriends != null){
Log.e("is null","No");
}
if(allFriends != null){
Log.e("is all null","No");
}
Does anyone know how come the selectedFriends is null when allFriends is not?
EDIT:
Just a thought, but maybe it's because i put 2 parcables on a Bundle?
just i just add 2 bundles?
In the sending method you have a typo in this line:
b.putParcelable("selecet_friends", selectedFriends);
try this instead:
b.putParcelable("selected_friends", selectedFriends);
Also, you should use more specific names for the keys. The documentation for putExtras() says:
Add a set of extended data to the intent. The keys must include a
package prefix, for example the app com.android.contacts would use
names like "com.android.contacts.ShowAll

Information on setters and getters

I am learning extensively about getters and setters but I seem not to be having my way.
I have a class called Apps_Info which contains my setters and getters and I have my main activity FavouriteApps that has a list which uses the class Apps_Info.
I am trying to get the name of the package from the List in FavouriteApps but I am still getting null.
Please can someone tell what to do? Below is the code in this order: class Apps_Info and FavouriteApps activity
public class Apps_Info {
private Bitmap bIcon;
private String sName;
private String sPacks_Name;
public Apps_Info(Bitmap icon, String name, String Packs_Name) {
bIcon = icon;
sName = name;
sPacks_Name = Packs_Name;
}
public void setIcon(Bitmap icon) {
bIcon=icon;
}
public Bitmap getIcon() {
return bIcon;
}
public void setName(String name) {
sName=name;
}
public String getName() {
return sName;
}
public void setPacks_Name(String Packs_Name) {
this.sPacks_Name=Packs_Name;
}
public String getPacks_Name() {
return sPacks_Name;
}
}
FavouriteApps Activity code (part)
String packname, packsname, apps_names;
Bitmap app_icon;
Resources res = getResources();
List<Apps_Info> ListApps_Info = new ArrayList<Apps_Info>();
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.browser_app), "Browser", "com.browser"));
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.clock_app), "Alarm Clock", "com.alarm.clock"));
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.threegplus), "3G Secure Connection", "threeg.secureconnect"));
mGridView.setAdapter(new Apps_Info_Adapter(this, ListApps_Info));
Apps_Info packinfo = new Apps_Info(app_icon, apps_names, packname);
packsname = packinfo.getPacks_Name();
apps_names = packinfo.getName();
Log.i("The Pack_Name is " + packsname, "Pack Name");
You should do like this.
for (int i = 0; i < ListApps_Info.size(); i++) {
Apps_Info packinfo = ListApps_Info.item(i);
packsname = packinfo.getPacks_Name();
apps_names = packinfo.getName();
Log.i("The Pack_Name is " + packsname, "Pack Name");
}
It's because you never initialize the packname variable in your code.
String packname,packsname,apps_names;
When you do this :
Apps_Info packinfo=new Apps_Info(app_icon, apps_names,packname);
packsname=packinfo.getPacks_Name();
your getter is doing well and this is normal if it returns null.

Categories

Resources