我有两个不同的活动: 1.Login.java 2.Dashboard.java
在仪表板活动中,我通过在仪表板活动中显示导航抽屉片段来添加导航抽屉。
现在我想通过login.java
将数据传递给该导航抽屉片段这是我的代码:
Login.java-导入所有内容
public class Login extends AppCompatActivity implements View.OnClickListener, OnItemSelectedListener{
private EditText loginid;
private EditText password;
private Spinner type;
private Button loginbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginid=(EditText) findViewById(R.id.editText_loginid);
password=(EditText) findViewById(R.id.editText_password);
loginbtn=(Button) findViewById(R.id.btn_login);
type=(Spinner) findViewById(R.id.spinner_type);
loginbtn.setOnClickListener(this);
type.setOnItemSelectedListener(this);
List<String> types = new ArrayList<String>();
types.add("Student");
types.add("Faculty");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
type.setAdapter(adapter);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= loginid.getText().toString().trim();
String pass= password.getText().toString().trim();
String type_passed = type.getSelectedItem().toString().toLowerCase();
LoginRequest(type_passed,id,pass);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void LoginRequest(final String type_selected,String id,String pass)
{
VolleySingleton volleySingleton = VolleySingleton.getInstance();
RequestQueue requestQueue= volleySingleton.getRequestQueue();
JsonObjectRequest jsonobject= new JsonObjectRequest(Request.Method.GET,
"http://10.0.2.2:80/noticeboardapi/loginrequest.php/?type="+type_selected+"&enrollid="+id+"&password="+pass+"",
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Bundle bundle = new Bundle();
bundle.putString("type", type_selected);
NavigationDrawerFragment navfrag = new NavigationDrawerFragment();
// TODO Auto-generated method stub
if(type_selected.equals("student"))
{
try {
String enrollid = response.getString("enrollid");
String name = response.getString("name");
String section = response.getString("section");
String rollno = response.getString("rollno");
int status = Integer.parseInt(response.getString("status"));
switch(status)
{
case 0:
{
Toast.makeText(getApplicationContext(), "Incorrect password", Toast.LENGTH_SHORT).show();
break;
}
case 1:
{
navfrag.setArguments(bundle);
Intent sloggedin= new Intent(getApplicationContext(),Dashboard.class);
startActivity(sloggedin);
finish();
break;
}
case 2:
{
Toast.makeText(getApplicationContext(), "User does not exist", Toast.LENGTH_SHORT).show();
break;
}
default:
{
Toast.makeText(getApplicationContext(), "Request Not Accepted", Toast.LENGTH_SHORT).show();
break;
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(type_selected.equals("faculty"))
{
try {
String enrollid = response.getString("enrollid");
String name = response.getString("name");
String cc = response.getString("cc");
String hod = response.getString("hod");
int status = Integer.parseInt(response.getString("status"));
switch(status)
{
case 0:
{
Toast.makeText(getApplicationContext(), "Incorrect password Faculty", Toast.LENGTH_SHORT).show();
break;
}
case 1:
{
navfrag.setArguments(bundle);
Intent floggedin= new Intent(getApplicationContext(),Dashboard.class);
startActivity(floggedin);
finish();
break;
}
case 2:
{
Toast.makeText(getApplicationContext(), "Faculty does not exist", Toast.LENGTH_SHORT).show();
break;
}
default:
{
Toast.makeText(getApplicationContext(), "Request Not Accepted", Toast.LENGTH_SHORT).show();
break;
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} , new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Response \n" + error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonobject);
}
}
我的导航抽屉Fragment.java:
public class NavigationDrawerFragment extends Fragment implements NavigationListAdapter.ClickedListener{
public static final String PREF_FILE_NAME="testpref";
public static final String KEY_USER_LEARNED_DRAWER="user_learned_drawer";
private RecyclerView recyclerView;
private NavigationListAdapter adapter;
private View containerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
String type = getArguments().getString("type");
View layout = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
recyclerView= (RecyclerView) layout.findViewById(R.id.drawerList);
adapter= new NavigationListAdapter(getActivity(), getNavData("student"));
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
HomeFragment home = new HomeFragment();
transaction.replace(R.id.layout_dashboard, home, "Home");
transaction.addToBackStack("home");
transaction.commit();
}
public static List<NavigationListContent> getNavData(String type){
List<NavigationListContent> data = new ArrayList<NavigationListContent>();
if(type.equals("student")){
int[] icons= {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String[] titles= {"Home","Profile","Contact Us"};
for(int i =0;i<titles.length && i<icons.length;i++)
{
NavigationListContent current = new NavigationListContent();
current.title=titles[i];
current.iconId=icons[i];
data.add(current);
}
}else if(type.equals("faculty"))
{
int[] icons= {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String[] titles= {"Home","Profile","Add Notice","Contact Us"};
for(int i =0;i<titles.length && i<icons.length;i++)
{
NavigationListContent current = new NavigationListContent();
current.title=titles[i];
current.iconId=icons[i];
data.add(current);
}
}
return data;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(),KEY_USER_LEARNED_DRAWER , "false"));
if(savedInstanceState!=null)
{
mFromSavedInstanceState=true;
}
}
public void setUp(int fragmentID,DrawerLayout drawerLayout,Toolbar toolbar) {
// TODO Auto-generated method stub
containerView= getActivity().findViewById(fragmentID);
mDrawerLayout=drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close){
@Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer)
{
mUserLearnedDrawer=true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer+"");
}
getActivity().invalidateOptionsMenu();
}
};
if(mUserLearnedDrawer &&mFromSavedInstanceState)
{
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context,String preferenceName,String preferenceValue){
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context,String preferenceName,String preferenceValue){
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, preferenceValue);
}
@Override
public void itemClicked(View view, int position) {
// TODO Auto-generated method stub
//startActivity(new Intent(getActivity(), SubActivity.class));
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
switch(position)
{
case 0:
{
HomeFragment home = new HomeFragment();
transaction.replace(R.id.layout_dashboard, home, "Home");
transaction.addToBackStack("home");
break;
}
case 1:
{
ProfileFragment profile = new ProfileFragment();
transaction.replace(R.id.layout_dashboard, profile, "Profile");
transaction.addToBackStack("profile");
break;
}
case 2:
{
AddNoticeFragment addnotice = new AddNoticeFragment();
transaction.replace(R.id.layout_dashboard, addnotice, "AddNotice");
transaction.addToBackStack("addnotice");
break;
}
case 3:
{
ContactUsFragment contactus = new ContactUsFragment();
transaction.replace(R.id.layout_dashboard, contactus, "ContactUs");
transaction.addToBackStack("contactus");
break;
}
default:
{
Toast.makeText(getActivity(), "No such Option", Toast.LENGTH_SHORT).show();
transaction.addToBackStack("home");
break;
}
}
mDrawerLayout.closeDrawers();
transaction.commit();
}
}
我的Dashboard.java
public class Dashboard extends AppCompatActivity {
private Toolbar toolbar;
private DrawerLayout drawer_layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
toolbar=(Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawer_layout=(DrawerLayout) findViewById(R.id.drawer_layout);
NavigationDrawerFragment drawerfragment= (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerfragment.setUp(R.id.fragment_navigation_drawer,drawer_layout,toolbar);
}
@Override
public void onBackPressed() {
if (drawer_layout.isDrawerOpen(Gravity.START)) { // replace this with
// actual function
// which returns if
// the drawer is
// open
drawer_layout.closeDrawer(Gravity.START); // replace this with
// actual function which
// closes drawer
} 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.dashboard, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
收到错误:
04-29 19:11:06.009: E/AndroidRuntime(3641): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
我尝试了很多stackoverflow解决方案,但没有人适合我。 请告诉我该做什么,因为我被困在这里太多时间,并提前感谢!