skip to Main Content

So, i am trying to get the data from a pastebin JSON file. i need to have it in a listView afterwards. But something is off. I the execute method in main i can make the onPreExecute work but not the onPostExecute. Does anyone have any idea how this works?

 public void onClick(View view) {

            ExtragereJSON extragereJSON=new ExtragereJSON(){
                ProgressDialog progressDialog;

                @Override
                protected void onPreExecute() {
                    progressDialog=new ProgressDialog(Proba_Practica_Petrescu_Rares_Mihnea.this);
                   progressDialog.setMessage("Please wait...");
                    progressDialog.show();
                }

                @Override
                protected void onPostExecute(String s) {
                    //progressDialog.setMessage("Done...");
                    //progressDialog.show();
                    progressDialog.cancel();
                    if (s != null) {
                        listaInregistrari.addAll(this.listaRestaurante);
                       // CustomAdapter adaptorNou = new CustomAdapter(getApplicationContext(), R.layout.listviewrestaurante_layout,
                               // getLayoutInflater(), listaInregistrari);
                        Log.d("AsyncTask", "onPostExecute: JSON extraction successful");
                    } else {
                        // Handle the case where the JSON extraction failed
                        // Log or display an error message
                        Log.e("AsyncTask", "onPostExecute: Failed to extract JSON");
                    }
                }
            };
            try{
                extragereJSON.execute(new URL("https://pastebin.com/raw/vVBcgK7H"));
            } catch (MalformedURLException e) {
                Log.e("URLValidationError", "Malformed URL: " + e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                // Log or display a general error message
                Log.e("ExtractionError", "Failed to extract JSON: " + e.getMessage());
                e.printStackTrace();
            }
        }
    });

OK, here is my ExtactJSON class.

public class ExtragereJSON extends AsyncTask<URL,Void,String> {

public List<InregistrareRestaurant> listaRestaurante=new ArrayList<>();
@Override
protected String doInBackground(URL... urls) {

    try {
        HttpURLConnection connection=(HttpURLConnection) urls[0].openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream=connection.getInputStream();

        InputStreamReader isr=new InputStreamReader(inputStream);
        BufferedReader br=new BufferedReader(isr);
        String line=null;
        String rezultat="";
        while((line=br.readLine())!=null)
            rezultat+=line;
        parsareJSON(rezultat);

        return rezultat;
    } catch (IOException e) {
        Log.e("AsyncTask", "Exception in doInBackground: " + e.getMessage());
        return null; // Return null or an error message
    }
}
private void parsareJSON(String result){

    if(result!=null){
        try{
            JSONObject obiect=new JSONObject(result);

                JSONArray restaurante = obiect.getJSONArray("restaurante");
                for (int i = 0; i < restaurante.length(); i++) {
                    JSONObject restaurant = restaurante.getJSONObject(i);
                    int codRestaurant = restaurant.getInt("codRestaurant");
                    String numeRestaurant = restaurant.getString("numerestaurant");
                    int capacitate = restaurant.getInt("capacitate");
                    float venituri = (float) restaurant.getDouble("venituri");
                    String tipRestaurant = restaurant.getString("tipRestaurant");
                    InregistrareRestaurant ir = new InregistrareRestaurant(codRestaurant, numeRestaurant, capacitate, venituri, tipRestaurant);
                    listaRestaurante.add(ir);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    else
    {
        Log.e("parsareJSON","JSON este null");
    }
}

}

2

Answers


  1. I’ve triggered your URL https://pastebin.com/raw/vVBcgK7H

    it gives response below, which is in incorrect format

      "restaurante": [
        {
          "codRestaurant": 1,
          "numerestaurant": "Restaurant A",
          "capacitate": 50,
          "venituri": 5000.0,
          "tipRestaurant": "CHINEZESC"
        },
        {
          "codRestaurant": 2,
          "numerestaurant": "Restaurant B",
          "capacitate": 80,
          "venituri": 8000.0,
          "tipRestaurant": "CHINEZESC"
        },
        {
          "codRestaurant": 3,
          "numerestaurant": "Restaurant C",
          "capacitate": 30,
          "venituri": 3000.0,
          "tipRestaurant": "MEXICAN"
        }
    

    Please update your data in response to this

    {
      "restaurante": [
        {
          "codRestaurant": 1,
          "numerestaurant": "Restaurant A",
          "capacitate": 50,
          "venituri": 5000.0,
          "tipRestaurant": "CHINEZESC"
        },
        {
          "codRestaurant": 2,
          "numerestaurant": "Restaurant B",
          "capacitate": 80,
          "venituri": 8000.0,
          "tipRestaurant": "CHINEZESC"
        },
        {
          "codRestaurant": 3,
          "numerestaurant": "Restaurant C",
          "capacitate": 30,
          "venituri": 3000.0,
          "tipRestaurant": "MEXICAN"
        }
      ]
    }
    

    It might solve your issue, because you didn’t get formatted data in response from your pastBin url

    Login or Signup to reply.
  2. handle errors like this:

    } catch (IOException e) {
        Log.e("AsyncTask", "Exception in doInBackground: " + e.getMessage());
        return "Error: " + e.getMessage(); // Return an error message
    }
    

    In your onPostExecute method, add some log statements to check whether it’s being called and what the content of the s variable is.

    @Override
    protected void onPostExecute(String s) {
        progressDialog.cancel();
        Log.d("AsyncTask", "onPostExecute: Result - " + s);
    
        if (s != null && !s.startsWith("Error")) {
           
            listaInregistrari.addAll(this.listaRestaurante);
            Log.d("AsyncTask", "onPostExecute: JSON extraction successful");
        } else {
            // Handle the case where the JSON extraction failed
            // Log or display an error message
            Log.e("AsyncTask", "onPostExecute: Failed to extract JSON - " + s);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search