简体   繁体   中英

Could not display data from json in listview java and android.os.asynctask is deprecated

I got a problem when i want showing data with json from android with java it showing nothing in here

没有数据

But from json generator its fine here is the example of json http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2

and here is my MainActivity.java

package com.example.callapi;


import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.AsyncTask;

import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private static String url = "http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2";
    ArrayList<HashMap<String,String>> bookList;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listview);
        bookList = new ArrayList<>();
    }

    private class getBooks extends AsyncTask<Void, Void,Void> {
        @Override
        protected void onPostExecute(Void aVoid){
         super.onPostExecute(aVoid);

         if(progressDialog.isShowing())
         {
             progressDialog.dismiss();
         }
            ListAdapter listAdapter = new SimpleAdapter(MainActivity.this, bookList,R.layout.item,new String[]{"book_name"},new int[]{R.id.book_name});

         listView.setAdapter(listAdapter);
        }
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Loading.....");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
        @Override
        protected Void doInBackground(Void... voids){
            Handler handler = new Handler();

            String jsonString = handler.httpServiceCall(url);
            if(jsonString!=null){
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONArray books = jsonObject.getJSONArray("Book");
                    for(int i= 0; i<books.length(); i++){
                        JSONObject jsonObject1 = books.getJSONObject(i);
                        String id_book = jsonObject1.getString("id_book");
                        String book_name = jsonObject1.getString("book_name");


                        HashMap<String,String> bookMap = new HashMap<>();

                        bookMap.put("id_book",id_book);
                        bookMap.put("book_name",book_name);


                        bookList.add(bookMap);
                    }
                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
            else {
                Toast.makeText(getApplicationContext(),"Server Error",Toast.LENGTH_LONG).show();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Json Parsing Error",Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }
    }
}

and i saw something like this android.os.AsyncTask is deprecated What's going on here? is something wrong with my code? thanks

Yes, Async Task is deprecated now. There are already better and best alternate available those already handled these hacks of handling automatically and provide more readable and maintainable code. You must try one of those as I am mentioned below:

  1. Retrofit
  2. Volley
  3. LoopJ

And many examples can be found over stack-overflow very easily.

First of all, we would need a full stack trace of your exception to check what is wrong with the code. At first, what I don't see is you ever executing AsyncTask. Even though AsyncTask is deprecated it still works but it's an old solution to modern problems.

To fix this I would probably suggest working with RxJava, here is an example of how:

private void process() {
    try {

        Observable.fromCallable(new Callable<JsonNode>() {
            @Override
            public JsonNode call() {
                try {

                    JSONObject jsonObject;
                    
                    //prepare your JSONObject for HttpClient

                    JsonParser jsonParser = new CustomHttpClient().postParser(url, jsonObject.toString());
                    ObjectMapper mapper = new ObjectMapper();

                    return mapper.readTree(jsonParser);
                } catch (Exception e) {
                    e.getMessage();
                }
                return JsonNodeFactory.instance.objectNode();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<JsonNode>() {
                    @Override
                    public void accept(@NonNull JsonNode node) throws Exception {
                        try {
                            if (node == null || node.isEmpty()) {
                                return;
                            }
                            if (node.get("status_code").asInt() != 200) {
                                return;
                            }

                            //do something with your data
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        Exception e = new Exception(throwable.getMessage());
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        try {
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

To get the data you need just call the function like anyother

process();

In my case, I work with JsonNode and I use my CustomHttpClient which is a class for itself. But you can do whatever you want, just edit it accordingly. There are also many other implementations of this using other libraries but I found this easy to read, quick and understandable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM