My JSONArray keeps appending the last object on loop - Java for Android App Development

Here is my code:
Code:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jObject = new JSONObject(jsonObj.toString().trim());
Iterator<?> keys = jObject.keys();
JSONArray temp_json_arr = null;
JSONObject temp_json_obj = null;
String temp_string = "";
int index_count = 0;
LinearLayout ll = (LinearLayout)findViewById(R.id.test_layout);
//temp_json_obj = jsonObj.getJSONObject("identification");
//Log.d("TEST: ", "ARRAY LENGTH> "+temp_json_arr.length());
while( keys.hasNext() ){
String key = (String)keys.next();
Log.d("TEST: ", "KEYS> " + key);
// Getting JSON Array node
temp_json_arr = jsonObj.getJSONArray(key);
// looping through All Questions
for (int i = 0; i < temp_json_arr.length(); i++) {
JSONObject q = temp_json_arr.getJSONObject(i);
if( key.equals("identification") ) {
tv[tv_ctr] = new TextView(getApplicationContext());
tv[tv_ctr] = (TextView)findViewById(id);
id++;
et[identification_question] = new EditText(getApplicationContext());
et[identification_question] = (EditText)findViewById(id);
id++;
//json manipulation
try {
jsonOb.put("question-id", tv[tv_ctr].getText().toString());
jsonOb.put("answer", et[identification_question].getText().toString());
} catch(Exception e) {
}
Log.d("TEST: ", "jsonOb> " + jsonOb.toString());
//answer += et[identification_question].getText().toString() + "-" + tv[tv_ctr].getText().toString() + "/";
tv_ctr++;
identification_question++;
jsonArr.put(test,jsonOb);
test++;
Log.d("TEST: ", "jsonArr> " + jsonArr.toString());
}
Everytime I use .put of the JSONArray, it appends the last object on all indexes for example:
I have 3 input namely answer 1 , answer 2 and answer 3
The expected json data will be this:
Code:
[{"answer":"answer1","question-id":"question1"},{"answer":"answer2","question-id":"question2"},{"answer":"answer3","question-id":"question3"}]
But this is the current output:
Code:
[{"answer":"answer3","question-id":"question3"},{"answer":"answer3","question-id":"question3"},{"answer":"answer3","question-id":"question3"}]
As you can see the last index get appended multiple times.

Nevermind I've already solved my own problem.

Related

[Q] How to convert extended ASCII character to number in Android?

Hi!
Can you help me, please? I'm working on an Android app. I get some characters from a file on the Internet and put it to a TextView. These characters are ASCII characters. Then I read these characters one by one and convert it to numbers with the following code:
Code:
char my_char2;
char my_char3;
int myNum = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
myNum = my_char2 * 256 + my_char3;
}
}
Then I write it to an another TextView:
Code:
crlNumber.setText("" + myNum);
The problem is that this can only convert standard ASCII characters(from 0 to 127) except of the new line character(character number 10), carriage return character(character number 13) and the cancel character(character number 24).
But I need to convert also the extended ASCII characters(from 128 to 255) and the 3 characters mentioned above.
What should I do?
Thanks for helping.
Do these help?
http://stackoverflow.com/questions/13826781/java-extended-ascii-table-usage
http://stackoverflow.com/questions/5535988/string-to-binary-and-vice-versa-extended-ascii
nikwen said:
Do these help?
http://stackoverflow.com/questions/13826781/java-extended-ascii-table-usage
http://stackoverflow.com/questions/5535988/string-to-binary-and-vice-versa-extended-ascii
Click to expand...
Click to collapse
A little. I have tried the following code below. It didn't show me the number of the extended ascii characters. But I think I should somehow read the text not as a String, but as a byte, and then I think, it should work(maybe I am wrong). If it is right, please, can you tell me, how should I do it?
Code:
final String textSource = "path to my file";
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
String PT = textMsg.getText().toString();
CharSequence c = new String(PT);
String string0 = "";
String string1 = "";
char my_char2;
char my_char3;
String binary = "";
String binary2 = "";
int myNum2 = 0;
int decimalValue1 = 0;
int decimalValue2 = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
char[] buffer = string0.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
binary = Integer,toBinaryString(b[i] & 0xFF);
decimalValue1 = Integer.parseInt(binary, 2);
}
char[] buffer2 = string1.toCharArray();
byte[] b2 = new byte[buffer2.length];
for (int i = 0; i < b2.length; i++) {
b2[i] = (byte) buffer2[i];
binary2 = Integer.toBinaryString(b2[i] & 0xFF);
decimalValue2 = Integer.parseInt(binary2, 2);
}
myNum2 = decimalValue1 * 256 + decimalValue2;
}
}
crlNumber.setText("" + binary2 + "," + decimalValue1 + "," + decimalValue2 + "," + myNum2);
}
adamhala007 said:
A little. I have tried the following code below. It didn't show me the number of the extended ascii characters. But I think I should somehow read the text not as a String, but as a byte, and then I think, it should work(maybe I am wrong). If it is right, please, can you tell me, how should I do it?
Code:
final String textSource = "path to my file";
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
String PT = textMsg.getText().toString();
CharSequence c = new String(PT);
String string0 = "";
String string1 = "";
char my_char2;
char my_char3;
String binary = "";
String binary2 = "";
int myNum2 = 0;
int decimalValue1 = 0;
int decimalValue2 = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
char[] buffer = string0.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
binary = Integer,toBinaryString(b[i] & 0xFF);
decimalValue1 = Integer.parseInt(binary, 2);
}
char[] buffer2 = string1.toCharArray();
byte[] b2 = new byte[buffer2.length];
for (int i = 0; i < b2.length; i++) {
b2[i] = (byte) buffer2[i];
binary2 = Integer.toBinaryString(b2[i] & 0xFF);
decimalValue2 = Integer.parseInt(binary2, 2);
}
myNum2 = decimalValue1 * 256 + decimalValue2;
}
}
crlNumber.setText("" + binary2 + "," + decimalValue1 + "," + decimalValue2 + "," + myNum2);
}
Click to expand...
Click to collapse
Hm, I don't know. According to this answer, you can change the encoding on the desktop, otherwise you will just see question marks.
But according to the accepted answer here, this should be done automatically on a Linux system. And Android is Linux based. Did you try it on an Android device or just on your computer?
Bytes shouldn't work. In Java they are signed, so their range is -128 ... 127.
nikwen said:
Hm, I don't know. According to this answer, you can change the encoding on the desktop, otherwise you will just see question marks.
But according to the accepted answer here, this should be done automatically on a Linux system. And Android is Linux based. Did you try it on an Android device or just on your computer?
Bytes shouldn't work. In Java they are signed, so their range is -128 ... 127.
Click to expand...
Click to collapse
Yes, I tried it on my Android device. Maybe, the best choice would be then to use that certificate code which you suggested me in one of my previous threads, but the problem is, that I am beginner in Android developing and I read it and I didn't know how to use it in my code. So I thougt, if I got the 2 ASCII characters and converted it to decimal numbers, it would also work. And it also works until I have the standard ASCII characters. When there is an extended ASCII character, it shows me the number 65533.
adamhala007 said:
Yes, I tried it on my Android device. Maybe, the best choice would be then to use that certificate code which you suggested me in one of my previous threads, but the problem is, that I am beginner in Android developing and I read it and I didn't know how to use it in my code. So I thougt, if I got the 2 ASCII characters and converted it to decimal numbers, it would also work. And it also works until I have the standard ASCII characters. When there is an extended ASCII character, it shows me the number 65533.
Click to expand...
Click to collapse
But I think I have found out something.
Code:
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
int one = 0;
int two = 0;
String ascii1="\u001f";
String ascii2="\u0018";
String aa = "";
String bb = "";
if(string0.equals(ascii1)){
one = one + 31;
aa = aa + one;
}else{
one = 1;
}
if(string1.equals(ascii2)){
two = two + 24;
bb = bb + two;
}else{
two = 1;
}
textPrompt.setText("" + aa + bb);
But this needs a little correction, because this way it doesn't show me anything, but if I write
Code:
textPrompt.setText("" + aa);
inside my first if statement it shows me correctly 31. What can be the mistake I have made?
convert ASCII character
I'm a self android learner. I want to convert ascii code to character. Here is the code I used.
String s = "1000001";
int num = Integer.parseInt(s, 2);
TextView textView = new TextView(this);
textView.setText(String.valueOf(num));
setContentView(textView);
Here s is 1000001(65 in decimal) 65 is ascii value of 'A'. I want to get 'A' in my output screen.variable num has the value 65. please help me

How can I loop through my JSON object?

I am new to Java and I am getting kind of stuck by trying to loop through my JSON. I am retrieving a JSON object where I want to loop through.
My JSON looks as follow:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","success":1,"created_at":null,"updated_at":null}]}}
I tried a loop like this:
Code:
for(int i = 0; i<json.names().length(); i++){
try {
Log.v("TEST", "key = " + json.names().getString(i) + " value = " + json.get(json.names().getString(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
But this will only target "message" which includes the whole JSON "string". I want to loop through each message and retrieving the value of uid 1, uid 2 etc. How can I achieve this?
Thanks in advance.
Here is how I'm doing it:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String NEWS = "news";
private static final String TITLE = "title";
private static final String STORY = "story";
private final JSONParser jParser = new JSONParser();
private JSONArray newsItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
newsItems = json.getJSONArray(NEWS);
for (int i = 0; i < newsItems.length(); i++) {
JSONObject obj = newsItems.getJSONObject(i);
Integer id = i + 1;
String title = obj.getString(TITLE);
String story = obj.getString(STORY);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
CodeMonkeyy said:
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
Click to expand...
Click to collapse
You might want to try the matching JSONParser I have for it, sorry forgot to include it:
https://github.com/JonnyXDA/WGSB/bl...om/jonny/wgsb/material/parser/JSONParser.java
Also noting that your entire JSON Array is called "message" but you also have a parameter called "message" - maybe rename the Array to "messages"?
As for the code you should have something like:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String MESSAGES = "messages";
private static final String TITLE = "title";
private static final String MESSAGE = "message";
private final JSONParser jParser = new JSONParser();
private JSONArray messageItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
My code looks like the this:
Code:
//Message task
MessageTask task = new MessageTask(DashboardActivity.class);
task.execute();
try {
json = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
I am using Async Task to retrieve my JSON.
And my JSON parser looks like this:
Code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
CodeMonkeyy said:
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
Click to expand...
Click to collapse
We're getting closer! With regards to using AsyncTask - thats fine and the recommended way to do service side sync/download operations (doesn't block the UI thread) so no need to change that.
I just took a look at my reference JSON and I have the success tag outside of an item eg:
Code:
{"topical":[{"tid":"5","title":"Exam countdown... just 12 weeks left!","story":"some_story_text_here","staff":"0","red":"0","show":"1"}],[COLOR="red"]"success":1[/COLOR]}
Whereas your success tag is put in each item:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","[COLOR="red"]success":1,[/COLOR]"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !",[COLOR="red"]"success":1[/COLOR],"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","[COLOR="Red"]success":1[/COLOR],"created_at":null,"updated_at":null}]}}
I'm guessing that your php line for:
PHP:
$response["success"] = 1;
is inside of the while loop:
PHP:
while ($row = mysql_fetch_array($result)) {
Taking it out of the while loop should fix that
That makes sense, because I am trying to get a success code for my whole JSON response. I changed my PHP code to:
Code:
while($row = mysqli_fetch_array( $messages )) {
// create rowArr
$rowArr = array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row["message"],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
// store rowArr in $return_arr
$return_arr[$row['id']][] = $rowArr;
}
$return_arr['success'] = 1;
// Json encode
echo json_encode(array("messages" => $return_arr));
}
Retrieving the following JSON:
Code:
{"messages":{"2":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}],"success":1}}
But I am still getting the following exception:
Code:
org.json.JSONException: No value for success
The success tag is still being encoded as part of an inner array, not the first array - try this:
PHP:
if (mysql_num_rows($messages) > 0) {
$response["messages"] = array();
while ($row = mysql_fetch_array($messages)) {
$messagesArray= array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row['message'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
array_push($response["messages"], $messagesArray);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No messages found";
echo json_encode($response);
}
And it's finally working!
Getting the following JSON result:
Code:
{"tag":"message","success":1,"error":0,"messages":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null},{"uid":"3","title":"","message":"Test2!","created_at":null,"updated_at":null},{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}]}
And I can successfully loop through my JSON with the following code:
Code:
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
Log.e("TITLE :", title);
Log.e("MESSAGE :", message);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you very much! So the problem was that I placed the "success" tag outside my Array?

ProcessBuilder.start() with "su" command blocks thread

I'm implementing a terminal "emulator"/"launcher" in my app. I want to let the user to use all android shell commands. This works great, until I use the "su" command. here is the source code:
Code:
ProcessBuilder processBuilder = new ProcessBuilder(input);
processBuilder.directory(info.currentDirectory);
Process process;
try {
process = processBuilder.start();
} catch (IOException e) {
return 1;
}
process.waitFor();
InputStream i = process.getInputStream();
InputStream e = process.getErrorStream();
BufferedReader ir = new BufferedReader(new InputStreamReader(i));
BufferedReader er = new BufferedReader(new InputStreamReader(e));
String s = null;
output = "";
for(int count = 0; count == 0 || s != null; count++) {
s = ir.readLine();
if(s != null) {
if(count == 0)
output = output.concat(mContext.getString(R.string.output_label) + "\n");
output = output.concat(s + "\n");
}
}
s = null;
for(int count = 0; count == 0 || s != null; count++) {
s = er.readLine();
if(s != null) {
if(count == 0)
output = output.concat(mContext.getString(R.string.error_label) + "\n");
output = output.concat(s + "\n");
}
}
process.destroy();
Main thread is blocked forever in any case: if I call only process.waitFor, and if I use one of the InputStream objects.
What's the problem? SU permissions are granted normally...

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int

hello i have a problems with app
result
W/System.err﹕ com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int but was BOOLEAN at line 1 column 856
code:
private Boolean getCourseInfo() {
CourseSyncTask cs = new CourseSyncTask(mUrl, token, siteInfo.getId());
publishProgress(context.getString(R.string.login_prog_sync_course));
Boolean usrCourseSyncStatus = cs.syncUserCourses();
if (!usrCourseSyncStatus) {
publishProgress(cs.getError());
publishProgress("\n"
+ context.getString(R.string.login_prog_sync_failed));
}
return usrCourseSyncStatus;
}
////////////////////////////////////////////////////////////
public class CourseSyncTask {
String mUrl;
String token;
long siteid;
String error;
/**
*
* @param mUrl
* @param token
* @param siteid
*
*/
public CourseSyncTask(String mUrl, String token, long siteid) {
this.mUrl = mUrl;
this.token = token;
this.siteid = siteid;
}
/**
* Sync all the courses in the current site.
*
* @return syncStatus
*
*/
public Boolean syncAllCourses() {
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getAllCourses();
/** Error checking **/
// Some network or encoding issue.
if (mCourses.size() == 0) {
error = "Network issue!";
return false;
}
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0) {
error = "Moodle Exception: User don't have permissions!";
return false;
}
// Add siteid to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses != null && dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsUserCourse(dbCourses.get(0).getIsUserCourse());
course.setIsFavCourse(dbCourses.get(0).getIsFavCourse());
}
course.save();
}
return true;
}
/**
* Sync all courses of logged in user in the current site.
*
* @return syncStatus
*/
public Boolean syncUserCourses() {
// Get userid
MoodleSiteInfo site = MoodleSiteInfo.findById(MoodleSiteInfo.class,
siteid);
if (site == null)
return false;
int userid = site.getUserid();
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getEnrolledCourses(userid + "");
/** Error checking **/
// Some network or encoding issue.
if (mCourses == null)
return false;
// Some network or encoding issue.
if (mCourses.size() == 0)
return false;
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0)
return false;
// Add siteid and isUserCourse to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
course.setIsUserCourse(true);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsFavCourse(dbCourses.get(0).getIsFavCourse());
}
course.save();
}
return true;
}
/**
* Error message from the last failed sync operation.
*
* @return error
*
*/
public String getError() {
return error;
}
}
////////////////////////////////////////////
public class MoodleRestCourse {
private final String DEBUG_TAG = "MoodleRestCourses";
private String mUrl;
private String token;
public MoodleRestCourse(String mUrl, String token) {
this.mUrl = mUrl;
this.token = token;
}
public ArrayList<MoodleCourse> getAllCourses() {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ALL_COURSES;
try {
// Adding all parameters.
String params = "" + URLEncoder.encode("", "UTF-8");
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
public ArrayList<MoodleCourse> getEnrolledCourses(String userId) {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ENROLLED_COURSES;
try {
// Adding all parameters.
String params = "&" + URLEncoder.encode("userid", "UTF-8") + "="
+ userId;
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
}

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int

hello i have a problems with app
result
W/System.err﹕ com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int but was BOOLEAN at line 1 column 856
code:
private Boolean getCourseInfo() {
CourseSyncTask cs = new CourseSyncTask(mUrl, token, siteInfo.getId());
publishProgress(context.getString(R.string.login_p rog_sync_course));
Boolean usrCourseSyncStatus = cs.syncUserCourses();
if (!usrCourseSyncStatus) {
publishProgress(cs.getError());
publishProgress("\n"
+ context.getString(R.string.login_prog_sync_failed) );
}
return usrCourseSyncStatus;
}
////////////////////////////////////////////////////////////
public class CourseSyncTask {
String mUrl;
String token;
long siteid;
String error;
/**
*
* @param mUrl
* @param token
* @param siteid
*
*/
public CourseSyncTask(String mUrl, String token, long siteid) {
this.mUrl = mUrl;
this.token = token;
this.siteid = siteid;
}
/**
* Sync all the courses in the current site.
*
* @return syncStatus
*
*/
public Boolean syncAllCourses() {
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getAllCourses();
/** Error checking **/
// Some network or encoding issue.
if (mCourses.size() == 0) {
error = "Network issue!";
return false;
}
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0) {
error = "Moodle Exception: User don't have permissions!";
return false;
}
// Add siteid to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses != null && dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsUserCourse(dbCourses.get(0).getIsUserC ourse());
course.setIsFavCourse(dbCourses.get(0).getIsFavCou rse());
}
course.save();
}
return true;
}
/**
* Sync all courses of logged in user in the current site.
*
* @return syncStatus
*/
public Boolean syncUserCourses() {
// Get userid
MoodleSiteInfo site = MoodleSiteInfo.findById(MoodleSiteInfo.class,
siteid);
if (site == null)
return false;
int userid = site.getUserid();
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getEnrolledCourses(userid + "");
/** Error checking **/
// Some network or encoding issue.
if (mCourses == null)
return false;
// Some network or encoding issue.
if (mCourses.size() == 0)
return false;
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0)
return false;
// Add siteid and isUserCourse to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
course.setIsUserCourse(true);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsFavCourse(dbCourses.get(0).getIsFavCou rse());
}
course.save();
}
return true;
}
/**
* Error message from the last failed sync operation.
*
* @return error
*
*/
public String getError() {
return error;
}
}
////////////////////////////////////////////
public class MoodleRestCourse {
private final String DEBUG_TAG = "MoodleRestCourses";
private String mUrl;
private String token;
public MoodleRestCourse(String mUrl, String token) {
this.mUrl = mUrl;
this.token = token;
}
public ArrayList<MoodleCourse> getAllCourses() {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ALL_COURSES;
try {
// Adding all parameters.
String params = "" + URLEncoder.encode("", "UTF-8");
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
public ArrayList<MoodleCourse> getEnrolledCourses(String userId) {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ENROLLED_COURSES;
try {
// Adding all parameters.
String params = "&" + URLEncoder.encode("userid", "UTF-8") + "="
+ userId;
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
}

Categories

Resources