1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
// Загрузка дополнительных данных с сервера по API для форм - (void)loadAdditionalInformationFromServer { loadingError = nil; success = YES; group = dispatch_group_create(); [self startOfferEducationsRetrieveOperation]; [self startOfferLanguageLevelsRetrieveOperation]; [self startOfferTradesRetrieveOperation]; [self startOfferLanguagesRetrieveOperation]; [self startOperatingScheduleRetrieveOperation]; [self startRegionsRetrieveOperation]; dispatch_group_notify(group, dispatch_get_main_queue(), ^{ [self.delegate resumeManagerDidFinishLoadingAdditionalInformationWithSuccess:success error:loadingError]; }); //dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); } // Запрос на получение уровней образования - (void)startOfferEducationsRetrieveOperation { if ([[RRSession sharedSession] offerEducations] == nil) { // Блок успешного завершения запроса SuccessBlock successBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSArray *jsonArray = (NSArray *)JSON; NSMutableArray *temp = [NSMutableArray new]; for (NSDictionary *jsonDic in jsonArray) { RROfferEducation *obj = [[RROfferEducation alloc] initFromDic:jsonDic]; [temp addObject:obj]; } [[RRSession sharedSession] setOfferEducations:temp]; dispatch_group_leave(group); }; // Добавление запроса на загрузку в очередь [self addOperationForMethod:RRApiMethodOfferEducations successBlock:successBlock]; } } // Запрос на получение уровней владения языком - (void)startOfferLanguageLevelsRetrieveOperation { if ([[RRSession sharedSession] offerLanguageLevels] == nil) { // Блок успешного завершения запроса SuccessBlock successBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSArray *jsonArray = (NSArray *)JSON; NSMutableArray *temp = [NSMutableArray new]; for (NSDictionary *jsonDic in jsonArray) { RROfferLanguageLevel *obj = [[RROfferLanguageLevel alloc] initFromDic:jsonDic]; [temp addObject:obj]; } [[RRSession sharedSession] setOfferLanguageLevels:temp]; dispatch_group_leave(group); }; // Добавление запроса на загрузку в очередь [self addOperationForMethod:RRApiMethodOfferLanguageLevels successBlock:successBlock]; } } // Запрос на получение языков - (void)startOfferLanguagesRetrieveOperation { if ([[RRSession sharedSession] offerLanguages] == nil) { // Блок успешного завершения запроса SuccessBlock successBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSArray *jsonArray = (NSArray *)JSON; NSMutableArray *temp = [NSMutableArray new]; for (NSDictionary *jsonDic in jsonArray) { RROfferLanguage *obj = [[RROfferLanguage alloc] initFromDic:jsonDic]; [temp addObject:obj]; } [[RRSession sharedSession] setOfferLanguages:temp]; dispatch_group_leave(group); }; // Добавление запроса на загрузку в очередь [self addOperationForMethod:RRApiMethodOfferLanguages successBlock:successBlock]; } } // Запрос на получение графиков работы - (void)startOperatingScheduleRetrieveOperation { if ([[RRSession sharedSession] operatingSchedules] == nil) { // Блок успешного завершения запроса SuccessBlock successBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSArray *jsonArray = (NSArray *)JSON; NSMutableArray *temp = [NSMutableArray new]; for (NSDictionary *jsonDic in jsonArray) { RROperatingSchedule *obj = [[RROperatingSchedule alloc] initFromDic:jsonDic]; [temp addObject:obj]; } [[RRSession sharedSession] setOperatingSchedules:temp]; dispatch_group_leave(group); }; // Добавление запроса на загрузку в очередь [self addOperationForMethod:RRApiMethodOperatingSchedules successBlock:successBlock]; } } // Запрос на получение регионов - (void)startRegionsRetrieveOperation { if ([[RRSession sharedSession] regions] == nil) { // Блок успешного завершения запроса SuccessBlock successBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSArray *jsonArray = (NSArray *)JSON; NSMutableArray *temp = [NSMutableArray new]; for (NSDictionary *jsonDic in jsonArray) { RRRegion *obj = [[RRRegion alloc] initFromDic:jsonDic]; [temp addObject:obj]; } [[RRSession sharedSession] setRegions:temp]; dispatch_group_leave(group); }; // Добавление запроса на загрузку в очередь [self addOperationForMethod:RRApiMethodRegions successBlock:successBlock]; } } // Запрос на получение рубрик вакансий - (void)startOfferTradesRetrieveOperation { if ([[RRSession sharedSession] offerTrades] == nil) { // Блок успешного завершения запроса SuccessBlock successBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSArray *jsonArray = (NSArray *)JSON; NSMutableArray *temp = [NSMutableArray new]; for (NSDictionary *jsonDic in jsonArray) { RROfferTrade *obj = [[RROfferTrade alloc] initFromDic:jsonDic]; [temp addObject:obj]; } [[RRSession sharedSession] setOfferTrades:temp]; dispatch_group_leave(group); }; // Добавление запроса на загрузку в очередь [self addOperationForMethod:RRApiMethodOfferTrades successBlock:successBlock]; } } // Добавление запроса на загрузку в очередь - (void)addOperationForMethod:(NSString *)methodName successBlock:(SuccessBlock)successBlock { dispatch_group_enter(group); RRHTTPClient *client = [RRHTTPClient sharedClient]; NSString *apiMethodPath = [NSString stringWithFormat:@"%@%@", [RRHelper apiDomain], methodName]; NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:apiMethodPath parameters:nil]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:successBlock failure:[self getStandartFailureBlock]]; [operation start]; //[[RRServerConnection sharedConnection] addCustomOperation:operation]; } // Блок обработки ошибки при запросе - (FailureBlock)getStandartFailureBlock { FailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { success = NO; loadingError = error; NSLog(@"Error: %@", error); [RRHelper showServerErrorMessage]; dispatch_group_leave(group); }; return failureBlock; } |
Monthly Archives: October 2014
Android Java Serialization Using Generics
I have created a class – SerializationManager, it can serialize any objects and write them to files. It can be used to save and restore form states in Android. It is based on Java Generics. What is achieved by this is that you do not need to duplicate serialization code in every class.
Object must implement Serialized interface. Here form is an object instance of a class. It can be named as just obj.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.alwawee.util; import android.content.Context; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializationManager<T> { //================================================================================ // Constructor //================================================================================ public SerializationManager(){ } //================================================================================ // Other //================================================================================ // Reads saved object from a file. Object must implement Serialized interface. public T readObjectFromFile(Context context, String className) { T form = null; try { String fileName = className + ".ser"; FileInputStream fileInputStream = context.openFileInput(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); form = (T) objectInputStream.readObject(); objectInputStream.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return form; } // Serializes object and saves it to a file. File name is created using object type (class name). public void saveObjectToFile(Context context, T form) { try { String fileName = form.getClass().getSimpleName() + ".ser"; FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(form); objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } |
This is how you can use it. First you declare a SerializationManager in your class and you tell it which class you are going to serialize:
1 |
private SerializationManager<CreateResumeForm> manager; |
Then in onCreate method you create SerializationManager instance:
1 2 3 |
@Override protected void onCreate(Bundle savedInstanceState) { manager = new SerializationManager<CreateResumeForm>(); |
Writing object to a file:
1 2 |
// Saving to a file manager.saveObjectToFile(this, form); |
Reading objects from saved file:
1 2 |
// Reading form object from a file form = manager.readObjectFromFile(this, "CreateResumeForm"); |
Tips discovered while using Android spinners : setting selected item and finding objects in arrays in Java
To set a selected item programmatically in Android Spinner, you should use setSelection method.
To get an index of an item to select from an array of strings using IndexOf, you should first use java.util.Arrays.asList method.
Complete code:
1 2 |
int genderIndex = java.util.Arrays.asList(R.array.genders).indexOf(form.gender); genderSpinner.setSelection(genderIndex); |
Serialize an object, save it to a file and read it from a file in Android
Android interface Serializable is not sufficient to save your objects to the file, it only creates streams.
This is a complete code with error handling and handling closes of streams. Add it to your class that you want to be able to serialize and deserialize.
In my case the class name is CreateResumeForm. You should change it to your own class name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Constant with a file name public static String fileName = "createResumeForm.ser"; // Serializes an object and saves it to a file public void saveToFile(Context context) { try { FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(this); objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } // Creates an object by reading it from a file public static CreateResumeForm readFromFile(Context context) { CreateResumeForm createResumeForm = null; try { FileInputStream fileInputStream = context.openFileInput(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); createResumeForm = (CreateResumeForm) objectInputStream.readObject(); objectInputStream.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return createResumeForm; } |
Use it like this in your Activity:
1 |
form = CreateResumeForm.readFromFile(this); |
Sorting objects in Objective-C in Alphabet Order by Name
It is a very easy but a common task. There is no need to create any custom NSSortDescriptors. Let’s say, we have an unsorted array of RRRegion objects, that have a name property. This is how we can sort this array:
1 2 3 4 |
NSArray *regionArray = [[RRSession sharedSession] regions]; // Sorting in alphabet order by name NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; regionArray = [regionArray sortedArrayUsingDescriptors:@[sortDescriptor]]; |