Create ordered Arrays with JSONObject - java

Let me explain my problem.
(I'm new to java so maybe this type of thing might be easy but I can't figure it out !)
I have a JSONObject which looks like :
{
notes:[
{
"scolaryear":2013,
"codemodule":"B-CPE-042",
"titlemodule":"B1 - Unix & C Lab Seminar",
"codeinstance":"NCE-1-1",
"codeacti":"acti-134315",
"title":"Piscine Jour 1",
"date":"2013-10-04 13:33:51",
"correcteur":"ramassage-tek",
"final_note":0,
"comment":"Ex_00 -> output differs"
},
{} // And so on ..
]
}
For now I can get all the data doing something like :
try {
// Pulling items from the array
JSONArray notesArr = jsonObject.getJSONArray("notes");
try {
ListView lv = (ListView) _modulesActivity.findViewById(R.id.listView);
List < String > notesList = new ArrayList < String > ();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
String code_module = tmp.getString("codemodule");
String module = tmp.getString("titlemodule");
String title = tmp.getString("title");
String final_note = tmp.getString("final_note");
String year = tmp.getString("scolaryear");
String comment = tmp.getString("comment");
String display = year + " | " + title + " | " + final_note;
notesList.add(display);
}
ArrayAdapter < String > arrayAdapter = new ArrayAdapter < String > (
_mainContext, android.R.layout.simple_list_item_1, notesList);
lv.setAdapter(arrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
So with that technique I got all my data in one array and an only listView which looks like :
2014 | PROJECT #1 | 13/20
2015 | PROJECT #2 | 20/20
But I need to order my data with year, and module.
It would look like :
> YEAR (year)
> TITLE OF MODULE (module) - MODULE CODE (codemodule)
> PROJECT NAME (title) | MARK (final_note)
- COMMENT (comment)
You have a first header with the year, when you click on a year, you can see all the module :
> MODULE #1
> MODULE #2
...
And when you click on a module you can see all project :
> PROJECT #1 | MARK : 20
> PROJECT #2 | MARK : 13
...
And finally when you click on a project you can see the comment !
^ PROJECT #1 | MARK : 20
- Great project .. bla bla bla
(or maybe display a popup window which contains the comments if it's possible)
I know it may be a complexe thing but I really want to achieve that !
Thanks in advance for your help !

In my opinion you have two possibilities:
Implement a Note Java object, during the form initialize this objects and put them in an ArrayList. In the end sort it with some algorithm.
For example it would look like:
List<Note> notesList = new ArrayList<Note>();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
noteListe.add(new Note(tmp.getString("codemodule"), tmp.getString("titlemodule"),...);
}
Now sort it with a proper method and in the end print it maybe overriding toString() Note method.
If possible sort the JsonObjectArray when you create it.
Hope it can help you

So I found a solution !
I used this library : https://github.com/bmelnychuk/AndroidTreeView
Here is my Code :
try {
// Pulling items from the array
TreeNode root = TreeNode.root();
TreeNode child;
String year = "YEAR";
String moduleName = "";
YearHolder.IconTreeItem nodeItem = new YearHolder.IconTreeItem(1, year);
ModuleHolder.IconTreeItem nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
TreeNode parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
TreeNode parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
JSONArray modArr = jsonObject.getJSONArray("notes");
try {
for (int i = 0; i < modArr.length(); i++) {
JSONObject tmp = modArr.getJSONObject(i);
/*String title = tmp.getString("title");*/
String final_note = tmp.getString("final_note");
String newModuleName = tmp.getString("titlemodule");
String newYear = tmp.getString("scolaryear");
if (!(newYear.equals(year))) {
year = newYear;
nodeItem = new YearHolder.IconTreeItem(1, year);
parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
root.addChild(parent);
}
if (!(newModuleName.equals(moduleName))) {
moduleName = newModuleName;
nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
parent.addChild(parentModule);
}
NoteHolder.IconTreeItem nodeNote = new NoteHolder.IconTreeItem(1, final_note);
child = new TreeNode(nodeNote).setViewHolder(new NoteHolder(_mainContext));
parentModule.addChildren(child);
/*String display = year + " | " + title + " | " + final_note;*/
}
AndroidTreeView tView = new AndroidTreeView(_notesActivity, root);
_notesActivity.setContentView(tView.getView());
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
YearHolder class looks like this :
public class YearHolder extends TreeNode.BaseNodeViewHolder<YearHolder.IconTreeItem> {
public YearHolder (Context context ) {
super(context);
}
#Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.custom_notes_view, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.text_title);
tvValue.setText(value.text);
return view;
}
public static class IconTreeItem {
public int icon;
public String text;
IconTreeItem(int icon_, String text_) {
this.icon = icon_;
this.text = text_;
}
}
}
Super easy to use !

Related

How to do a select all using GreenDAO?

Does anyone know how to do a simple select * from table in greenDAO and place it into an entity? I have done some research on this and I am unable to get any simple example. This is what I have so far:
public void storeAppTimeUsageData(AppTimeUsage stats) {
List<AppTimeUsage> items = new ArrayList<>();
//appTimeUsageDao = DeviceInsightApp.getSession(this, true).getAppTimeUsageDao();
try {
// master
appTimeUsageDao.insertOrReplace(stats);
//} catch (IOException e) {
} catch (Exception e) {
Log.e("Error", "Some exception occurred", e);
Log.e("APP_TAG", "STACKTRACE");
Log.e("APP_TAG", Log.getStackTraceString(e));
}
String sql = "SELECT * FROM APP_TIME_USAGE ";
Cursor c = appTimeUsageDao.getDatabase().rawQuery(sql, null);
int offset = 0;
int d ;
int cd ;
String e = "";
while (c.moveToNext()) {
AppTimeUsage atu AppTimeUsage(
c.getLong(0);
//long b = c.getInt(0);
d = c.getInt(2);
e = c.getString(3);
break;
);
items.add(atu);
}
}
GreenDAO already comes with a built-in method for achieve this task. In your case:
List<AppTimeUsage> items = appTimeUsageDao.loadAll();
This will select all records from APP_TIME_USAGE and return a List<AppTimeUsage> containing the entities.

NullPointerException with listview on android

I am want to show this json data in to listview. Iam having this problem:
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
private String[] arrow() throws JSONException {
json = new JSONObject();
JSONArray com= null;
String[] list = new String[10];
try {
com = json.getJSONArray("parameters"); // this have 10 different values
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++)
try {
json = com.getJSONObject(i);
String forward= json.getString("forward");
String back= json.getString("back");
list[i]="Forward: " + forward + "\n" + "Backward: " + back;
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
I did it with textview but cant do it with listview, i get this nullpointer..
Please help. Thanks.
There are multiple problems. The first problem is that you are using two try/catch. If you get exception in first one, you still go to 2nd try and try to run code.
json = com.getJSONObject(i);
this line is in 2nd try catch. In your case it seems com is null because there was exception in 1st try/catch.
try {
com = json.getJSONArray("parameters"); // this have 10 different values
for (int i = 0; i < com.length(); i++) {
json = com.getJSONObject(i);
String forward= json.getString("forward");
String back= json.getString("back");
list[i]="Forward: " + forward + "\n" + "Backward: " + back;
}
} catch (JSONException e) {
e.printStackTrace();
}

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

is it possible to loop through the ids to findViewById android [duplicate]

This question already has answers here:
Android getResources/getIdentifier not returning ID
(2 answers)
Closed 7 years ago.
I Have a table created on the GUI but I'm stuck on looping through the IDs of the views as it is not a string that goes in the path. HELP anyone please!
for example IDs are tMon9, tMon10, tMon11 etc...
String classgroup = "CO.DNET3";
int semester = 2;
Timetable t = null;
try {
t = new Timetable(classgroup, semester);
} catch (IOException e) {
e.printStackTrace();
}
if(t!=null)
{
TextView tv;
for (int i = 9; i < 18; i++) {
if (t.getModule("wednesday", i + ":00") != null) {
tv=(TextView)findViewById(R.id. (LOOP HERE) ); // I want to loop through ids
String s = "";
s+= t.getModule("wednesday", i + ":00") + "\n";
s+= t.getRoomNumber("wednesday", i + ":00") + "\n";
tv.setText(s);
}
}
}
Use getIdentifier to get id of View using String name:
int textViewID = getResources().getIdentifier("tMon"+i, "id", getPackageName());
tv=(TextView)findViewById(textViewID);

Displaying data from an ISP/Telephone (Telstra.com.au in Australia)

I am currently having issues in attempting to display data (i.e. itemSummaries with a certain ContainerType) for sites that are ISP, as an example, www.telstra.com.au from Australia
Logging into the site works fine, and the credentials for the site work fine (in other words, it does a refresh which succeeds), however there doesn't appear to be a way to display the itemSummary data
The soap command getItemSummaries, doesn't display data for the item (it displays item data from financial institutions fine). Upon examining the sample code provided by Yodlee for the java soap api, you are meant to use the getItemSummaries1 along with setting ContainerTypes using a SummaryRequest
The problem is that this returns a CoreExceptionFaultMessage. The getItemSummaries1 command is causing the CoreExceptionFaultError. Using different ContainerTypes with different combinations (i.e. ISP, Telephone, Bills) didn't alleviate the issue
The same error message is returned in Yodlees own sample code, i.e. java_soap_example (run the com.yodlee.sampleapps.accountsummary.DisplayBillsData main method and provide the Yodlee login info as command line arguments)
As a reference, the code that is provided by Yodlee sample app is below
Running the getItemSummaries1 command
public void displayBillsData (UserContext userContext)
{
/*SummaryRequest sr = new SummaryRequest(
new String[] {ContainerTypes.BILL, ContainerTypes.TELEPHONE},
new DataExtent[] { DataExtent.getDataExtentForAllLevels(),DataExtent.getDataExtentForAllLevels() }
);*/
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(new String[] {ContainerTypesHelper.BILL, ContainerTypesHelper.TELEPHONE});
sr.setContainerCriteria(list);
Object[] itemSummaries = null;
List itemSummariesList = null;
try {
itemSummariesList = dataService.getItemSummaries1(userContext, sr);
if (itemSummariesList != null){
itemSummaries = itemSummariesList.getElements();
}
} catch (StaleConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (InvalidConversationCredentialsExceptionFault e) {
e.printStackTrace();
} catch (CoreExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentTypeExceptionFault e) {
e.printStackTrace();
} catch (IllegalArgumentValueExceptionFault e) {
e.printStackTrace();
} catch (InvalidUserContextExceptionFault e) {
e.printStackTrace();
} catch (IllegalDataExtentExceptionFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
if (itemSummaries == null || itemSummaries.length == 0) {
System.out.println ("No bills data available");
return;
}
for (int i = 0; i < itemSummaries.length; i++) {
ItemSummary is = (ItemSummary) itemSummaries[i];
displayBillsDataForItem(is);
// Dump the BillsData Object
// dumpBillsDataForItem(is);
}
}
Printing the item data
public void displayBillsDataForItem (ItemSummary is)
{
String containerType = is.getContentServiceInfo ().
getContainerInfo ().getContainerName ();
System.out.println("containerType = " + containerType );
if (!(containerType.equals(ContainerTypesHelper.BILL ) || containerType.equals(ContainerTypesHelper.TELEPHONE)
|| containerType.equals(ContainerTypesHelper.MINUTES))) {
throw new RuntimeException ("displayBillsDataForItem called with " +
"invalid container type: " + containerType);
}
DisplayItemInfo displayItemInfo = new DisplayItemInfo ();
System.out.println("DisplayItemInfo:");
displayItemInfo.displayItemSummaryInfo (is);
System.out.println("");
ItemData id = is.getItemData();
if(id == null){
System.out.println("ItemData == null");
}else{
List accountsList = id.getAccounts();
Object[] accounts = null;
if (accountsList != null){
accounts = accountsList.getElements();
}
if (accounts == null || accounts.length == 0) {
System.out.println ("\tNo accounts");
}else {
for (int accts = 0; accts < accounts.length; accts++) {
BillsData billsData = (BillsData) accounts[accts];
System.out.println("\tAccount Holder: " + billsData.getAccountHolder() );
System.out.println("\tAccount Id: " + billsData.getAccountId());
System.out.println("\tItemAccountId: " + billsData.getItemAccountId() );
System.out.println("\tAccountName: " + billsData.getAccountName() );
System.out.println("\tAccountNumber: " + billsData.getAccountNumber() );
System.out.println("");
// Get List of Bill Objects
List billsList = billsData.getBills();
Object[] bills = null;
if (billsList != null){
bills = billsList.getElements();
}
if (bills == null || bills.length == 0) {
System.out.println ("\t\tNo Bill objects");
}else {
for (int b = 0; b < bills.length; b++) {
Bill bill = (Bill) bills[b];
System.out.println("\t\tBill Account Number: " + bill.getAccountNumber() );
System.out.println("\t\tBill Acct Type: " + bill.getAcctType() );
System.out.println("\t\tBill Due Date: " + Formatter.formatDate(bill.getDueDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Date: " + Formatter.formatDate(bill.getBillDate().getDate(), Formatter.DATE_SHORT_FORMAT) );
System.out.println("\t\tBill Past Due: "
+ (bill.getPastDue() != null ? bill
.getPastDue().getAmount() : 0.0));
System.out
.println("\t\tBill Last payment: "
+ (bill.getLastPayment() != null ? bill
.getLastPayment()
.getAmount()
: 0.0));
System.out.println("\t\tBill Amount Due: "
+ (bill.getAmountDue() != null ? bill
.getAmountDue().getAmount() : 0.0));
System.out
.println("\t\tBill Min Payment: "
+ (bill.getMinPayment() != null ? bill
.getMinPayment()
.getAmount()
: 0.0));
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = bill.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\t\tNo AccountUsageData objects");
}else {
for (int usage = 0; usage < acctUsageData.length; usage++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usage];
System.out.println("\t\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
System.out.println("");
// Get List of AccountUsageData
List acctUsageDataList = billsData.getAccountUsages();
Object[] acctUsageData = null;
if (acctUsageDataList != null){
acctUsageData = acctUsageDataList.getElements();
}
if (acctUsageData == null || acctUsageData.length == 0) {
System.out.println ("\t\tNo AccountUsageData objects");
}else {
for (int usageData = 0; usageData < acctUsageData.length; usageData++) {
AccountUsageData aud = (AccountUsageData) acctUsageData[usageData];
System.out.println("\t\tAccount Usage Bill ID: " + aud.getBillId() );
System.out.println("\t\tAccount Usage Units Used: " + aud.getUnitsUsed() );
}
}
}
}
}
}
EDIT2:
I have updated the getItemSummaries1 command to look like this
ContainerCriteria bills = new ContainerCriteria();
ContainerCriteria telephone = new ContainerCriteria();
ContainerCriteria isp = new ContainerCriteria();
ContainerCriteria utilities = new ContainerCriteria();
bills.setContainerType(ContainerTypesHelper.BILL);
telephone.setContainerType(ContainerTypesHelper.TELEPHONE);
isp.setContainerType(ContainerTypesHelper.ISP);
utilities.setContainerType(ContainerTypesHelper.UTILITIES);
Object[] containerList = {
bills,telephone,isp,utilities
};
SummaryRequest sr = new SummaryRequest();
List list = new List();
list.setElements(containerList);
sr.setContainerCriteria(list);
The command now executes and works correctly, however its returning a list of 0 elements (using DataExtents with different values didn't change anything). My suspicion is that Telstra.com.au site is broken on Yodlee's end (when a full refresh is done on the Telstra site, Yodlee returns a null for refreshing that specific site).
So far I can see some deviation, so do modify your container criteria as mentioned below
object[] list = {
new ContainerCriteria { containerType = "bills" },
new ContainerCriteria { containerType = "telephone" }
};
sr.containerCriteria = list;
You may additionally provide data extent as follows
DataExtent de = new DataExtent();
dataExtent.startLevel = 0; //as per your needs
dataExtent.endLevel = 0; //as per your needs
object[] list = {
new ContainerCriteria { containerType = "bills", dataExtent = de },
new ContainerCriteria { containerType = "telephone", dataExtent = de }
};
sr.containerCriteria = list;
This should solve your issue. If not then try to get the detail which is is node in the response for the CoreExceptionFaultMessage, this detail may help to diagnose the accurate issue.
To get data for any of the container first you need to add an account for the site belonging to that container. Once you have added the account successfully then only you will be able to pull in the data for such container. Also you can check the tag returned in the getItemSummaries API which has and once this statusCode = 0 then only you have data present for that account.
You can do testing by using the Dummy account which yodlee provides. Please refer to Yodlee Dummy account generator page for more info on Dummy accounts.

Categories