Get Array list with JSON in android studio

1

I have a problem that takes several hours to bother me.

I have a dialog that is based on notifying if there is a new version of the application and sends a message with the available version along with the changes in it.

I have this code:

public class MainActivity extends AppCompatActivity {

private static  String url = "laruta/version.json";
String VersionUpdate;
String Cambios;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new VersionCheck().execute();
}
private class VersionCheck extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        String jsonStr = sh.makeServiceCall(url);
        if (jsonStr != null){
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray obtener = jsonObj.getJSONArray("Obtener");
                for (int i = 0; i < obtener.length(); i++)
                {
                    JSONObject v = obtener.getJSONObject(i);
                    VersionUpdate = v.getString("version");
                    Cambios = v.getString("cambios");
                }
            }catch (final JSONException e) {

                // Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Toast.makeText(getApplicationContext(),
                                "El formato de JSON esta errado: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {



            //Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "El servidor de comprobar versión esta caido.",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
        return null;
    }

        @Override
        protected void onPostExecute (Void result){

        if (VersionUpdate != null) {

        super.onPostExecute(result);
        String VersionName = BuildConfig.VERSION_NAME;
        if (VersionUpdate.equals(VersionName)) {
            Toast.makeText(getApplicationContext(),
                    "Version actual: " + VersionName,
                    Toast.LENGTH_LONG)
                    .show();
        } else {

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Actualización");
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setMessage("Nueva versión disponible" + "\n" + "Incluye: " + Cambios + "\n" + "Version disponible: " + VersionUpdate)
                    .setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            final String appName = getPackageName();

                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
                            } catch (android.content.ActivityNotFoundException anfe) {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
                            }

                            finish();

                        }
                    });

            AlertDialog alert = builder.create();
            alert.show();


            }
        }
    }
}

}

And I have the JSON format on a web to read it this would be:

{
"Obtener": [
   {
   "version": "1.2",
 "cambios": [ 
   "fox1",
   "fox2",
   "fox3",
   "fox4",
   "fox5",
   "fox6",
   "fox7",
   "fox8",
   "fox9",
   "fox10"
   ]
 }
]	
}	

Everything is fine! However, there is a json reading that is not appropriate and it sends me this message like this:

Where we see in the JSON format is the array "changes" with a list fox1 fox2 ...

then it does not do the reading correctly since the whole list leaves in a single line together with "" and the, so it should only show the list separated by lines without "" and, example:

Nueva version disponible
Incluye:
Fox1
Fox2
Fox3
Fox4
Fox5
Fox6
Fox7
Fox8
Fox9
Fox10
Versión disponible: 1.2

Thanks in advance for your answers: D

    
asked by Luis Rivas 06.05.2018 в 04:57
source

2 answers

0

Edit 06/05/2018.

The problem is solved, I went to ask in the English page of the same. In the future maybe another person is looking for this solution, here it is:

  

That is because you are casting JSONArray into a String object. you   JSONArray to String

Cambios = "";
JSONArray cambiosArr = v.getJSONArray("cambios");
for (int j = 0; j < cambiosArr.length(); j++) {
    Cambios += cambiosArr.getString(j) + "\n";
}
     

instead of your following line

Cambios = v.getString("cambios");

    
answered by 06.05.2018 / 07:44
source
0

You must first create a model of the object according to the JSON object, for example:

import java.util.List;

public class Obtener {
private String version;

private List<String> cambios = null;


public String getVersion() {
return version;
}

public void setVersion(String version) {
this.version = version;
}

public List<String> getCambios() {
return cambios;
}

public void setCambios(List<String> cambios) {
this.cambios = cambios;
}

}

Then you use the JSON instance to recover the complete object based on the class mentioned: "Get":

I use this library: link

If you want to add it in serious build.gradle:
compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'

Gson gson = new Gson();
Obtener resultado=gson.fromJson(json,Obtener.class);

This gives you the object as such which you can retrieve the data you want, for example if I just want to get the serious version:

Log.i("version",resultado.getVersion());

If I want to go through the list of channels that you have, it would be:

for (String canal: resultado.getcambios()){
 //hago lo que quiera con cada canal, toast o Dialog
}
    
answered by 06.05.2018 в 05:32