0

I have two activity named School.java and SchoolDetails.java.Under SchoolDetails activity i have used fragments by implementing swipeable tabs.I passed a value from Schools.java to SchoolDetails.java using intent.Now i want to set this value received from Schools.java to a textField which is inside a fragment of SchoolDetails.java activity.I got Following error.

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

This is all what I did inside Schools.java i passed the name of school to SchoolDetails

School.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.user.educationhunt.adapter.CustomListAdapter;
import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.pojos.AppController;
import com.example.user.educationhunt.pojos.OurSchool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class School extends AppCompatActivity{

    // Log tag
    private static final String TAG = School.class.getSimpleName();

    // Billionaires json url
    private static final String url = "http://myeducationhunt.com/public/schools";

    private ProgressDialog pDialog;
    private List<OurSchool> ourSchoolsListItems = new ArrayList<OurSchool>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Schools");


        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, ourSchoolsListItems);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                OurSchool ourSchool=new OurSchool();
                Intent i=new Intent(School.this,SchoolDetails.class);

                i.putExtra("id", ourSchoolsListItems.get(position).schoolId);
                i.putExtra("name", ourSchoolsListItems.get(position).schoolName);
                i.putExtra("location", ourSchoolsListItems.get(position).schoolLocation);
                i.putExtra("logo", ourSchoolsListItems.get(position).schoolLogo);
                i.putExtra("email", ourSchoolsListItems.get(position).schoolEmail);
                i.putExtra("website", ourSchoolsListItems.get(position).schoolEmail);
                i.putExtra("created_at", ourSchoolsListItems.get(position).createdAt);
                i.putExtra("updated_at", ourSchoolsListItems.get(position).updatedAt);

                startActivity(i);

            }
        });

        pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
        pDialog.setMessage("Loading…");
        pDialog.show();

// Creating volley request obj
        JsonArrayRequest billionaireReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                OurSchool ourSchool = new OurSchool();

                                ourSchool.schoolId=obj.getInt("id");
                                ourSchool.schoolName=obj.getString("name");
                                ourSchool.schoolLocation=obj.getString("location");
                                ourSchool.schoolLogo=obj.getString("logo");
                                ourSchool.schoolEmail=obj.getString("email");
                                ourSchool.schoolWebsite=obj.getString("website");
                                ourSchool.createdAt=obj.getString("created_at");
                                ourSchool.updatedAt=obj.getString("updated_at");

                            // adding schools to ourSchool list
                                ourSchoolsListItems.add(ourSchool);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

     // Adding request to request queue
        AppController.getInstance().addToRequestQueue(billionaireReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.schoolSearch:
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search, menu);
        return true;
    }
}

SchoolDetails.java

  package com.example.user.educationhunt;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.fragment.Admission;
import com.example.user.educationhunt.fragment.FeeStructure;
import com.example.user.educationhunt.fragment.Majors;
import com.example.user.educationhunt.pojos.OurSchool;

import org.junit.runner.Describable;

import java.util.ArrayList;
import java.util.List;

public class SchoolDetails extends AppCompatActivity{

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        About aboutFragment= (About) getSupportFragmentManager().findFragmentById(R.id.aboutFragment);
        aboutFragment.aboutSchoolName.setText("name:"+ getIntent().getStringExtra("name"));

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new About(), "ABOUT US");
        adapter.addFragment(new Admission(), "ADMISSION");
//        adapter.addFragment(new Majors(), "MAJORS");
        adapter.addFragment(new FeeStructure(), "FEE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

And finally this is my About Fragment

package com.example.user.educationhunt.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.user.educationhunt.R;
import com.example.user.educationhunt.School;
import com.example.user.educationhunt.SchoolDetails;
import com.example.user.educationhunt.pojos.OurSchool;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.junit.runner.Describable;

import java.io.Serializable;

/**
 * A simple {@link Fragment} subclass.
 */
public class About extends Fragment implements OnMapReadyCallback{

    MapView mapView;
    GoogleMap map;
    public TextView aboutSchoolName,aboutSchoolLocation,aboutSchoolNumber,aboutSchoolEmail,aboutSchoolWebsite,aboutSchoolCategory;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_about, container, false);

        aboutSchoolName= (TextView) v.findViewById(R.id.about_school_name);
        aboutSchoolLocation= (TextView) v.findViewById(R.id.about_school_location);
        aboutSchoolNumber= (TextView) v.findViewById(R.id.about_school_number);
        aboutSchoolCategory= (TextView) v.findViewById(R.id.about_school_category);
        aboutSchoolEmail= (TextView) v.findViewById(R.id.about_school_email);
        aboutSchoolWebsite= (TextView) v.findViewById(R.id.about_school_website);

//        School school=new School();
//        aboutSchoolName.setText("name:"+ school.getIntent().getStringExtra("name"));



        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        // Gets to GoogleMap from the MapView and does initialization stuff
        map = mapView.getMap();
        map.getUiSettings().setMyLocationButtonEnabled(false);
        map.setMyLocationEnabled(true);

        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        MapsInitializer.initialize(this.getActivity());

        // Updates the location and zoom of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(27.6933, 85.3211), 15);
        map.animateCamera(cameraUpdate);
        onMapReady(map);

        return v;
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.addMarker(new MarkerOptions()
                .position(new LatLng(27.6933, 85.3211))
                .title("St. Xavier's College"));
    }
}

Can somebody please help me out?

seon
  • 1,050
  • 2
  • 13
  • 27

2 Answers2

0

Try to get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments. Follow this, Where/How to getIntent().getExtras() in an Android Fragment?

Community
  • 1
  • 1
Priya Jagtap
  • 1,023
  • 13
  • 19
0

From Activity to Fragment

    About about = new About();
    Bundle args = new Bundle();
    args.putString("key", value);
    about.setArguments(args);

In Fragment

Bundle args = getArguments();
String value = args.getInt("key");
Arsen Sench
  • 438
  • 4
  • 18
  • please note that I wish to send data from an activity to a fragment which belongs to some other activity,Does the above code works on this scenario. – seon Nov 15 '16 at 08:19
  • send your data as u send from Activity A to Activity B with intent.putExtra. and for sending from the Activity B to Fragment use as i posted above. – Arsen Sench Nov 15 '16 at 08:25
  • Great to hear that. – Arsen Sench Nov 15 '16 at 09:07