GridView没有刷新?

时间:2017-11-17 07:27:27

标签: android android-fragments gridview

我正在开发一款只有一个活动和多个片段的Android应用。

其中一个片段包含带有自定义适配器的GridView。

GridView中显示的数据是从远程服务器数据库加载的。

在另一个片段上,用户可以将项目添加到远程数据库,在发送数据后,应用程序会再次打开包含GridView的片段,但数据不会使用最后一个包含的项目进行更新。

这里有方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    Log.d("MISUPICKS","ESTOE EN MISUPICKS ONCREATE");

    View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

    txtbusqueda = (EditText) view.findViewById(R.id.txtbusqueda);

    botonbuscar =(Button) view.findViewById(R.id.btnbuscar);

    botonbuscar.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        String busqueda = txtbusqueda.getText().toString();
        getUpicksBusquedaFromDB(0, busqueda);
      }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    upicks = new ArrayList<>();

    gridLayout = new GridLayoutManager(getActivity(), 2);
    recyclerView.setLayoutManager(gridLayout);

    adapter = new UpicksAdapter(getActivity(), upicks);

    adapter.notifyDataSetChanged();

    upicks.clear();

    recyclerView.setAdapter(adapter);

    adapter.notifyDataSetChanged();

    getUpicksFromDB(0);
    return view;
}

你可以在那里找到实际从远程服务器加载数据的getUpicksFromDB(0)方法:

private void getUpicksFromDB(int id) {
    Log.d("MISUPICKS","ESTOE EN MISUPICKS getupicksfromddb");

    AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
      @Override
      protected Void doInBackground(Integer... addressesIds) {
        //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("http://.../upicks_todos.php")
            .build();
        try {
          okhttp3.Response response = client.newCall(request).execute();

          JSONArray array = new JSONArray(response.body().string());

          for (int i = 0; i < array.length(); i++) {

            JSONObject object = array.getJSONObject(i);
            Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
            Upicks upicks = new Upicks(object.getInt("id_servicio"),
                object.getString("driver_servicio"),
                object.getString("inicio_servicio"),
                object.getString("lat_origen_servicio"),
                object.getString("lon_origen_servicio"),
                object.getString("lat_destino_servicio"),
                object.getString("lon_destino_servicio"),
                object.getString("cliente_servicio"),
                object.getString("final_servicio"),
                object.getString("distancia_servicio"),
                object.getString("tarifa_servicio"),
                object.getString("origen_servicio"),
                object.getString("destino_servicio"),
                object.getString("estado_servicio"),
                object.getString("tiempo_servicio")
            );

            MisUpicksFragment.this.upicks.add(upicks);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (JSONException e) {
          e.printStackTrace();
        }
        return null;
      }

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

    asyncTask.execute(id);
}

每次显示片段时,我应该更改什么才能刷新数据?

编辑:

适配器

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.juarezserver.upick.R;
import com.juarezserver.upick.fragment.DetalleUpickFragment;

import java.util.List;

import static android.content.Context.MODE_PRIVATE;


public class UpicksAdapter extends RecyclerView.Adapter<UpicksAdapter.ViewHolder> {

    private Context context;
    private List<Upicks> upicks;
    private String emailsegundo;

    private SharedPreferences mPref;
    private  static final String PREF_NAME = "directorio";

    public UpicksAdapter(Context context, List<Upicks> upicks) {
        this.context = context;
        this.upicks = upicks;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.upick_card,parent,false);

        return new ViewHolder(itemView);
    }

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

       // holder.txtapodo.setText(upicks.get(position).getid_servicio());
        holder.txtOrigen.setText(upicks.get(position).getorigen_servicio());
        holder.txtDestino.setText(upicks.get(position).getdestino_servicio());
       // holder.txtapellidos.setText(upicks.get(position).getApellidos());
        //holder.txtempresa.setText(upicks.get(position).getEmpresa());
      //  String url_foto = "http://.../usuarios/"+ upicks.get(position).getImagen();
    //    Glide.with(context).load(url_foto).into(holder.imageView);



    }



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

    public  class ViewHolder extends  RecyclerView.ViewHolder implements View.OnClickListener{



        public TextView txtOrigen;
        public TextView txtDestino;


        public ViewHolder(View itemView) {
            super(itemView);
            txtOrigen = (TextView) itemView.findViewById(R.id.txtOrigen);
            txtDestino = (TextView) itemView.findViewById(R.id.txtDestino);

            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            showPopupMenu(v,position);
        }
    }

    private void showPopupMenu(View view, int poaition) {
        PopupMenu popup = new PopupMenu(context, view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_context_upick, popup.getMenu());
        popup.setOnMenuItemClickListener(new MenuClickListener(poaition));
        popup.show();
    }


    class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
        Integer pos;
        public MenuClickListener(int pos) {
            this.pos=pos;
        }

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_favourite:




                    mPref = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);


                    SharedPreferences.Editor editor = mPref.edit();

                    editor.putString("NOMBRE", upicks.get(pos).getinicio_servicio());
          //          editor.putString("APELLIDOS", upicks.get(pos).getApellidos());
          //          editor.putString("APODO", upicks.get(pos).getApodo());
                    //          editor.putString("CUMPLE", upicks.get(pos).getCumple());
//

                    //      editor.putString("CONYUGE", upicks.get(pos).getConyuge());
                    //       editor.putString("CUMPLE_CONYUGE", upicks.get(pos).getCumple_conyuge());
                    //       editor.putString("ANIVERSARIO_BODAS", upicks.get(pos).getAniversario_bodas());
                    //       editor.putString("EMPRESA", upicks.get(pos).getEmpresa());
                    //       editor.putString("DIRECCION_EMPRESA", upicks.get(pos).getDireccion_empresa());

                    //       editor.putString("TEL_NEGOCIO", upicks.get(pos).getTel_negocio());
                    //         editor.putString("FECHA_INGRESO", upicks.get(pos).getFecha_ingreso());
                    //       editor.putString("NUM_ROTARIO", upicks.get(pos).getNum_rotario());
                    //        editor.putString("PADRINO", upicks.get(pos).getPadrino());
                    //       editor.putString("DIRECCION_CASA", upicks.get(pos).getDireccion_casa());

                    //       editor.putString("TEL_CASA", upicks.get(pos).getTel_casa());
                    //      editor.putString("CELULAR", upicks.get(pos).getCelular());
                    //      editor.putString("EMAIL", upicks.get(pos).getEmail());

                    //   Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + upicks.get(pos).getEmail_privado());
                    //    emailsegundo = "-";

                    //       if("null".equals(upicks.get(pos).getEmail_privado()))
                    //       {
                    //        emailsegundo = "-";
                    //       Log.d("HOLA PERFIL", "RESPONSE 2 no hay " + upicks.get(pos).getEmail_privado());
                    //      }
                    //    else
                    //    {
                    //         emailsegundo = upicks.get(pos).getEmail_privado();
                    //Log.d("HOLA PERFIL", "RESPONSE 2 email: " + upicks.get(pos).getEmail_privado());


                    //  }


                    //  editor.putString("EMAIL_PRIVADO", emailsegundo);


                    //      editor.putString("CLASIFICACION", upicks.get(pos).getClasificacion());
                    //    editor.putString("IMAGEN", upicks.get(pos).getImagen());

                    //    Log.d("HOLA PERFIL", "RESPONSE rotario  en direcadapter: " + upicks.get(pos).getNum_rotario());



                    //    editor.apply();





                 DetalleUpickFragment firstFragment = new DetalleUpickFragment();
                  ((MainActivity)context).getSupportFragmentManager().beginTransaction()
                           .add(R.id.frame, firstFragment).commit();

                    return true;

                default:
            }
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

getStringIndex