I would like to read data from a URL (JSON format) and add these values to the an ArrayList
.
I tested the reading from the URL part and this works. But for some reason I can't add the value that I read to the ArrayList
Anyone has an idea why this happens and how I could fix it?
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class SaldoActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private ArrayList<String> names;
private ArrayList<Integer> payList;
private ArrayList<Integer> totalList;
private ArrayList<Integer> debtList = new ArrayList<Integer>();
private int offset = 1;
private String email;
private int previousID;
private int loginID;
private int totalPerPerson;
private int info;
private static final String GET_LAST_URL = "https://studev.groept.be/api/a21pt120/getPreviousIDFromGroup/";
private static final String QUEUE_URL_LOGIN_ID = "https://studev.groept.be/api/a21pt120/getLoginID/";
private static final String GET_PAY_AMOUNT_PER_NAME = "https://studev.groept.be/api/a21pt120/payedPerPerson/";
private static final String GET_TOTAL_AMOUNT = "https://studev.groept.be/api/a21pt120/totalPayed/";
@Override
protected void onCreate(Bundle savedInstanceState) {
//READING FROM DATABASE DOESNT WORK -> SOMETHING ABOUT THE ARRAYLIST
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saldo);
getPayList();
Bundle extras = getIntent().getExtras();
email = (String) extras.get("email");
names = GroupActivity.getNamesList();
//######## TRANSACTIONS ###########
Button newTransaction = findViewById(R.id.button3);
newTransaction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onAddTransaction_Clicked();
}
});
//##################################
ListView saldoList = findViewById(R.id.saldoList);
TextView lblGroup = findViewById(R.id.lblGroup);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, names);
saldoList.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
//######### DELETE BUTTON ###########
JsonArrayRequest loginIDRequest = new JsonArrayRequest(Request.Method.GET, QUEUE_URL_LOGIN_ID email,null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length(); i) {
loginID = 0;
JSONObject o = null;
try {
loginID = response.getJSONObject(i).getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
JsonArrayRequest previousIDRequest = new JsonArrayRequest(Request.Method.GET,GET_LAST_URL Integer.toString(loginID),null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length(); i) {
previousID = 0;
JSONObject o = null;
try {
previousID = response.getJSONObject(i).getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
Toast.makeText(SaldoActivity.this, "Unable to communicate with the server", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(previousIDRequest);
}
}, new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
Toast.makeText(SaldoActivity.this, "Unable", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(loginIDRequest);
calculateTotalPerPerson();
calculateDebtList();
lblGroup.setText(Integer.toString(payList.get(0)));
saldoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int amount = debtList.get(i);
Toast.makeText(SaldoActivity.this, Integer.toString(amount), Toast.LENGTH_LONG).show();
}
});
}
public void onAddTransaction_Clicked() {
Intent intent = new Intent(this, AddTransaction.class);
startActivity(intent);
}
public void onDeleteGroup_Clicked(View caller) throws InterruptedException {
if(previousID == GroupActivity.getID()){
offset ;
}
String url = "https://studev.groept.be/api/a21pt120/deleteGroup/" GroupActivity.getID();
httpCall(url);
String url_offset = "https://studev.groept.be/api/a21pt120/deleted_input/" offset;
httpCall(url_offset);
Intent intent = new Intent(this, GroupActivity.class);
timeout();
intent.putExtra("email", email);
startActivity(intent);
}
private void calculateDebtList() {
for(int i = 0; i < payList.size(); i ){
int debt = payList.get(i) - totalPerPerson;
debtList.add(debt);
}
}
private void calculateTotalPerPerson() {
if(names.size() > 0) {
totalPerPerson = calculateSum()/names.size();
}
else{
totalPerPerson = calculateSum();;
}
}
private int calculateSum() {
int sum = 0;
for(int i = 0; i < totalList.size(); i )
sum = totalList.get(i);
return sum;
}
private void timeout() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void getPayList(){
RequestQueue requestQueue = Volley.newRequestQueue(GroupActivity.returnContext());
String url = GET_PAY_AMOUNT_PER_NAME GroupActivity.getID();
StringRequest submitRequest = new StringRequest(Request.Method.GET, url,
response -> {
try {
JSONArray responseArray = new JSONArray(response);
payList = new ArrayList<>();
for(int i = 0; i<responseArray.length(); i ) {
JSONObject curObject = responseArray.getJSONObject(i);
payList.add(curObject.getInt("totalPerPerson"));
}
}
catch (JSONException e)
{
Log.e("Error", e.toString());
}
},
error -> Log.e("Error", "Could not reach database"));
requestQueue.add(submitRequest);
}
}
I want to add the int values into the payList. But the add()
doesn't do the trick.
When I try to get the first element form the paylist with lblGroup.setText(Integer.toString(payList.get(0)));
(there should be 3 in it for the example I used), the app crashes because there are no elements in the paylist.
This is the JSON I get from the URL. I would like to have the values 200, 3, 10 in an ArrayList
named payList
[ { "totalPerPerson": "200" }, { "totalPerPerson": "3" }, { "totalPerPerson": "10" } ]
CodePudding user response:
I think you are directly trying to add string number value to Int Array payList
so first cast to Parse int using Integer.parseInt()
try below code this may help
try {
JSONArray responseArray = new JSONArray(response);
payList = new ArrayList<>();
for(int i = 0; i<responseArray.length(); i ) {
JSONObject curObject = responseArray.getJSONObject(i);
payList.add(Integer.parseInt(curObject.getInt("totalPerPerson"))); //check here
}
}
catch (JSONException e)
{
Log.e("Error", e.toString());
}