Sum of items in JSONArray doubling on activity relaunch - android

I'm using Fast Android Networking library to parse a JSONArray generated from my PHP/MySQL API. I'm using a for loop to sum all integer values in the JSONArray. Everything works great when I first launch the activity the data is sent to (as static references), but on relaunch, the data is doubled i.e if on first launch sum was 500, on relaunch it returns 1000.
This is the method I use to parse the JSONArray
public void getGroupStats() {
MaterialDialog.Builder builder = new MaterialDialog.Builder(Splash.this)
.progress(true, 100)
.content("Loading...")
.cancelable(false);
dialog = builder.build();
dialog.show();
AndroidNetworking.post(Helper.Header + "/savings/api/Api.php?apicall=getgroups")
.addBodyParameter("goal", sharedPreferences.getString("Goal", ""))
.addBodyParameter("type", sharedPreferences.getString("Type", ""))
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("savings");
for (int j = 0; j < jsonArray.length(); j++) {
obj = (JSONObject) jsonArray.get(j);
groupsaving += Integer.parseInt(obj.getString("saving"));
groupsaved += Integer.parseInt(obj.getString("saved"));
Helper.Members = jsonArray.length();
}
Intent intent = new Intent(Splash.this, Statistics.class);
intent.putExtra("Title", textView.getText().toString());
if (textView.getText().toString().contains("SAVVY SAVER")) {
Helper.Image = "smallest_bag";
} else if (textView.getText().toString().contains("POWER SAVER")) {
Helper.Image = "small_bag";
} else if (textView.getText().toString().contains("SUPER SAVER")) {
Helper.Image = "big_bag";
} else {
Helper.Image = "biggest_bag";
}
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
Helper.GroupSaving = groupsaving;//to be used in next activity
Helper.GroupSaved = groupsaved;
Toast.makeText(getApplicationContext(), String.valueOf(groupsaved) + " " + String.valueOf(groupsaving), Toast.LENGTH_LONG).show();
dialog.cancel();
}
#Override
public void onError(ANError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
}
What am I doing wrong?

Cant you just make your variables zero before the loop?

Related

Quiz app- pls given logic for quiz app in next button, prev button and skip button

"Below code working but when I select Q1-answer and clicked next button in gone to Q2 but when i clicked on previous button to going Q1 but repeat I click next button is show toast massage pls select the answer but already given Q1 answer pls help
"android code"
#Override
public void onClick(View v) {
//Toast.makeText(getContext(),"talent",Toast.LENGTH_SHORT).show();
switch (v.getId()) {
case R.id.previous_button:
if (que_position > 0) {
que_position--;
//setSelectedOption();
setPreviousQuestion();
IsSelectedAnswer=true;
}
break;
case R.id.next_button:
//sendAnswers();
//setSelectedOption();
if (IsSelectedAnswer) {
setSelectedOption();
sendAnswers();
que_position++;
//setAnswers(que_position - 1);
setQuestion();
/*if (isFinishTest) {
setAnswers(que_position - 1);
setSkipQuestion();
} else {
que_position++;
setAnswers(que_position - 1);
setQuestion();
//Toast.makeText(parent, "mistak", Toast.LENGTH_SHORT).show();
}*/
} else {
Toast.makeText(parent, "Please Select Answer", Toast.LENGTH_SHORT).show();
//IsSelectedAnswer=false;
}
break;
}
}
"answer selection code"
private void setSelectedOption() {
try {
if(jsonArray.length()>0){
boolean isAdded=false;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject=jsonArray.getJSONObject(i);
int questionposition=jsonObject.getInt("questionposition");
if(questionposition==que_position){
isAdded=true;
IsSelectedAnswer=true;
break;
}
}
if(isAdded){
//jsonArray.remove(que_position);
}
JSONObject jsonObject=new JSONObject();
jsonObject.put("questionposition",que_position);
jsonObject.put("selectedoption",selectedOption);
jsonArray.put(jsonObject);
}else {
JSONObject jsonObject=new JSONObject();
jsonObject.put("questionposition",que_position);
jsonObject.put("selectedoption",selectedOption);
jsonArray.put(jsonObject);
}
}catch (Exception e){
e.printStackTrace();
}
}
"seleted answer send to server"
public void sendAnswers() {
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String result = gson.toJson(results);
JSONObject params = new JSONObject();
try {
params.put("PaperId", PrefHelper.getString(PrefHelper.KEY_PAPER_ID, ""));
params.put("QuestionId", QuestionId);
params.put("Answer", Answer);
params.put("StudentId", LoginHelper.getInstance().getStudent_Id());
params.put("IsSkipped", IsSkipped);
params.put("IsCorrect", IsCorrectAnswer);
RestClient.getInstance().postRequest(parent, Request.Method.POST, ApiList.APIs.submitStudentAnswer.getUrl(), params, this, RequestCode.submitStudentAnswer, true, false, "");
} catch (Exception e) {
e.printStackTrace();
}
}
"next question display"
public void setQuestion() {
if (quizzes.size() != que_position) {
setQuestionLayout();
ExamQuestion quiz = quizzes.get(que_position);
//QuizQuestionModel quiz = quizlist.get(que_position);
setQue(quiz, que_position);
Toast.makeText(parent, "yha pe", Toast.LENGTH_SHORT).show();
// que_position++;
} else {
if (results.size() > 0) {
FragmentNavigationInfo fragmentNavigationInfo = new FragmentNavigationInfo(ExamFinishFragment.newInstance(subjectName,topicName,String.valueOf(total_marks), String.valueOf(total_right_ans), String.valueOf(total_rightCount), String.valueOf(quizzes.size()), String.valueOf(total_skipped), String.valueOf(total_attempt), rightAnswers));
parent.addFragment(fragmentNavigationInfo);
//Toast.makeText(parent, "mistake", Toast.LENGTH_SHORT).show();
// sendAnswers();
}
}
}
"previ. question"
public void setPreviousQuestion() {
if (quizzes.size() != que_position) {
setQuestionLayout();
ExamQuestion quiz = quizzes.get(que_position);
//QuizQuestionModel quiz = quizlist.get(que_position);
setQue(quiz, que_position);
// que_position++;
}
}

Obtaining an array of json format question and put them into an array in android studio

The goal here is to retrieve JSON format data from an API, convert the data into an array in android studio. Then to display a random question into a text view and the question will not repeat itself. The question changes everytime a button is clicked. There's something wrong with the logic of how I use my array/parsing the data to the array. I am not sure how to proceed. Any help is appreciated
MY JSON format
{
"error": false,
"message": "Successfully retrieved",
"questions": [
{
"question": "Tell us about yourself?"
},
{
"question": "Tell us about yourself2?"
},
{
"question": "Tell us about yourself3?"
},
{
"question": "Tell us about yourself4?"
},
{
"question": "Tell us about yourself5?"
}
]
}
My code so far ( simplified to this function )
public class MainActivity extends AppCompatActivity {
// create arraylist to store question
List<String> questionList = new ArrayList<>();
// use max to decide the number of question
// use i to find out the number of questions
int i = 10;
int min = 0;
int max = i;
int[] usedInt = new int[max];
//create another array to put all the used integer inside for 0 repeition of question
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textViewQuestions = (TextView) findViewById(R.id.questionView);
usedInt = new int[i];
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
//generate random number, set textview the question, set int to usedint array
textViewQuestions.setText(questionList.get(i1));
usedInt[0] = i1;
//set first question
findViewById(R.id.changeQuestion).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(TAG,questionList[updateQuestions(usedInt)]);
//final int[] usedIntTemp = usedInt;
getQuestions();
int n = updateQuestions(usedInt);
textViewQuestions.setText(questionList.get(n));
//finish();
}
});
}
}
public int updateQuestions(int usedInteger[]) {
int min = 0;
int max = i;
Random r = new Random();
int i2 = r.nextInt(max - min + 1) + min;
int uInteger[] = usedInteger;
int l = 0;
while (l != max) {
if (i2 == usedInteger[l]) {
l++;
if (l == max) {
Toast.makeText(getApplicationContext(), "No other questions available", Toast.LENGTH_LONG).show();
}
} else {
usedInteger[usedInteger.length + 1] = i2;
return i2;
}
}
return i2;
}
private void getQuestions()
{
class GetQuestions extends AsyncTask<Void, Void, String> {
//private ProgressBar progressBar;
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("role_id", "1");
//returing the response
return requestHandler.sendPostRequest(URLs.URL_QUESTIONS, params);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
//progressBar = (ProgressBar) findViewById(R.id.progressBar);
//progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
//progressBar.setVisibility(View.GONE);
boolean Error1 = false;
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//HashMap<String, String> questionJson = new HashMap<>();
// success = obj.getBoolean("error");
if (!obj.getBoolean("error")) {
//Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the questions from the response
JSONArray questionsJson = obj.getJSONArray("questions");
//creating a new questions object
for (i = 0; i < questionsJson.length(); i++) {
JSONObject object = questionsJson.getJSONObject(i);
questionList.add(object.getString("question"));
Log.d(TAG,"objcheck");
Log.d(TAG,object.getString("question"));
//q = c.getString("question");
//questionJson.put("question", q);
//questionList.add(questionJson);
}
finish();
//startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
GetQuestions gq = new GetQuestions();
gq.execute();
}
Object[] array = new Object[10]; // say 10 objects
int remain = array.length;
Random rnd = new Random();
public Object next () {
if (remain == 0) {
return null;
} else {
int i = rnd.nextInt(remain--);
Object tmp = array[i];
array[i] = array[remain];
array[remain] = tmp;
return tmp;
}
}
This will generate next random question
I tried this, with
getQuestions();
String n = String.valueOf(next());
textViewQuestions.setText(n);
I also populated the array like this
for (i = 0; i < questionsJson.length(); i++) {
JSONObject object = questionsJson.getJSONObject(i);
array[i] = object.getString("question");
questionList.add(object.getString("question"));
Log.d(TAG,object.getString("question"));
}
However, the questions do repeat but will only show a set amount of questions. :( How to make the questions not repeat?

Retrofit - how do I make a synchronous request within an asynchronous request

I'm implementing a two-level nested recyclerView and both recycler views make an API call using retrofit. This is the method that makes the synchronous request:
public void loadSectionStories(String sessionKey, CuratedSection section) {
Call<JsonArray> subCall;
subCall = TravelersApi.endpoint().getCuratedSectionTopics(sessionKey, section.id);
try {
Response<JsonArray> response = subCall.execute();
if(response.code() != 200) {
Toast.makeText(getApplicationContext(), "Cannot load page as of the moment.", Toast.LENGTH_SHORT).show();
return;
}
JsonArray rawStories = response.body();
if(rawStories.size() == 0) {
//TODO: show placeholder
return;
}
ArrayList<CuratedSectionItem> stories = new ArrayList<>();
for(int i = 0; i < rawStories.size(); i++) {
JsonObject jStories = rawStories.get(i).getAsJsonObject();
JSONObject temp = new JSONObject(jStories.toString());
JsonObject author = jStories.get("author").getAsJsonObject();
CuratedSectionItem story = new CuratedSectionItem();
story.title = jStories.get("title").getAsString();
story.avatar = author.get("profile_photo").getAsString();
story.displayPhoto = temp.getString("primary_photo");
story.username = author.get("username").getAsString();
story.description = jStories.get("content").getAsString();
story.topicId = jStories.get("id").getAsString();
story.postId = jStories.get("first_post_id").getAsString();
story.hasReacted = false;
story.upvotes = jStories.get("stats").getAsJsonObject().get("upvotes").getAsInt();
stories.add(story);
}
section.stories = stories;
} catch (IOException e) {
Log.d("ERROR!", e.toString());
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
This is the method that makes the asynchronous request and also calls loadSectionStories in a thread:
public void loadCuratedSections(final int start, final int limit) {
SharedPreferences prefs = getSharedPreferences("user_session", MODE_PRIVATE);
final String sessionKey = prefs.getString("session_key", null);
Call<JsonArray> call;
call = TravelersApi.endpoint().getCuratedSections(sessionKey);
call.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
if(response.code() != 200) {
Toast.makeText(getApplicationContext(), "Cannot load page as of the moment.", Toast.LENGTH_SHORT).show();
return;
}
JsonArray rawSections = response.body();
if(rawSections.size() == 0) {
return;
}
for (int i = start; i < limit; i++) {
JsonObject jSection = rawSections.get(i).getAsJsonObject();
final CuratedSection section = new CuratedSection();
section.id = jSection.get("id").getAsString();
section.header = jSection.get("section_header").getAsString();
section.isShown = jSection.get("is_shown").getAsBoolean();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
loadSectionStories(sessionKey, section);
}
});
thread.start();
curatedSections.add(section);
}
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
Log.d("ERROR!", t.toString());
t.printStackTrace();
}
});
}
Everything is working fine except the fact that section.stories returns null. It doesn't make sense to me because of this statement section.stories = stories inside loadSectionStories.
If you are using section.stories before your synchronous request is completed (which is running in new threads) then it will return null which is currently happening.
so either you have to remove new thread flow if you want to use it after your first asynchronous request is completed,
or you have to reload your recycler view when you stories is updated.
Also why are you executing your synchronous request(loadSectionStories) in new thread, is it not similar to asynchronous request?
Retrofit asyncRetrofit = new Retrofit.Builder()
.baseUrl(URLS.MAIN_SERVER_URL)
// below line create thread for syncrouns request
.callbackExecutor(Executors.newSingleThreadExecutor())
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
this will run your request in asyncronous

using retrofit process of retrying going slow

I am new for retrofit and I am using it and I have implemented in activity directly not inside thread and when I am starting then it taking lot of time and blocking User Interface also and after getting response and when I hit again same by restarting activity It wait unlimited time. It is being stuck on same request.
I have an activity and having three fragment and using pager so firstly I am hitting web-service inside activity and using call back updating my recycler view adapter
retrofit = new Retrofit.Builder().baseUrl("xyz.co.in/").addConverterFactory(GsonConverterFactory.create()).build();
app = retrofit.create(ApiInterface.class);
Call<List<Pojo>> listCall = app.getDetails();
sb = new StringBuffer("xyz.co.in/api/api.php?api=user&ver=1.0&key=56F353E05208C8E&cmd=OBJECT_GET_LOCATIONS");
sb.append(",");
listCall.enqueue(new Callback<List<Pojo>>() {
#Override
public void onResponse(Response<List<Pojo>> response, Retrofit retrofit) {
final ArrayList<Pojo> list = (ArrayList<Pojo>) response.body();
for (int i = 0; i < list.size(); i++) {
if (i == 0)
sb.append("" + list.get(i).getImei());
else
sb.append(";" + list.get(i).getImei());
}
Ion.with(MainActivity.this).load(sb.toString())
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
if (e != null)
Toast.makeText(getApplicationContext(), "Error : " + e.toString(), Toast.LENGTH_SHORT).show();
else {
try {
list_pojo = new ArrayList<>();
address_description = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
JsonObject jsonObject = result.getAsJsonObject(list.get(i).getImei().toString());
list_pojo.add(new Imei_Pogo(jsonObject.get("dt_server").getAsString(), jsonObject.get("dt_tracker").getAsString(), jsonObject.get("lat").getAsDouble(), jsonObject.get("lng").getAsDouble(), jsonObject.get("altitude").getAsString(), jsonObject.get("angle").getAsString(), jsonObject.get("speed").getAsInt()));
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
addresses = geocoder.getFromLocation( jsonObject.get("lat").getAsDouble(), jsonObject.get("lng").getAsDouble(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
address_description.add(address + "," + city + "," + state + "," + country + "-" + postalCode);
}
// new MyDataBase(getApplicationContext()).insertData(list,list_pojo,address_description);
callback.updateUI(list, list_pojo,address_description);
dialog.dismiss();
} catch (Exception g) {
g.printStackTrace();
}
finally {
if(dialog.isShowing())
dialog.dismiss();
}
}
}
});
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_SHORT).show();
}
});

Check if new value is same as the old value

I'm getting few values from a web service. The values keep changing every time I get the value from web service. I use a TimerTask in Serviceto get the values repeatedly.
I can't think of how to check if the value I got is the same as before.
public ArrayList getCo_ordinates(String deviceId) {
String URL_CO_ORDINATES = "http://192.168.1.42:8080/image/getDevicePosition?deviceId=" + deviceId;
// trimCache(getApplicationContext());
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
final JsonArrayRequest request = new JsonArrayRequest(URL_CO_ORDINATES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
// tap();
addTap(Integer.parseInt(X), Integer.parseInt(Y));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,""+e,Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Could Not connect to server", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(request);
return null;
}
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
if(prev_x==X)
{
Log.d("same","value");
}
else
{
Log.d("different","value");
}
prev_x=X;
prev_y=Y;

Categories

Resources