如何使用volley库检查响应中是否有新数据?安卓工作室

nhaq1z21  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(313)

我正在开发一个聊天应用程序的凌空图书馆。我使用webapi来存储数据。当我需要从webapi获取消息时,我可以获取它们。当有人发送信息时,我也可以通过post方法发布信息(发送者、内容、日期等)。但我不知道如何编写“当webapi发生任何变化时”的代码。我尝试使用无限循环,每5-10秒检查一次webapi上的数据,但当我转到另一个片段时,应用程序给出了错误。如何可能与凌空图书馆或与其他一些网站服务(如消防基地等)
消息片段.java

public class MesajlarEkrani extends Fragment {

    View view;
    RecyclerView recyclerView;
    EditText inputChat;
    FloatingActionButton fab;
    SharedPreferences preferences;
    ArrayList<Mesajlarim> mesajlarim=new ArrayList<>();
    Toolbar toolbar;
    TextView textView;

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_mesajlar_ekrani, container, false);
        preferences=getActivity().getApplicationContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
        toolbar=view.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        textView=view.findViewById(R.id.toolbar_title);
        inputChat=view.findViewById(R.id.inputChat);
        fab=view.findViewById(R.id.fab);
        recyclerView=view.findViewById(R.id.chatRecyclerView);
        LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity().getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        mesajlariGoster(preferences);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputChat.getText().length()>0){
                    mesajYolla(preferences,inputChat.getText().toString());
                    recyclerView.scrollToPosition(mesajlarim.size()-1);

                }else {
                    Toast.makeText(getActivity().getApplicationContext(), "Mesaj içeriği boş olamaz.", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //checks the API in every 1 second to see if there is new data
        final Handler handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mesajlariGoster(preferences);
                handler.postDelayed(this,1000);
            }
        }, 1000);

        return view;
    }

    //to show the messages, gets datas form web API and shows them in recyclerview
    public void mesajlariGoster(SharedPreferences bilgiler){
        String url = "https://api.calmeclis.com/messageList.json";
        String sender = bilgiler.getString("username", "unknown");
        final String receiver;
        if (sender.equals("arhanalp")){
            receiver = "alierencelik";
        }else{
            receiver = "arhanalp";
        }
        int a= 150;

        Map<String,String> map = new HashMap<String, String>();
        map.put("message_from", sender);
        map.put("message_to", receiver);
        map.put("client_token", "RwdSHZvAtDE9GAW6");
        map.put("message_limit",Integer.toString(a));
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity().getApplicationContext());

        JsonObjectRequest messageRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject mesajlar = response.getJSONObject("messages");

                    if (mesajlar.length()!=mesajlarim.size()){
                    textView.setText(receiver);

                    int baslangic_uzunlugu=mesajlarim.size();

                        for (int i = mesajlar.length()-baslangic_uzunlugu ; i> 0;i--){
                        JSONObject mesaj_id = mesajlar.getJSONObject(""+ i);
                        String gonderici = mesaj_id.getString("from");
                        String alici = mesaj_id.getString("to");
                        String icerik = mesaj_id.getString("content");
                        String date = mesaj_id.getString("date");
                        mesajlarim.add(new Mesajlarim(gonderici, icerik,date));
                    }
                        MesajAdapter mesajAdapter=new MesajAdapter(mesajlarim,getActivity().getApplicationContext());
                        recyclerView.setAdapter(mesajAdapter);
                        recyclerView.scrollToPosition(mesajlarim.size()-1);}
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity().getApplicationContext(), "Hata oluştu, bu sayfayı tekrar yükleyiniz", Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(messageRequest);

    }

    //to send message, when the fab is clicked, posts the informations(sender,receiver and content) to the web API. Then the web API automatically saves the message datas
    public void mesajYolla(SharedPreferences bilgiler, final String icerik){
        String url = "https://api.calmeclis.com/messageSend.json";
        final String sender = bilgiler.getString("username", "unknown");
        final String receiver;
        if (sender.equals("arhanalp")){
            receiver = "alierencelik";
        }else{
            receiver = "arhanalp";
        }
        Map<String,String> map = new HashMap<String, String>();
        map.put("message_from", sender);
        map.put("message_to", receiver);
        map.put("message_content", icerik);
        map.put("client_token", "rn5ZkHxs43TZAfwM");

        RequestQueue requestQueue= Volley.newRequestQueue(getActivity().getApplicationContext());
        JsonObjectRequest sendMessage = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                mesajlariGoster(preferences);
                inputChat.setText("");
                InputMethodManager imm = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestQueue.add(sendMessage);

    }
}

getter、setter和constructor

public class Mesajlarim {
    String mesajYazan,mesajIcerik,mesajTarih;

    public Mesajlarim(String mesajYazan, String mesajIcerik, String mesajTarih) {
        this.mesajYazan = mesajYazan;
        this.mesajIcerik = mesajIcerik;
        this.mesajTarih = mesajTarih;
    }

    public String getMesajYazan() {
        return mesajYazan;
    }

    public void setMesajYazan(String mesajYazan) {
        this.mesajYazan = mesajYazan;
    }

    public String getMesajIcerik() {
        return mesajIcerik;
    }

    public void setMesajIcerik(String mesajIcerik) {
        this.mesajIcerik = mesajIcerik;
    }

    public String getMesajTarih() {
        return mesajTarih;
    }

    public void setMesajTarih(String mesajTarih) {
        this.mesajTarih = mesajTarih;
    }

消息适配器.java

public class MesajAdapter extends RecyclerView.Adapter<MesajAdapter.ViewHolder> {
    ArrayList<Mesajlarim> mesajlarim = new ArrayList<>();
    LayoutInflater inflater;
    Context context;
    SharedPreferences preferences;
    public static final int sagMesaj = 1, solMesaj=0;
    String sender;

    public MesajAdapter(ArrayList<Mesajlarim> mesajlarim, Context context) {
        this.mesajlarim = mesajlarim;
        this.context = context;
        preferences = context.getSharedPreferences("preferences", context.MODE_PRIVATE);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        inflater = LayoutInflater.from(context);

        if(viewType==sagMesaj){
            View view = inflater.inflate(R.layout.mesaj_sag_taraf, parent, false);
            ViewHolder viewHolder= new ViewHolder(view);
            return viewHolder;
        }else{
            View view = inflater.inflate(R.layout.mesaj_sol_taraf, parent, false);
            ViewHolder viewHolder= new ViewHolder(view);
            return viewHolder;
        }

    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

            Mesajlarim icerik = mesajlarim.get(position);
            holder.txtUser.setText(icerik.getMesajYazan());
            holder.txtMessage.setText(icerik.getMesajIcerik());
            holder.txtTime.setText(icerik.getMesajTarih());
            holder.mesajLinear.setTag(holder);

    }

    @Override
    public int getItemCount() {
        return mesajlarim.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        TextView txtUser,txtMessage,txtTime;
        LinearLayout mesajLinear;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtUser = itemView.findViewById(R.id.txtUser);
            txtMessage = itemView.findViewById(R.id.txtMessage);
            txtTime = itemView.findViewById(R.id.txtTime);
            mesajLinear = itemView.findViewById(R.id.mesajLinear);

        }
    }

    @Override
    public int getItemViewType(int position) {
        sender = preferences.getString("username", "unknown");
        if(mesajlarim.get(position).getMesajYazan().equals(sender)){
            return sagMesaj;
        }else {
            return solMesaj;
        }
    }
}
rpppsulh

rpppsulh1#

我解决了这个问题。我在无限循环中设置了if条件。只有当视图不等于null时,runnable中的代码才能工作。

//checks the API in every 1 second to see if there is new data
        final Handler handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getView()!=null) {
                    mesajlariGoster(preferences);
                    handler.postDelayed(this, 1000);
                }
            }
        }, 1000);

相关问题