获取android studio项目的JSON数据

pod7payv  于 11个月前  发布在  Android
关注(0)|答案(2)|浏览(209)

所以,我试图从一个pastebin JSON文件中获取数据。之后我需要将其放在一个listView中。但是有些东西是关闭的。我在main中执行方法,我可以使onPreExecute工作,但不能使onPostExecute工作。有人知道这是如何工作的吗?

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();
    }
}

字符串
这是我的ExtactJSON类。

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");
        }
    }

}

6jygbczu

6jygbczu1#

我已触发您的URL https://pastebin.com/raw/vVBcgK7H
它在下面给出了响应,格式不正确

"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"
    }

字符串
请更新您的数据,以回应此

{
  "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"
    }
  ]
}


它可能会解决您的问题,因为您没有从pastBin URL中获得格式化的数据

a5g8bdjr

a5g8bdjr2#

处理这样的错误:

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

字符串
在onPostExecute方法中,添加一些日志语句来检查是否正在调用它以及s变量的内容是什么。

@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);
    }
}

相关问题