我无法将活动的数据(字符串)发送到活动中包含的片段

时间:2018-08-01 01:20:22

标签: android firebase android-fragments android-recyclerview google-cloud-firestore

我正在尝试发送存储在Firebase中的文档的ID。文档的所有ID均打印在RecyclerView中,当您单击任何一个时,应将String中的ID发送到Fragment DatosEntregaActivity,以便它可以在“传递”的集合中搜索最后一个具有字段ID的文档活动的ID。 我已经用Bundle尝试过,但是单击时它不发送或不接收发送的数据。

这是当我单击RecyclerView的元素时抛出的错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.asus.loginsmk, PID: 15755
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
                      at com.example.asus.loginsmk.Fragments.DatosEntregaActivity.onCreate(DatosEntregaActivity.java:62)
                      at android.support.v4.app.Fragment.performCreate(Fragment.java:2331)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1386)
                      at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1188)
                      at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1071)
                      at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:115)
                      at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2380)
                      at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
                      at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2215)
                      at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:649)
                      at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                      at android.support.v4.view.ViewPager.populate(ViewPager.java:1238)
                      at android.support.v4.view.ViewPager.populate(ViewPager.java:1086)
                      at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1616)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1489)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1489)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1489)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at com.android.internal.policy.DecorView.onMeasure(DecorView.java:729)
                      at android.view.View.measure(View.java:19937)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2442)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1488)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1747)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1372)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6774)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:735)
                      at android.view.Choreographer.doFrame(Choreographer.java:667)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
                      at android.os.Handler.handleCallback(Handler.java:761)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:156)
                      at android.app.ActivityThread.main(ActivityThread.java:6595)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

这是将发送数据的活动

public class ServicioActivity extends AppCompatActivity{
    NotificationCompat.Builder notificacion;
    NotificationManagerCompat nM;
    private static final int notificationID = 100;
    String estado;
    private static final String TAG = "ServicioActivity";

    private SwipeRefreshLayout mSwipeRefreshLayout;
    List<IdListaVo> listDatos;
    RecyclerView recycler;
    AdapterDatos mAdapterDatos;
    FirebaseFirestore db;
    Task<QuerySnapshot> docRef;
    FragmentManager mFragmentManager;
    String datoFragment;

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

        listDatos = new ArrayList<>();
        recycler = (RecyclerView)findViewById(R.id.reclycer_ordenes_servicio);

        insertar_orden_servicio();

        mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_lista);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeRefreshLayout.setRefreshing(true);
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run()
                    {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mAdapterDatos.clear();
                        insertar_orden_servicio();

                    }
                },3000);
            }
        });

        estado = "entregado";
        notificacionOrdenServicio(estado);

    }

    public void notificacionOrdenServicio(String stado)
    {
        if (stado == "entregado")
        {
            Intent intent = new Intent(this, DatosActivity.class);
            intent.putExtra("mitab2",2);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            notificacion = new NotificationCompat.Builder(this, "CHANNEL_ID");

            notificacion.setSmallIcon(R.drawable.ic_smk_icon_notification);
            notificacion.setContentTitle("SMK");
            notificacion.setContentText("Se ha realizado la entrega de su pedido");
            notificacion.setWhen(System.currentTimeMillis());
            notificacion.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
            notificacion.setAutoCancel(true);
            notificacion.setContentIntent(pendingIntent);

            nM = NotificationManagerCompat.from(this);
            nM.notify(notificationID, notificacion.build());
        }


    }

    public void insertar_orden_servicio()
    {

        db = FirebaseFirestore.getInstance();
        docRef = db.collection("DatosGenerales").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            //Toast.makeText(getApplicationContext(), "DocumentSnapshot data: " + "succes", Toast.LENGTH_LONG).show();

                            QuerySnapshot queryDocumentSnapshots = task.getResult();
                            int tam_botones = queryDocumentSnapshots.size();

                            Toast.makeText(getApplicationContext(), "DocumentSnapshot data: " + tam_botones, Toast.LENGTH_SHORT).show();
                            for (DocumentSnapshot document: task.getResult()) {
                                IdListaVo idListaVo = document.toObject(IdListaVo.class);
                                idListaVo.setOrden_servicio(document.getId());
                                idListaVo.setImagen(R.drawable.baseline_local_shipping_black_18);
                                listDatos.add(idListaVo);
                            }

                            mAdapterDatos = new AdapterDatos(listDatos);
                            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
                            recycler.setLayoutManager(mLayoutManager);
                            recycler.setAdapter(mAdapterDatos);
                            setOnItemListener();

                            //Toast.makeText(getApplicationContext(), "DocumentSnapshot data: sin for" + contador, Toast.LENGTH_SHORT).show();
                            int cantPS = tam_botones;



                        } else {
                            Toast.makeText(getApplicationContext(), "DocumentSnapshot data: " + "not succes", Toast.LENGTH_LONG).show();
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });


    }

    public void setOnItemListener(){
        if(mAdapterDatos!=null)
        {
            mAdapterDatos.setOnItemClick(new AdapterDatos.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    IdListaVo clickedForm=listDatos.get(position);

                    Intent intent = new Intent(ServicioActivity.this, DatosActivity.class);

                    DatosEntregaActivity datosEntregaActivity = new DatosEntregaActivity();

                    Bundle bundle = new Bundle();
                    bundle.putString("documento", String.valueOf(clickedForm.getOrden_servicio()));

                    Toast.makeText(getApplicationContext(), String.valueOf(clickedForm.getOrden_servicio()), Toast.LENGTH_LONG).show();

                    datosEntregaActivity.setArguments(bundle);

                    /*intent.putExtras(bundle);
                    //intent.putExtra("documento-OS", listDatos.get(position).getOrden_servicio());*/
                    startActivity(intent);

                }
            });
        }
    }

}

这是将接收数据的el片段

public class DatosEntregaActivity extends Fragment {
    View mView;
    RecyclerView mRecyclerView;
    List<DatosEntrega> listaEntrega;
    Bundle extras;
    String documento_os;
    String tipo_servicio;
    FirebaseFirestore db;
    DocumentReference docRef;
    DatosEntrega datosEntrega;
    
public DatosEntregaActivity()
    {
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.datos_entrega_fragment_tab, container, false);
        mRecyclerView = (RecyclerView)mView.findViewById(R.id.recyclerview_datos_entrega);
        RecyclerViewAdapter_DatosEntrega recyclerViewAdapter = new RecyclerViewAdapter_DatosEntrega(getContext(), listaEntrega);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(recyclerViewAdapter);

        return mView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listaEntrega = new ArrayList<>();

        /*if (getArguments() != null) {
            documento_os = getArguments().getString("documento");
        }*/

        documento_os = getArguments().getString("documento");

        db = FirebaseFirestore.getInstance();
        docRef = db.collection("DatosGenerales").document(documento_os);

        tipo_servicio_entrega();

    }

    /*private void consultarBD() {
        extras = getIntent().getExtras();
        documento_os = extras.getString("documento-OS");
        docRef = db.collection("DatosGenerales").document(documento_os);

    }*/

    private void tipo_servicio_entrega() {

        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<
                    DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {

                        tipo_servicio = document.getString("idtiposervicio");

                        String estado = "entregado";
                        String[] entregado = {"ESTATUS", "ENTREGADO A", "FECHA", "OBSERVACIÓN"};

                        if (tipo_servicio.equalsIgnoreCase("LOCAL") || tipo_servicio.equalsIgnoreCase("nacional")) {
                            String[] locNac = {"ORIGEN", "DESTINO", "SERVICIO", "CANTIDAD", "DESCRPCIÓN", "PESO", "DESTINARIO"};
                            String[] infor = {"ORG", "AAAA", "SERV", "CANT", "DESCRP", "BBB", "CCC"};

                            for (int i = 0; i < locNac.length; i++) {
                                listaEntrega.add(new DatosEntrega(locNac[i], infor[i]));
                            }

                            if (estado.equalsIgnoreCase("entregado")) {

                                for (int i = 0; i < entregado.length; i++) {
                                    listaEntrega.add(new DatosEntrega(entregado[i], infor[i]));
                                }

                            }
                        } else {
                            if (tipo_servicio.equalsIgnoreCase("paquete")) {
                                String[] paquete = {"TIPO DE SERVICIO", "N° DE RECOJOS", "N° DE DISTRIBUCIÓN", "SERVICIO", "ORIGEN", "CANTIDAD/TIPO DE MERCADERÍA", "PESO"
                                        , "MEDIDAS", "HORA PROGRAMADA", "DIRECCIÓN DE RECOJO", "NIVEL DE PISO DE RECOJO", "CONTACTO DE RECOJO", "DESTINO", "DIRECCIÓN DE ENTREGA",
                                        "NIVEL PISO DE ENTREGA", "CONTACTO DE ENTREGA", "HORA DE ENTREGA"};

                                for (int i = 0; i < paquete.length; i++) {
                                    listaEntrega.add(new DatosEntrega(paquete[i], "infoPaq"));
                                }


                            } else {
                                if (tipo_servicio.equalsIgnoreCase("almacen")) {
                                    String[] almacen = {"TIPO DE SERVICIO", "AREA M2", "TIEMPO", "TIPO DE MERCADERÍA", "N° PALETS", "CONDICIONES", "DIRECCIÓN", "FECHA DE INICIO", "FECHA DE CULMINACIÓN"};

                                    for (int i = 0; i < almacen.length; i++) {
                                        listaEntrega.add(new DatosEntrega(almacen[i], "infoAl"));
                                    }

                                }
                            }
                        }
                    }
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

要将Bundle传递给新的Activity,您需要设置intent的附加项,而不是Activity。在您的onClick中,您可以正确找到它的代码。

Intent intent = new Intent(ServicioActivity.this, DatosActivity.class);

Bundle bundle = new Bundle();
bundle.putString("documento", String.valueOf(clickedForm.getOrden_servicio()));

intent.putExtras(bundle);
startActivity(intent);

然后在您的Activity中。

@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    documento_os = getIntent().getExtras().getString("documento");
    // ...
}