简体   繁体   English

无法在列表视图中显示来自 json 的数据 java 和 android.os.asynctask 已弃用

[英]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当我想用 json 从 android 和 java 显示数据时遇到问题

没有数据

But from json generator its fine here is the example of json http://www.json-generator.com/api/json/get/cfYdxbAzma?indent=2但是从 json 生成器这里很好的是 json http://www.json-generator.com/api/json/get/cfYdxbAzma?indent的例子

and here is my MainActivity.java这是我的 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?我看到了类似这样的android.os.AsyncTask已弃用这是怎么回事? 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 Retrofit
  2. Volley排球
  3. LoopJ循环J

And many examples can be found over stack-overflow very easily.在 stack-overflow 上可以很容易地找到许多示例。

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.起初,我没有看到您曾经执行过 AsyncTask。 Even though AsyncTask is deprecated it still works but it's an old solution to modern problems.即使 AsyncTask 已被弃用,它仍然有效,但它是现代问题的旧解决方案。

To fix this I would probably suggest working with RxJava, here is an example of how:为了解决这个问题,我可能会建议使用 RxJava,下面是一个例子:

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要获取您需要的数据,只需像其他任何人一样调用 function

process();

In my case, I work with JsonNode and I use my CustomHttpClient which is a class for itself.就我而言,我使用 JsonNode 并使用我的 CustomHttpClient,它本身就是一个 class。 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.还有许多其他使用其他库的实现,但我发现这易于阅读、快速且易于理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在android.os.AsyncTask $ 3.done(AsyncTask.java:300) - at android.os.AsyncTask$3.done(AsyncTask.java:300) 在Java中是否有与“ android.os.AsyncTask”等效的功能,或者我只是使用“ Thread#sleep”? - Is there an equivalence of 'android.os.AsyncTask' in java or I just use 'Thread#sleep'? 使用Collections.sort时android.os.AsyncTask中的java.lang.ArrayIndexOutOfBoundsException - java.lang.ArrayIndexOutOfBoundsException in android.os.AsyncTask while using Collections.sort 未选中调用'执行(Params ...)'作为原始类型'android.os.AsyncTask'的成员 - Unchecked Call to 'execute(Params…)' as a member of raw type 'android.os.AsyncTask' 方法在 android.os.AsyncTask 中执行未模拟错误,但实际上不是 mocking 任何东西 - Method execute in android.os.AsyncTask not mocked error, but not actually mocking anything Android Listview在添加AsyncTask数据时出现问题 - Android Listview issues in adding data from AsyncTask 无法在ListView Java中显示来自php mysql的数据 - Could not display data from php mysql in listview java ANDROID使用AsyncTask MySQL通过JSON更新ListView - ANDROID Updating a ListView via JSON with AsyncTask MySQL Android-从SQLite获取数据并在ListView中显示 - Android - Fetch data from SQLite and display in ListView 如何在Android的ListView中显示来自MySQL的数据? - How to display the data from mySQL in listview in android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM