I started studying Java, I'm addicted to it now. Java seems to be easier than English for me. I just LOVE JAVA! I stated learning Java two days ago. Yesterday, at night, I started writing code without peaking in a book or some website. I'm getting a certain error whenever I use Scanners.
Code:
package com.jasonkzly.ProjectMine;
import java.util.Scanner;
public class Start {
public static void main(String jason[]){
Scanner inputUser = new Scanner(System.in);
double misc;
System.out.println("What are you doing? Addition(Type 1), Subtraction (Type 2), Multiplication (Type 3) or Division (Type 4)");
misc = inputUser.nextDouble();
if(misc == 1)
{
Addition();
}
if(misc == 2)
{
Subtraction();
}
if(misc == 3)
{
Multiplication();
}
if(misc == 4)
{
Division();
}
if(misc == 0 || misc > 4)
{
System.out.println("Enter A Valid Option!");
wrongInput();
}
}
public static void wrongInput()
{
double misc;
Scanner inputUser = new Scanner(System.in);
System.out.println("What are you doing? Adition(Type 1), Subtraction (Type 2), Multiplication (Type 3) or Division (Type 4)");
misc = inputUser.nextDouble();
if(misc == 1)
{
Addition();
}
if(misc == 2)
{
Subtraction();
}
if(misc == 3)
{
Multiplication();
}
if(misc == 4)
{
Division();
}
if(misc == 0 || misc > 4)
{
System.out.println("Enter A Valid Option!");
wrongInput();
}
}
public static void Addition()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf +nums;
System.out.println("The Sum of " + numf + " and " + nums + " is " + answer);
}
public static void Subtraction()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf - nums;
System.out.println(numf + " minus " + nums + " is equal to " + answer + ".");
}
public static void Multiplication()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf * nums;
System.out.println("The Product of " + numf + " and " + nums + " is " + answer + ".");
}
public static void Division()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf / nums;
System.out.println("The Answer is " + answer + "." );
}
}
I get this warning in Eclipse (next to the Scanner) --- Resource leak: "inputUser" is never closed --- That looks like Chinese to me, the only fixes I have is to add "SuppressWarning" Thingies...
And BTW, I would appreciate it if you guys could give me some advice or something like that!
--------------------
Linux Mint 14 "Nadia" 32 bit,
OpenJDK 7,
Eclipse Helios.
I just checked your code (copied it to Eclipse) and it does not show any warning for me.
Running it works fine, too:
Code:
What are you doing? Addition(Type 1), Subtraction (Type 2), Multiplication (Type 3) or Division (Type 4)
1
What is the First Number?
2
What is the Second Number?
3
The Sum of 2.0 and 3.0 is 5.0
Oh, which JDK do you use?
Have you tried inputUser.close(); when you know you are done with that object? Also on a side note. Being that you are asking for what type of math operation you are doing twice, I would suggest creating a routine for it and calling that routine a second time if need be. Reuse your code when possible. It saves you time in the long run.
Code:
package com.jasonkzly.ProjectMine;
import java.util.Scanner;
public class Start {
public static void main(String jason[]){
getOperation();
}
public static void getOperation()
{
double misc;
Scanner inputUser = new Scanner(System.in);
System.out.println("What are you doing? Adition(Type 1), Subtraction (Type 2), Multiplication (Type 3) or Division (Type 4)");
misc = inputUser.nextDouble();
//try closing inputUser here, should work since misc is already set.
inputUser.close();
switch(misc){
case 1: {
Addition();
break;
}
case 2: {
Subtraction();
break;
}
case 3: {
Multiplication();
break;
}
case 4: {
Division();
break;
}
default: {
System.out.println("Enter A Valid Option!");
getOperation();
break;
}
}
public static void Addition()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf +nums;
System.out.println("The Sum of " + numf + " and " + nums + " is " + answer);
}
public static void Subtraction()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf - nums;
System.out.println(numf + " minus " + nums + " is equal to " + answer + ".");
}
public static void Multiplication()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf * nums;
System.out.println("The Product of " + numf + " and " + nums + " is " + answer + ".");
}
public static void Division()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf / nums;
System.out.println("The Answer is " + answer + "." );
}
}
zalez said:
Have you tried inputUser.close(); when you know you are done with that object? Also on a side note. Being that you are asking for what type of math operation you are doing twice, I would suggest creating a routine for it and calling that routine a second time if need be. Reuse your code when possible. It saves you time in the long run.
Code:
package com.jasonkzly.ProjectMine;
import java.util.Scanner;
public class Start {
public static void main(String jason[]){
getOperation();
}
public static void getOperation()
{
double misc;
Scanner inputUser = new Scanner(System.in);
System.out.println("What are you doing? Adition(Type 1), Subtraction (Type 2), Multiplication (Type 3) or Division (Type 4)");
misc = inputUser.nextDouble();
//try closing inputUser here, should work since misc is already set.
inputUser.close();
switch(misc){
case 1: {
Addition();
break;
}
case 2: {
Subtraction();
break;
}
case 3: {
Multiplication();
break;
}
case 4: {
Division();
break;
}
default: {
System.out.println("Enter A Valid Option!");
getOperation();
break;
}
}
public static void Addition()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf +nums;
System.out.println("The Sum of " + numf + " and " + nums + " is " + answer);
}
public static void Subtraction()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf - nums;
System.out.println(numf + " minus " + nums + " is equal to " + answer + ".");
}
public static void Multiplication()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf * nums;
System.out.println("The Product of " + numf + " and " + nums + " is " + answer + ".");
}
public static void Division()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf / nums;
System.out.println("The Answer is " + answer + "." );
}
}
Click to expand...
Click to collapse
I tried that before and it crashed. Without it it did not.
I have never had to close a Scanner.
That is weird. I would ignore it then as well.
Thank you!
Hey Guys! Thanks for all your replies!
I did a bit of Googling and this problem seems to be specific with Java 7.
BTW, I'm using OpenJDK 7 in Mint 32 bit... Eclipse Helios.
Eureka!!!
zalez said:
Have you tried inputUser.close(); when you know you are done with that object? Also on a side note. Being that you are asking for what type of math operation you are doing twice, I would suggest creating a routine for it and calling that routine a second time if need be. Reuse your code when possible. It saves you time in the long run.
Code:
package com.jasonkzly.ProjectMine;
import java.util.Scanner;
public class Start {
public static void main(String jason[]){
getOperation();
}
public static void getOperation()
{
double misc;
Scanner inputUser = new Scanner(System.in);
System.out.println("What are you doing? Adition(Type 1), Subtraction (Type 2), Multiplication (Type 3) or Division (Type 4)");
misc = inputUser.nextDouble();
//try closing inputUser here, should work since misc is already set.
inputUser.close();
switch(misc){
case 1: {
Addition();
break;
}
case 2: {
Subtraction();
break;
}
case 3: {
Multiplication();
break;
}
case 4: {
Division();
break;
}
default: {
System.out.println("Enter A Valid Option!");
getOperation();
break;
}
}
public static void Addition()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf +nums;
System.out.println("The Sum of " + numf + " and " + nums + " is " + answer);
}
public static void Subtraction()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf - nums;
System.out.println(numf + " minus " + nums + " is equal to " + answer + ".");
}
public static void Multiplication()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf * nums;
System.out.println("The Product of " + numf + " and " + nums + " is " + answer + ".");
}
public static void Division()
{
double numf, nums, answer;
Scanner input = new Scanner(System.in);
System.out.println("What is the First Number?");
numf = input.nextDouble();
System.out.println("What is the Second Number?");
nums = input.nextDouble();
answer = numf / nums;
System.out.println("The Answer is " + answer + "." );
}
}
Click to expand...
Click to collapse
Thanks for the so-awesome reply!... It works!!!:victory:
BTW, Can I ask one more question?
Ask away.
zalez said:
Ask away.
Click to expand...
Click to collapse
How do you use Java in Android??? I am puzzled. I've seen people use some weird things like "onStart", "onPause" and onClickListener... none of this is in my study material. Most Tutorials don't tutorials simply "teach"... they don't say "why"?
JasonKZLY said:
How do you use Java in Android??? I am puzzled. I've seen people use some weird things like "onStart", "onPause" and onClickListener... none of this is in my study material. Most Tutorials don't tutorials simply "teach"... they don't say "why"?
Click to expand...
Click to collapse
It is related to the Activity lifecycle: http://docs.xamarin.com/guides/android/application_fundamentals/activity_lifecycle
Al UI things are different in Android.
Related
Hello, in android,
How do you use a TextView to show multiple lines of text in android?
I tried doing android:singleLine = "false" but that's not working
Here is my code
for(int i = 1; i <= 10; i++)
{
tv.setText("instant " + i + ": ");
}
so it should say
instant 1:
instant 2:
instant 3:
instant 4:
instant 5:
instant 6:
instant 7:
instant 8:
instant 9:
instant 10:
BUT, the emulator only showing
instant 10:
How can I achieve this? Thanks!
You are setting the text value each time you go through the loop so it will only show you the result of the final iteration. You should hold a temporary string variable instead and add to it in the loop. Then set it to the textview value after the loop is finished.
Sent from my HTC Desire using XDA App
String s = "";
for(int i = 1; i <= 10; i++)
{
s.concat("\ninstant " + i + ": ");
}
tv.setText(s);
Hi, I am trying this but nothing is shown on screen
Code:
String s="";
for(int i = 1; i <= 10; i++)
{
tv.setText(s + "instant " + i + ": \n");
s=(String) tv.getText();
}
or
Code:
for(int i = 1; i <= 10; i++)
{
tv.setText(tv.getText() + "instant " + i + ": \n");
}
Hello everybody. I've tried to make a suitable database for my game that will represent shop stock. The problem is when I call the purchase() method, I got that exception mentioned in the title. The problem is that I need to chceck depending on ID if I need to increment number of purchases or i just unlock the whole item. Here is my code for the database
Code:
public class MonsterTapDatabase extends SQLiteOpenHelper {
static final String dbName = "MonsterTapDb";
static final int version = 1;
static final String tTableName = "Shop";
static final String fItemID = "ItemID";
static final String fItemName = "ItemName";
static final String fItemNumberOfPurchases = "NumberOfPurchases";
static final String fItemIsLocked = "IsItemLocked";
public MonsterTapDatabase(Context context) {
super(context, dbName, null, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+tTableName+" (" +
fItemID + " INTEGER PRIMARY KEY , " +
fItemName + " TEXT , " +
fItemNumberOfPurchases + " INT, " +
fItemIsLocked + " TEXT" +
")");
ContentValues cv = new ContentValues();
cv.put(fItemID, 1);
cv.put(fItemName, "Lives");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
cv.put(fItemID, 2);
cv.put(fItemName, "Hardmode");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
cv.put(fItemID, 3);
cv.put(fItemName, "Reversed");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
cv.put(fItemID, 4);
cv.put(fItemName, "Reversed Hardmode");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + tTableName);
onCreate(sqLiteDatabase);
}
public void purchase(int ID){
if(ID==1){
SQLiteDatabase myDB = this.getReadableDatabase();
String[] mySearch = new String[]{String.valueOf(ID)};
Cursor myCursor = myDB.rawQuery("SELECT "+ fItemNumberOfPurchases +" FROM "+ tTableName +" WHERE "+ fItemID +"=?",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(fItemNumberOfPurchases);
if(index<5){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fItemNumberOfPurchases, index);
db.update(tTableName,cv, fItemID, new String[]{String.valueOf(ID)});
}
else{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fItemIsLocked, false);
db.update(tTableName,cv, fItemID, new String[]{String.valueOf(ID)});
}
myCursor.close();
}
else{
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fItemIsLocked, false);
cv.put(fItemNumberOfPurchases, 1);
myDB.update(tTableName, cv, fItemID+"=?", new String []{String.valueOf(ID)});
}
}
public String isPurchased(int ID){
SQLiteDatabase myDB = this.getReadableDatabase();
String[] mySearch = new String[]{String.valueOf(ID)};
Cursor myCursor = myDB.rawQuery("SELECT "+ fItemIsLocked +" FROM "+ tTableName +" WHERE "+ fItemID +"=?",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(fItemID);
String myAnswer = myCursor.getString(index);
myCursor.close();
return myAnswer;
}
public int numberOfLives(){
int ID = 1;
SQLiteDatabase myDB = this.getReadableDatabase();
String[] mySearch = new String[]{String.valueOf(ID)};
Cursor myCursor = myDB.rawQuery("SELECT "+ fItemNumberOfPurchases +" FROM "+ tTableName +" WHERE "+ fItemID +"=?",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(fItemNumberOfPurchases);
myCursor.close();
return index;
}
}
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.
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;
}
}
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;
}
}