如何异步发送类之间的数据?

时间:2019-09-06 15:06:46

标签: java android android-room

我需要知道该怎么做吗?

我有两个观点

  • ActivityMain.java
  • FilmActivity

在MainActivity中,我创建了一个从第二个视图中获取一些信息的意图:

 @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
        simpleGrid.setAdapter(customGridviewAdapter);
        simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), FilmActivity.class);
                intent.putExtra("FilmBoster", filmList.get(position).getBackdrop_path())
                        .putExtra("FilmImage", filmList.get(position).getPoster_path())
                        .putExtra("FilmName", filmList.get(position).getTitle())
                        .putExtra("FilmDate", filmList.get(position).getRelease_date())
                        .putExtra("FilmDisc", filmList.get(position).getOverview())
                        .putExtra("isFavFilm", filmList.get(position).getIsLiked());
                startActivityForResult(intent, 2);
            }
        });
    }

第二个视图:

 private void sendDataToMainActivity(String isPressed) {
    Intent intent = new Intent();
    intent.putExtra("isPressed" , isPressed);
    setResult(1 , intent);
    finish();
}

我在MainActivity中使用了AsyncTask。第二个活动在onActivityResult中发送了数据,但是(onActivityResult)执行了AsyncTask之后,在AsyncTask中,我在数据库上设置了一些数据。这样,从“第二个活动”返回的数据就等于null。

一些帮助代码

 @NonNull
    private String convertToString(InputStream in) {
        String res = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sd = new StringBuilder();
        try {
            while ((res = reader.readLine()) != null) {
                sd.append(res).append("/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        parseString(sd.toString());
        db.userDao().updateFilmList(filmList);
        return sd.toString();
    }

  private void parseString(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject filmObject = jsonArray.getJSONObject(i);
                Film film = new Film(filmObject.getString("title")
                        ,filmObject.getString("overview")
                        , filmObject.getString("poster_path")
                        , filmObject.getString("release_date")
                        ,db.userDao().getIsFave());
                filmList.add(film);
            }

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

    }

这是AsyncTask内部的两个方法,可将数据保存到db

如果要在AsyncTask上返回数据并在DB上进行设置,该怎么办?

2 个答案:

答案 0 :(得分:0)

在MainActivity类的onCreate或onResume方法中进行以下操作:

    // filmList should be an empty array at this point
    CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
    simpleGrid.setAdapter(customGridviewAdapter);
    simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getApplicationContext(), FilmActivity.class);
            intent.putExtra("FilmBoster", filmList.get(position).getBackdrop_path())
                    .putExtra("FilmImage", filmList.get(position).getPoster_path())
                    .putExtra("FilmName", filmList.get(position).getTitle())
                    .putExtra("FilmDate", filmList.get(position).getRelease_date())
                    .putExtra("FilmDisc", filmList.get(position).getOverview())
                    .putExtra("isFavFilm", filmList.get(position).getIsLiked());
            startActivityForResult(intent, 2);
        }
    });

然后,您只需在postExecute方法中执行此操作(假设您已在Async Task中重新填充了filmList):

    CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
    simpleGrid.setAdapter(customGridviewAdapter);

onItemClicked处理程序会将单击的项目发送到FilmActivity.java类活动。在该活动的onCreate中,您需要读取从MainActivity传递给它的数据:

 public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

 setContentView(R.layout.film_activity_layout); 

 FilmName = (String) getIntent().getExtra("FilmName");

 ...
 }

您需要显示MainActivity中的onActivityResult代码

答案 1 :(得分:-1)

您必须使用异步任务吗?我建议改用RxJava。

但是,您可以创建一个扩展AsyncTask的类并在构造函数中发送Context,以便setResult并完成onPostExecute中的当前活动。

示例:https://stackoverflow.com/a/16921076/12009871