Why am I getting duplicates when combining multiple ArrayLists? - java

Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}

Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.

Related

How to apply for loop on first n vlalues of arraylist

I have an arraylist in which I have ESSID, BSSID, Strenght of access Point on first three indexes, and from Index 4 to 6 I have again ESSID, BSSID, Strength of another AccessPoint. I want to store this list in database like first three values save in one row of table. and next three values save in 2nd row of table.
String[] namesArr = new String[arrayList2.size()]; //conver arraylist to array
for (int j = 0; j < arrayList2.size(); j++){
namesArr[j] = arrayList2.get(j);
int length = namesArr[j].length();
for (int k = 0; k < length; k += 3) {
ssid = namesArr[k];
bssid = namesArr[k + 1];
rssid = namesArr[k + 2];
}
insertValues(this);
}
public void insertValues(View.OnClickListener view){
SendData send = new SendData(this);
send.execute(bssid,ssid,rssid);}
I have made a class to store this data in database that works fine.
public class SendData extends AsyncTask<String, Void, String> {
AlertDialog dialog;
Context context;
public SendData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String data = "";
String result = "";
String MAC = voids[0];
String Name = voids[1];
String Strength = voids[2];
String con_Str = "http://10.5.48.129/Webapi/accesspoints_data/create.php";
try{
URL url = new URL(con_Str);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream out_Stream = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_Stream, "UTF-8"));
JSONObject obj = new JSONObject();
try {
obj.put("BSSID", MAC);
obj.put("ESSID", Name);
obj.put("RSSID", Strength);
} catch (JSONException e) {
e.printStackTrace();
}
data = obj.toString();
writer.write(data);
writer.flush();
writer.close();
out_Stream.close();
InputStream in_Stream = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in_Stream, "ISO-8859-1"));
String line = "";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
in_Stream.close();
http.disconnect();
return result;
} catch (MalformedURLException e){
result = e.getMessage();
} catch (IOException e){
result = e.getMessage();
}
return result;
}
}
SendData class is perfectly working but problem is with for loop.
I think this is result that you are expecting :
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("1");
arrayList2.add("2");
arrayList2.add("3");
arrayList2.add("4");
arrayList2.add("5");
arrayList2.add("6");
arrayList2.add("6");
arrayList2.add("7");
arrayList2.add("8");
arrayList2.add("9");
arrayList2.add("10");
List<String[]> sarrayList = new ArrayList<>();
String[] arr = new String[3];
int i = 0;
for (int j = 0; j < arrayList2.size(); j++)
{
arr[i] = arrayList2.get(j);
i++;
if((j+1)%3==0)
{
sarrayList.add(arr);
i = 0;
arr = new String[3];
}
}
for(String [] sa:sarrayList)
{
for(String s:sa)
{
System.out.println(s);
}
System.out.println("=========");
}
This might not be the most efficient way of doing it. But it splits the ArrayList in to String arrays of length=3 and stores them in a new ArrayList named sarrayList
I would advise to use a datastructure to hold the record. See the code below this is a small example how you could do it
ArrayList<Record> records;
for (int i = 2; i < inputArrayList.size(); i = i + 3){
string ssid = namesArr.get(i - 2);
string bssid = namesArr.get(i - 1);
string rssid = namesArr.get(i);
records.add(new Record(ssid, bssid, rssid));
}
class Record{
string ssid;
string bssid;
string rssid;
// Constructor...
// Getter and setter to be implemented...
}
ok from what i understand you want to divide the arraylist each 3 elements thats how you do it with streams and it will return an a collection of arraylists each one has 3 elements
final int chunkSize = 3;
final AtomicInteger counter = new AtomicInteger();
//arrayList here us your array list
final Collection<List<String>> result = arrayList.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
and mentioning supermar10 answer you code make a class to map the strings to it like that
class Record{
string ssid;
string bssid;
string rssid;
Record(String ssid,String bssid,String rssid){
this.ssid=ssid;
this.bssid=bssid;
this.rssid=rssid;
}
}
now you have a class to map to now save the records in a list of Record
create a a list in the main class
static List<Record> lists=new ArrayList<>();
then map the data like that
result.stream().forEach(nowList -> saveRecord(nowList));
and thats the save method
static void saveRecord(List<String> list){
lists.add(new Record(list.get(0),list.get(1),list.get(2)));
}
I have simplified it to one loop and also modified insertValues so that it takes 3 more parameters. This
int size = arrayList2.size();
for (int j = 0; j < size; j += 3) {
if (size - j < 3 ) {
break;
}
String ssid = arrayList2.get(j);
String bssid = arrayList2.get(j + 1);
String rssid = arrayList2.get(j + 2);
insertValues(this, ssid, bssid, rssid);
}
if one the other hand ssid and so on are class variables the inside of the loop can be changed to
ssid = arrayList2.get(j);
bssid = arrayList2.get(j + 1);
rssid = arrayList2.get(j + 2);
insertValues();

android JSONException index 1 out of range [0..1] (Parse 2 json arrays inside 1 loop)

I have code like this, the value of jArrAnswer is
[{"answer":"Yes"},{"answer":"No"},{"answer":"maybe"},{"answer":"yrg"}]
the result from jArrAnswer.length() is 4
but why I got error
org.json.JSONException: Index 1 out of range [0..1).
try {
JSONArray jArrAnswerid = new JSONArray(answerid);
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswerid = jArrAnswerid.getJSONObject(i);
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswerid.getString("answerid");
String ans= jObjAnswer.getString("answer");
GroupModel item2 = new GroupModel(String.valueOf(i + 1), ans, ansid);
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
You are iterating the for loop over jArrAnswer while your fetching the index i over jArrAnswerid.
Check and make sure that the jArrAnswerid.size() is equal to the jArrAnswer.size().
Print the jArrAnswerid.size() and check.
Try this
try {
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswer.getString("answerid");
String ans= jObjAnswer.getString("answer");
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
provided "answer" is your json array response
Try
String json = "[{\"answer\":\"Yes\",\"answerid\":\"1\"},{\"answer\":\"No\",\"answerid\":\"2\"},{\"answer\":\"maybe\",\"answerid\":\"3\"},{\"answer\":\"yrg\",\"answerid\":\"4\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String answerId = jsonObject.getString("answerid");
String answer = jsonObject.getString("answer");
//Use answerId and answer
}
}
} catch(JSONException e) {
e.printStackTrace();
}

Detect and Remove duplicates in ArrayList?

I have an array with 2 positions, each one contains a list of "ids_alunos", the first position has ids_alunos: "1,2,3" and the second:"4,5" but what is happening when I add the ids in my array is this, the first position gets "1,2,3" values and the second: "1,2,3,4,5". why is this happening?
public ArrayList<CadastraEscolas> getFilhos(String mToken) throws Exception {
String[] resposta = new WebService().get("filhos", mToken);
if (resposta[0].equals("200")) {
JSONObject mJSONObject = new JSONObject(resposta[1]);
JSONArray dados = mJSONObject.getJSONArray("data");
mArrayList = new ArrayList<CadastraEscolas>();
mGPSList = new ArrayList<GPSEscolas>();
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i).getJSONObject("escolas");
JSONArray escolas = item.getJSONArray("data");
for (int j = 0; j < escolas.length(); j++) {
JSONObject jItens = escolas.getJSONObject(j);
mCadastraEscolas = new CadastraEscolas();
mGPSEscolas = new GPSEscolas();
mCadastraEscolas.setId_escola(jItens.optInt("id_escola"));
mGPSEscolas.setId_escola(jItens.optInt("id_escola"));
JSONObject alunos = jItens.optJSONObject("alunos");
JSONArray data = alunos.getJSONArray("data");
if (data != null) {
ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>();
for (int a = 0; a < data.length(); a++) {
mFilhos = new Filhos();
JSONObject clientes = data.getJSONObject(a);
mFilhos.setId_aluno(clientes.optInt("id_aluno"));
arrayalunos.add(mFilhos);
idsAlunos += ";" + arrayalunos.get(a).getId_aluno().toString();
mGPSEscolas.setIds_alunos(idsAlunos);
}
mCadastraEscolas.setalunos(arrayalunos);
}
mArrayList.add(mCadastraEscolas);
mGPSList.add(mGPSEscolas);
}
}
return mArrayList;
} else {
throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]);
}
}
You probably want to initialize idsAlunos at the same time as mGPSEscolas, so where you do:
mGPSEscolas = new GPSEscolas();
you could also do:
idsAlunos = "";
otherwise idsAlunos gets appended to with every new mGPSEscolas.

How to convert java arraylist to json array store data using java and jsp and extjs

is there any way to convert array list to json store input data using jsp and java for extjs.
means i need to get data for json store from jsp page and java arraylis
Here you go hope this helps you... Here im getting state values from db..
String response = "id,State#";
List stateList = new ArrayList<>();
//DB call
for (int i = 0; i < stateList.size(); i++) {
response += stateList.get(i).gets_code() + ",";
response += stateList.get(i).getS_name() + "#";
}
StringTokenizer st = new StringTokenizer(response , "|");
String finalMsg = null;
String str1 = null;
while (st.hasMoreElements()) {
String token = st.nextToken();
finalMsg = token;
}
JSONObject object = new JSONObject();
stbuffer.append("{\"root\":[");
String[] data = finalMsg.split("#");
int len = data.length;
String[] headings = data[0].split(",");
for (int x = 1; x < len; x++) {
String[] data1 = data[x].split(",");
int len1 = data1.length;
for (int y = 0; y < len1; y++) {
object.put(headings[y], data1[y]);
}
stbuffer.append(object);
stbuffer.append(",");
}
stbuffer.append("]}");
String result = stbuffer.toString();
result = result.replace(",]", "]");

Android: ArrayIndexOutOfBoundsException when parsing JSON Array

Forgive for I am new to Android and a novice at Java. I am trying to create a dynamic list view using data from a MySQL server. However, sometimes a query returns only one result. When my adapter class parses a JSONArray with one element to a String array, I receive an ArrayIndexOutOfBoundsException. How do I avoid using an empty string in my resultArray to compensate for the exception? I don't want to use the empty string because it will still be selectable within the listview.
Parsing code:
try
{
jArray = new JSONArray(result);
// Taking a peek at the contents
Log.e("log_tag", jArray.getJSONObject(0).getString(queryID));
//For some reason if I don't do this
// I get ArrayIndexOutOfBoundsException.
if (jArray.length() == 1)
{
resultArray = new String[2];
resultArray[1] = "";
}
else
resultArray = new String[jArray.length()];
for(int i = 0; i < jArray.length(); i++)
{
resultArray[i] = jArray.getJSONObject(i).getString(queryID);
}
}
catch(JSONException e)
{
throw new NullResultFromServerException("No results from server.");
}
for(int i = 0; i < jArray.length(); i++)
{
String empty= jArray.getJSONObject(i).getString(queryID);
empty=empty.trim(); //this will remove the blank white space
if(!empty.equalsIgnoreCase(""))
resultArray[i] = empty;
}

Categories