How do I get a JSon from AsynTask on android?

5

This is my function:

public class JSONRequest extends AsyncTask <String, Void, JSONObject>{

private JSONCallback activity;

public JSONRequest(JSONCallback activity){
    this.activity = activity;
}

@Override
protected JSONObject doInBackground(String... params) {
    JSONObject result = null;

}

protected void onPostExecute(JSONObject jsonObject) {
    super.onPostExecute(jsonObject);
    activity.callBack(jsonObject);
}

What is missing?

    
asked by Juan Pablo 19.10.2016 в 03:42
source

10 answers

3

You need to read the file and convert it to JSON .

Example:

JSONObject json;
URL url = new URL("url");
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.connect();

InputStream is = conexion.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

StringBuilder sb = new StringBuilder();
String linea = "";

while ((linea = br.readLine()) != null){
      sb.append(linea);
}
json = new JSONObject(sb.toString());

This code goes inside the function doInBackground , and the only thing that you have to return is the JSON .

    
answered by 19.10.2016 в 04:06
3

Juan Pablo, checking your code, within doInBackground() of your Asynctask you get a String (surely a .json) from which you will get a JSONObject which will be sent to onPostExecute() :

public class JSONRequest extends AsyncTask <String, Void, JSONObject>{

private JSONCallback activity;

public JSONRequest(JSONCallback activity){
    this.activity = activity;
}

@Override
protected JSONObject doInBackground(String... params) {
    //Recibe un String en formato .json y obtiene un JSONObject.
    JSONObject result = null;

}

protected void onPostExecute(JSONObject jsonObject) {
    //Recibe el JSONObject obtenido en doInBackground().
    super.onPostExecute(jsonObject);
    activity.callBack(jsonObject);
}

Based on the above we will focus on the method doInBackground() , here the question is what is the JSON object you want to obtain, in advance you need to know the name to obtain it, for example let's say your JSONObject is called "datos" :

@Override
protected JSONObject doInBackground(String... params) {
    //Recibe un String en formato .json y obtiene un JSONObject.
    JSONObject data = params[0].getJSONObject("datos");
    //JSONObject result = null;    
}

I consider your question a bit broad, add an example of what you need, regularly a parameter to initialize your Asynctask should be the url of the Json file and from this you get either JSONObject or% JSONArray , This is an example:

    class JSONParser extends AsyncTask<String, Void, JSONObject>{

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    String url;
    List<NameValuePair> params;

    public JSONParser(String url, List<NameValuePair> params) {
        this.url = url;
        this.params = params;
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
                Log.e("JSON", json);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
            }

            // Parsea el string a JSONobject.
            try {
                jObj = new JSONObject(json);            
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // retorna el objeto JSON.
            return jObj;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);
        activity.callBack(jsonObject);
    }

}
    
answered by 20.10.2016 в 00:12
1

Use the following variables and within OnCreate

private ArrayList<Objeto> Obj;
private Blank_Frangment fragment;

fragment=(Blank_Fra) getFragmentManager().findFragmentById(R.id.fragment);

You can use the JSON function directly from the callback where you will implement it and in the onCreate

try {
        Obj = new ArrayList<E>();
        JSONArray arreglo = jo.getJSONArray("result");
        for (int i = 0; i < arreglo.length(); i++){
            JSONObject objecto = arreglo.getJSONObject(i);
            Clase objetito = new Clase(objecto.getString("Nombre"));
            Obj.add(objetito);
        }
    }catch (Exception e){
    }

    fragment.AgarraArray(Obj);

And you use this function where you have the list

 public void AgarraArray(ArrayList<E> Obj){
    MyAdapter adapter = new MyAdapter(getActivity(),Obj);
    lista.setAdapter(adapter);
}

And remember that it extends the functions that you need to use by default to be able to modify

MainActivity extends AppCompatActivity implements Blank_Frangment.OnFragmentInteractionListener, JSONCallback

JSONRequest extends AsyncTask <String, Void, JSONObject>

MyAdapter extends BaseAdapter
    
answered by 19.10.2016 в 18:28
1

You need to know the basics of AsyncTask, this will help you

public class JSONRequest extends AsyncTask <String, Void, JSONObject>{

private JSONCallback activity;

public JSONRequest(JSONCallback activity){
    this.activity = activity;
}

@Override
protected JSONObject doInBackground(String... params) {
    String json; //Lectura de tu json
    try {
        return new JSONObject(json);
    } catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}

protected void onPostExecute(JSONObject jsonObject) {
    if(jsonObject) {
        activity.callBack(jsonObject);
    } else {
        activity.callError("El json no se ha podido leer");
    }
}

and you call it that way

new JSONRequest(JSONActivity.this).excecute();

To read your json it would already depend on where you got it from, a file or an API that returns a json

I would recommend that you do not use AsyncTask for communication with an API or go for content specific to the network, in Android best practices recommend the use of the library called Retrofit

    
answered by 19.10.2016 в 22:16
0

Once, this code has been implemented to be able to create the connection within the app, it is very important to have it in your Manifest XML

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

and where you want to send the request in the following way

request = new JSONRequest(this); request.execute("pagina");

    
answered by 19.10.2016 в 09:17
0

Just remember that in your main activity you have to send it to call with:

nombre_clase clase = new nombre_clase(actividad);
clase.excute("url");

Once you send it to call in a function so that I do the request and you have to manage your JSONobject with the callback function.

    
answered by 19.10.2016 в 09:29
0

If you want to grab a local file from a folder it is:

try{
        AssetManager manager = getApplicationContext().getAssets();
        InputStream is = manager.open("archivo.txt");
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String currentLine;
        while((currentLine = br.readLine()) != null){
            textres.setText(currentLine);
        }
    }catch (Exception e){
        e.printStackTrace();
    }

And here's how you can read a file from your raw directory

try{
        InputStream is = getResources().openRawResource(R.raw.saludo);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        String currenLines;
        currenLines = br.readLine();
        textraw.setText(currenLines);
        is.close();
    }catch (Exception e){
        e.printStackTrace();
    }
    
answered by 19.10.2016 в 19:32
0

The getView of an adapter is the following:

public View getView(int position, View convertView, ViewGroup parent) {

    if(convertView==null){
        convertView=activity.getLayoutInflater().inflate(R.layout.row,null);
    }

    TextView nombre = (TextView) convertView.findViewById(R.id.NombreTextView);
    TextView hobby = (TextView) convertView.findViewById(R.id.hobbyTextView);

    nombre.setText(amigos.get(position).getNombre());
    hobby.setText(amigos.get(position).getHobby());

    return convertView;
}
    
answered by 19.10.2016 в 19:34
0

If you want to make a properties file

private final String FILENAME = "name.xml";

Properties properties;


File file = new File(getFilesDir(), FILENAME);
properties = new Properties();

try{
        if(file.exists()){
            // load values on properties object
            FileInputStream fis = openFileInput(FILENAME);
            properties.loadFromXML(fis);
            fis.close();
        } else {
            save();
        }

    }catch(Exception e){
        e.printStackTrace();
    }

public void save() throws Exception {
    saveProperties();
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    properties.storeToXML(fos, null);
    fos.close();
}

public void saveProperties(){
    properties.setProperty("usuario", inputtext.getText().toString());
}
    
answered by 19.10.2016 в 19:39
0

In the Adapter lacking

ArrayList c;     Activity activity;

public MyAdapter(ArrayList<Clase> c , Activity activity) {
    this.c = c;
    this.activity = activity;
}
    
answered by 19.10.2016 в 19:45