异步任务没有正确填充列表

时间:2018-03-08 12:06:35

标签: android android-asynctask

我正在开发一个Feed应用,用户可以在其中发帖,这些帖子会填充RecyclerView

我有一个导致帖子活动的FAB按钮,但是当我发布然后回到MainActivity时,列表不会更新。但是当我使用注销按钮并重新登录时,列表会更新,或者当我启动活动时它会工作。

我认为这是因为我的异步函数被调用以在onCreate上工作,但是我不能像这样工作,我需要AsyncTask自动获取,否则人们会赢得&#39 ; t实时更新列表。

你可以在黑暗中向我看一盏灯吗?以下是MainActivityPostActivity的代码和其他类的注销函数。

主要活动:

public class MainActivity extends AppCompatActivity {

private AppCompatActivity activity = MainActivity.this;
private RecyclerView recyclerViewNews;
private List<Noticia> listNoticias;
private NewsRecyclerAdapter newsRecyclerAdapter;
private DBNoticias databaseHelper;
private Button btnLogout;
private LinearLayoutManager mLayoutManager;
UserSession userSession;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    userSession = new UserSession(getApplicationContext());

    recyclerViewNews = findViewById(R.id.recyclerViewNews);
    btnLogout = findViewById(R.id.btlogout);

    TextView usuario = findViewById(R.id.textView5);


    /**
     * Olá mundo by Alciomar
     */
    SharedPreferences sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
    String  uName = sharedPreferences.getString("Name", "");
    usuario.setText(uName.toUpperCase());


    try {
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userSession.logoutUser();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    initStuff();
    getDataFromPostgres();

    FloatingActionButton fab = findViewById(R.id.fabNews);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, PostNews.class);
            startActivity(intent);
        }
    });

}


/**
 * This method is to initialize objects to be used
 */
private void initStuff() {

    try {
        listNoticias = new ArrayList<>();
        newsRecyclerAdapter = new NewsRecyclerAdapter(listNoticias);

        mLayoutManager = new LinearLayoutManager(getApplicationContext());
        mLayoutManager.setReverseLayout(true);
        mLayoutManager.setStackFromEnd(true);
        recyclerViewNews.setLayoutManager(mLayoutManager);
        recyclerViewNews.setItemAnimator(new DefaultItemAnimator());
        recyclerViewNews.setHasFixedSize(true);
        recyclerViewNews.setAdapter(newsRecyclerAdapter);
        databaseHelper = new DBNoticias(activity);

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

/**
 * This method is to fetch all user records from SQLite
 */
private void getDataFromPostgres() {
    // AsyncTask is used that SQLite operation not blocks the UI Thread.
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            listNoticias.clear();
            for (DBNoticias dbNoticias : databaseHelper.getNewsList()) {
                Noticia noticia = new Noticia();
                noticia.setUser_id(dbNoticias.getId());
                noticia.setNewsTitle(dbNoticias.getNewsTitle());
                noticia.setNewsMessage(dbNoticias.getNewsPost());

                listNoticias.add(noticia);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            newsRecyclerAdapter.notifyDataSetChanged();
        }
    }.execute();
}

发布新闻活动:

public class PostNews extends AppCompatActivity {

private DBNoticias dbNoticias;
private Button btnpostar;
private EditText editTextCDNewsTitle;
private EditText editTextCDNewsPost;
private Noticia noticia;
private SharedPreferences sharedPreferences;

public void alert(String titulo, String txt){
    AlertDialog alertDialog = new AlertDialog.Builder(PostNews.this).create();
    alertDialog.setTitle(titulo);
    alertDialog.setMessage(txt);
    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alertDialog.show();
}

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

    btnpostar = findViewById(R.id.btn_postar);
    dbNoticias = new DBNoticias();

    editTextCDNewsTitle = findViewById(R.id.EditTextNewsTitle);
    editTextCDNewsPost = findViewById(R.id.EditTextNewsPost);

}

public void salvarNoticia(View view) {
    try {
        {
            String newsTitle = editTextCDNewsTitle.getText().toString();
            String newsPost = editTextCDNewsPost.getText().toString();

            if (!(editTextCDNewsTitle.getText().toString().equals("") || editTextCDNewsTitle.getText() == null ||
                    editTextCDNewsPost.getText().toString().equals("") || editTextCDNewsPost.getText() == null

            )) {

                sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
               String  uName = sharedPreferences.getString("Name", "");
               String uEmail = sharedPreferences.getString("Email", "");
               int  uIdUser = sharedPreferences.getInt("IdUser", 0);

                dbNoticias.setNewsTitle(newsTitle);
                dbNoticias.setNewsPost(newsPost);
                dbNoticias.setIdUser(uIdUser);


                dbNoticias.salvar();

                noticia = new Noticia();


                Toast.makeText(getApplicationContext(), "Notícia postada com sucesso",
                        Toast.LENGTH_LONG).show();

                editTextCDNewsTitle.setText("");
                editTextCDNewsPost.setText("");
            }

        }
    }
    catch (Exception e){
        alert("Erro", e.getMessage());
    }
}

如果您阅读并尝试提供帮助,请提前感谢您!

2 个答案:

答案 0 :(得分:0)

请使用它,这对我有用

 newsRecyclerAdapter.notifyItemInserted(position);
 newsRecyclerAdapter.notifyDataSetChanged();

答案 1 :(得分:0)

有多种方法可以做到这一点:

方法1 - 使用onResume()

如果您在getDataFromPostgres()而不是onResume中调用onCreate方法,则每次活动从暂停中唤醒时都会获取数据和刷新列表(例如从另一个中恢复)活性)

// existing code

@Override
public void onResume(){
    super.onResume();
    getDataFromPostgres()
}

(这将是最简单的解决方案)

方法2 - 持续轮询数据库

如果有其他服务可能正在更新数据库,并且您需要始终在活动中显示最新状态,另一种方式(尽管效率非常低)将在定义的时间段后继续刷新列表(假设为10)以秒为例)。

How to run an async task for every x mins in android?

方法3 - 使用onActivityResult

如果您只想在第二个活动中创建新条目时更新列表,您可以使用onActivityResult通知第一个活动,然后然后刷新您的列表那里。

How to manage `startActivityForResult` on Android?