Cannot set property of object in Kotlin using var - android

I am trying to set the property of an object I've created in Android Studio using Kotlin. I am using a for loop to make a new object each time and add it to an array. When I initialize my object and try to set the topId it says "Val cannot reassigned" even though I'm declaring it a var.
for (i in 1..5) {
var topRanNum = generateRandomNum(topSize)
var top = currentSeasonTops[topRanNum]
var topLoopCounter = 0
var topId = top.id
var newOutfit: Outfit = Outfit()
if(top.wornCount < 5 ) {
newOutfit.topId = top.id
}
}
Outfit Class
public Outfit() {}
public Outfit(Long topId, Long bottomId, String topPhotoPath, String bottomPhotoPath) {
this.topId = topId;
this.bottomId = bottomId;
this.topPhotoPath = topPhotoPath;
this.bottomPhotoPath = bottomPhotoPath;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTopPhotoPath() {
return topPhotoPath;
}
public String getBottomPhotoPath() {
return bottomPhotoPath;
}
public Long getTopId() {
return topId;
}
public Long getBottomId() {
return bottomId;
}

This happens because you need to declare an accessible setter from outside in Java for topId or make the variable accessible from outside.
E.g.
public void setTopId(Long topId) {
this.topId = topId;
}

Related

Display the ArrayList values into TextVitew

Am working on one android project. i stored the getting response in the ArrayList while parsing from the JsonArray. now i want just display the values to required text views.
Here am doing.
public void updateRedemptionRequestDetails(){
//Dismiss dialog
dlgProgress.dismiss();
// Get the status
String status=redemptionRequestDetailsResponse.getStatus();
if(status.equals("success")){
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = redemptionRequestDetailsResponse.getData();
if(!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0 ){
redemptionRequestDetailsResources.addAll(redemptionRequestDetailsResource);
populateRedemptionDetails(redemptionRequestDetailsResources);
}
}else if ( status.equals("failed")) {
//Show toast based on error code
generalMethods.showToastMessage(context,redemptionRequestDetailsResponse.getErrorcode());
}
}
Can anyone please shed some lights on this.how can i get the values in specified string and display them.
Here my model class
public class RedemptionRequestDetailsResource {
private String rdmId;
private String rdmUniqueBatchTrackingId;
private String rdmLoyaltyId;
private String rdmStatus;
private String rdmCashPaymentStatus;
private String rdmProductCode;
public String getRdmId() {
return rdmId;
}
public void setRdmId(String rdmId) {
this.rdmId = rdmId;
}
public String getRdmUniqueBatchTrackingId() {
return rdmUniqueBatchTrackingId;
}
public void setRdmUniqueBatchTrackingId(String rdmUniqueBatchTrackingId) {
this.rdmUniqueBatchTrackingId = rdmUniqueBatchTrackingId;
}
public String getRdmLoyaltyId() {
return rdmLoyaltyId;
}
public void setRdmLoyaltyId(String rdmLoyaltyId) {
this.rdmLoyaltyId = rdmLoyaltyId;
}
public String getRdmStatus() {
return rdmStatus;
}
public void setRdmStatus(String rdmStatus) {
this.rdmStatus = rdmStatus;
}
public String getRdmCashPaymentStatus() {
return rdmCashPaymentStatus;
}
public void setRdmCashPaymentStatus(String rdmCashPaymentStatus) {
this.rdmCashPaymentStatus = rdmCashPaymentStatus;
}
public String getRdmProductCode() {
return rdmProductCode;
}
public void setRdmProductCode(String rdmProductCode) {
this.rdmProductCode = rdmProductCode;
}
}
here my populateRedemptionDetails method
public void populateRedemptionDetails(List<RedemptionRequestDetailsResource> requestDetailsResource) {
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = requestDetailsResource;
TextView txtLoyaltyId = (TextView)rootView.findViewById(R.id.txtLoyaltyId);
txtLoyaltyId.setText(redemptionRequestDetailsResource.getRdmLoylatyId());
}
i tried like this but it throwing error.
The if condition is wrong, it will never enter:
if (!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0) {
}
it should be:
if (!redemptionRequestDetailsResource.isEmpty()) {}
also, small tip, when using equals, you should put the constant on the left side of the call, like this:
"success".equals(status)
this is to prevent NullPointerExceptions

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

NullReferenceException in MvvmCross Messenger

This is code in my ViewModel
public ICommand GoToCartCommand{
get{
return new MvxCommand (() => {
var cartViewModel = Mvx.Resolve<CartViewModel>();
if (cartViewModel != null)
{
cartViewModel.cartlist.Add(new CartItemViewModel() { Name = Name, ID = ID, UnitPrice = double.Parse(Price), Quantity = 1, Description = Description, Image = Image });
}
cartListCount = cartViewModel.cartlist.Count;
var messanger = Mvx.Resolve<IMvxMessenger>();
var message = new MyMessage(this,"Product has been added",cartListCount);
messanger.Publish(message);
});
}
}
public class MyMessage : MvxMessage
{
public int CartList_Count{ get; set;}
public string Message{ get; set;}
public MyMessage(object sender,string _message,int _cartlist_count) : base(sender) {
this.Message = _message;
this.CartList_Count = _cartlist_count;
}
}
This is code in my View :
var messenger = Mvx.Resolve<IMvxMessenger>();
_token = messenger.Subscribe<MyMessage>(OnInputIsNeeded,MvxReference.Strong);
private void OnInputIsNeeded(MyMessage _Message)
{
Toast.MakeText (this.Activity,_Message.Message, ToastLength.Short).Show();
}
My problem here is when I comeback to this view after going to next view OnInputisNeeded the method is called two times.
And when go back from this view and when I again come to this view and click button I get a NullReferenceException.
What is the solution?
What is the meaning of this:
Nothing registered for messages of type MvxSubscriberChangeMessage
How do i register MvxSubscriberChangeMessage?

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

ORMLite many to many relation Android

I have two classes :
UniteStratigraphique.java :
#DatabaseTable(tableName = "unitestratigraphique")
public class UniteStratigraphique {
public final static String ID_FIELD_NAME = "id";
#DatabaseField(generatedId = true, columnName = ID_FIELD_NAME)
private int id;
// CAMPAGNES
#DatabaseField(foreign = true, foreignAutoRefresh = true)
private Campagne campagne;
#ForeignCollectionField
private ForeignCollection<Campagne> listeCampagnes;
public UniteStratigraphique() {}
public Campagne getCampagne() {
return campagne;
}
public void setCampagne(Campagne campagne) {
this.campagne = campagne;
}
public ArrayList<Campagne> getListeCampagnes() {
ArrayList<Campagne> campagnesArray = new ArrayList<Campagne>();
for (Campagne campagne : listeCampagnes) {
campagnesArray.add(campagne);
}
return campagnesArray;
}
public ForeignCollection<Campagne> getListeCampagnesForeign() {
return listeCampagnes;
}
public void setListeCampagnes(ForeignCollection<Campagne> listeCampagnes) {
this.listeCampagnes = listeCampagnes;
}
}
Campagne.java :
#DatabaseTable(tableName = "campagne")
public class Campagne {
#DatabaseField(generatedId = true)
private int id;
// UNITE STRATIGRAPHIQUE
#ForeignCollectionField
private ForeignCollection<UniteStratigraphique> listeUniteStratigraphique;
#DatabaseField(foreign = true, foreignAutoRefresh = true)
private UniteStratigraphique uniteStratigraphique;
public Campagne() {}
public ArrayList<UniteStratigraphique> getListeUniteStratigraphique() {
ArrayList<UniteStratigraphique> usArray = new ArrayList<UniteStratigraphique>();
for (UniteStratigraphique us : listeUniteStratigraphique){
usArray.add(us);
}
return usArray;
}
public ForeignCollection<UniteStratigraphique> getListeUniteStratigraphiqueForeign() {
return listeUniteStratigraphique;
}
public void setListeUniteStratigraphique(
ForeignCollection<UniteStratigraphique> listeUniteStratigraphique) {
this.listeUniteStratigraphique = listeUniteStratigraphique;
}
public int getSizeListeUniteStratigraphique() {
return listeUniteStratigraphique.size();
}
public UniteStratigraphique getUniteStratigraphique() {
return uniteStratigraphique;
}
public void setUniteStratigraphique(UniteStratigraphique uniteStratigraphique) {
this.uniteStratigraphique = uniteStratigraphique;
}
}
As you can see, these are Many-To-Many linked (0...n---0...n, with ORMLite annotations).
Now, my workflow is :
I create multiple "UniteStratigraphique" classes and I store them into my database (this works fine).
=> So I have n * "UniteStratigraphique" stored.
After that what I want is to create a "Campagne" class wich will contain multiple "UniteStratigraphique" classes.
=> So I want to set this field from "Campagne.java" :
#ForeignCollectionField
private ForeignCollection<UniteStratigraphique> listeUniteStratigraphique;
with the n * "UniteStratigraphique" elements I just stored before.
I tried to do this with this DAO method but it only duplicate the "UniteStratigraphique" classes into my db and no link is made..
public void addUsToCampagne(Campagne campagne,
ArrayList<UniteStratigraphique> usArray) {
ForeignCollection<UniteStratigraphique> usForeign = campagne
.getListeUniteStratigraphiqueForeign();
if (usForeign == null) {
try {
usForeign = getHelper().getCampagneDao()
.getEmptyForeignCollection("listeUniteStratigraphique");
for (UniteStratigraphique us : usArray) {
usForeign.add(us);
}
} catch (SQLException e) {
e.printStackTrace();
}
}else{
for (UniteStratigraphique us : usArray) {
usForeign.add(us);
}
}
}
And in my Activity I'm doing this :
db.addCampagne(campagne);
if( myUniteStratigraphiqueArray.size() > 0){
db.addUsToCampagne(campagne, myUniteStratigraphiqueArray);
}
Many to Many relations are non automatic with ORMLite, the only way to achieve it is to make a 3rd Table only for link beetween these 2 classes..
This link refers to this problem : What is the best way to implement many-to-many relationships using ORMLite?
And the example here : https://github.com/j256/ormlite-jdbc/tree/master/src/test/java/com/j256/ormlite/examples/manytomany
Hope it helped.

Categories

Resources