将字符串值(日期)从活动传递到另一个片段的textview

时间:2016-11-12 14:41:12

标签: java android

我有一个空值,它将包含时间和日期的字符串值传递给另一个带有textview的片段。是否有方法将这些值传递到我的片段的java类(Notifications.java)中的另一个?

            date = (TextView) view.findViewById(R.id.textDate);
            date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));

我收到了这个错误:

rogue.queue E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: rogue.queue, PID: 20762
                                                                      java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                          at rogue.queue.MainActivity$1.onClick(MainActivity.java:76)

使用fab按钮将值传递给另一个片段:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Snackbar.make(view, "Add a new queue", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
            fragmentManager.beginTransaction().replace(R.id.content_main, new Notifications()).commit();
            date = (TextView) view.findViewById(R.id.textDate);
        date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
        navigationView.setCheckedItem(R.id.nav_notifications);
    }
});

这是片段

的通知java类
public class Notifications extends Fragment {
TextView servingqueue;
TextView date;
String dateGET;

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mServingQueue = mRootRef.child("ServingQueue");


public Notifications() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle pb=getArguments();
    dateGET=pb.getString("date");


    mServingQueue.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Double number = dataSnapshot.getValue(Double.class);
            servingqueue.setText(String.valueOf(number));

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

}

@Override
public void onDetach() {
    super.onDetach();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_notifications, container, false);
    // Inflate the layout for this fragmentid.queueServing);
    servingqueue = (TextView) rootView.findViewById(R.id.queueServing);
    return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    date = (TextView) view.findViewById(R.id.textDate);
//        date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
    date.setText(dateGET);

    }
}

这是我的主要活动

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, Home.OnFragmentInteractionListener {
    //Read Firebase Database

    private FirebaseAuth firebaseAuth;
    private TextView textViewUserEmail;
    private MenuItem nav_logout;
    TextView servingqueue;
TextView date;


FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

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

    //Launches Home() fragment
    fragmentManager.beginTransaction().replace(R.id.content_main, new Home()).commit();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setCheckedItem(R.id.nav_home);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Add a new queue", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
//                Queue.getQueue();
                fragmentManager.beginTransaction().replace(R.id.content_main, new Notifications()).commit();
//                date = (TextView) view.findViewById(R.id.textDate);
//         

   date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));

            Fragment fragment2=new Notifications();
            Bundle arg= new Bundle();
            arg.putString("date","DATE");
            fragment2.setArguments(arg);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.content_main, fragment2);

            fragmentTransaction.commit();

//                fragmentManager.beginTransaction().replace(R.id.content_main,fragment2).commit();

            navigationView.setCheckedItem(R.id.nav_notifications);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();



    //User Profile Interface
    firebaseAuth = FirebaseAuth.getInstance();
    if (firebaseAuth.getCurrentUser() == null) {
        startActivity(new Intent(this, Login.class));
    }
    FirebaseUser user = firebaseAuth.getCurrentUser();

    View HeaderView = navigationView.getHeaderView(0);
    textViewUserEmail = (TextView) HeaderView.findViewById(R.id.textViewUserEmail);
    textViewUserEmail.setText("Welcome "+user.getEmail());
//        nav_logout = (MenuItem) findViewById(R.id.nav_logout);
//        nav_logout.setOnClickListener(this);

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }
     else {
        super.onBackPressed();
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        fragmentManager.beginTransaction().replace(R.id.content_main, new Home()).commit();
    } else if (id == R.id.nav_notifications) {
        fragmentManager.beginTransaction().replace(R.id.content_main, new Notifications()).commit();
    } else if (id == R.id.nav_settings) {
        fragmentManager.beginTransaction().replace(R.id.content_main, new Settings()).commit();
    } else if (id == R.id.nav_logout) {
        firebaseAuth.signOut();
        finish();
        startActivity(new Intent (this, Login.class));
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onFragmentInteraction(Uri uri) {

}

public void onClick(View v) {
    Intent intent = new Intent (this, Scanner.class);
    startActivity(intent);
}

}

这是我正在编辑的xml:

片段:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rogue.queue.Notifications"
android:id="@+id/notification_relative_layout">

<!-- TODO: Update blank fragment layout -->

<TextView
    android:text="Your Number:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="72dp"
    android:id="@+id/textView3"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:text="0000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp"
    android:id="@+id/myqueue"
    android:textSize="40sp" />

<TextView
    android:text="Current Number:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView9"
    android:layout_marginTop="62dp"
    android:layout_below="@+id/myqueue"
    android:layout_toStartOf="@+id/myqueue" />

<TextView
    android:text="PLEASE BE SEATED"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="78dp"
    android:id="@+id/textView15"
    android:layout_below="@+id/queueServing"
    android:layout_centerHorizontal="true" />

<TextView
    android:text="-"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/queueServing"
    android:layout_alignBaseline="@+id/textView9"
    android:layout_toEndOf="@+id/myqueue" />

<TextView
    android:text="YOU WILL BE SERVED SHORTLY"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="19dp"
    android:id="@+id/textView14"
    android:layout_below="@+id/textView15"
    android:layout_centerHorizontal="true" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Welcome to Sunway Education Group"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textDate"
    tools:text="00 - JAN - 0000"
    android:layout_below="@+id/textView14"
    android:layout_alignEnd="@+id/textView9" />

<Button
    android:text="CANCEL QUEUE"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="21dp"
    android:id="@+id/buttonQueueCancel"
    android:background="@android:color/holo_red_light"
    />

这是fab在链接到mainactivity.java时所处位置的app_main_bar

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@drawable/ic_add_white_24px" />

1 个答案:

答案 0 :(得分:1)

我在mydevice中对它进行了测试,结果非常好:

活动xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linn"
    android:orientation="vertical"
    tools:context="maker.jsonp.MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    </FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

和活动代码:

public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
String time= DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());
                Fragment fragment2=new Notifications();
                Bundle arg= new Bundle();
                arg.putString("date",time);
                fragment2.setArguments(arg);
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container, fragment2);
                fragmentTransaction.commit();
            }
        });
    }

}

现在,片段代码:

public class Notifications extends Fragment {

    TextView servingqueue;
    TextView date;
    String dateGET;

    public Notifications() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Bundle pb=getArguments();
        dateGET=pb.getString("date");

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.frag, container, false);
        // Inflate the layout for this fragmentid.queueServing);
        return rootView;
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        date = (TextView) view.findViewById(R.id.textDate);
        date.setText(dateGET);
    }

}