我创建了一个具有viewpager的fragmentactivity(MainActivity),因为我有3个listfragments。当在列表片段之一(AllPatient)中按下listitem时,会打开另一个片段活动(PrescAct),其中包含一个包含3个片段的viewpager。
我的问题是,当按下AllPatient列表项时,patient_id将传递给PrescAct,PrescAct又将该值传递给片段DocPresc。我在DocPresc.class中pid = b.getString("TAG_PATIENT_ID1");
获得Null Pointer Exception。
请建议,我在这个问题上坚持了很长时间。
以下是代码。
MainActivity FragmentActivity:
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
static AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
SearchView mSearchView;
MenuItem menuSearch;
Boolean flag = false;
String pid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupActionBar();
//getActionBar().setTitle("All Patients");
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setCurrentItem(0);
mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
public void onPageSelected(int position)
{
//mAppSectionsPagerAdapter.getItemPosition(getFragmentManager().findFragmentById(position));
//getActionBar().setTitle(mAppSectionsPagerAdapter.getPageTitle(position));
// getActionBar().setTitle(getTitle(position));
//mAppSectionsPagerAdapter.notifyDataSetChanged();
if(position==0){
getActionBar().setTitle("All Patients");
flag = true;
// menuSearch.setVisible(true);
//menuSearch.
invalidateOptionsMenu();
}
if(position==1){
getActionBar().setTitle("All Doctors");
flag=false;
// menuSearch.setVisible(false);
invalidateOptionsMenu();
}
else
getActionBar().setTitle("All Nurses");
invalidateOptionsMenu();
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageScrollStateChanged(int state)
{
if (state == ViewPager.SCROLL_STATE_DRAGGING)
{
}
if (state == ViewPager.SCROLL_STATE_IDLE)
{
}
}
});
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new AllPatient();
case 1:
//Intent intent = new Intent(MainActivity.this,abc.class);
return new AllDoctors();
case 2:
return new AllNurses();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
}
AllPatient ListFragment:
public class AllPatient extends ListFragment {
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String,String>>();
// url to get all products list
private static String url_all_patients = "http://192.168.44.208/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_PATIENT_NAME = "patient_name";
JSONArray products = null;
Context ctx;
String pid;
EditText inputSearch;
ListAdapter adapter;
ListView lv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.patient_list, container, false);
//ListView lv;
// lv = (ListView)view.findViewById(android.R.id.list);
//ListView v = getListView();
getActivity().getActionBar().setTitle("All Patients");
new LoadAllPatients().execute();
return view;
}
@Override
public void onListItemClick(ListView lv, View v, int position, long id) {
// TODO Auto-generated method stub
onAttach(getActivity());
//lv.setAdapter(adapter);
String id1 = ((TextView) v.findViewById(R.id.pid)).getText().toString();
System.out.println("all patient"+id1);
Bundle bundle = new Bundle();
bundle.putString("TAG_PATIENT_ID",id1 );
System.out.println("bundle"+id1);
Intent i = new Intent(getActivity(),PrescAct.class);
i.putExtras(bundle);
startActivity(i);
//passData(date);
Toast.makeText(
getActivity(),
getListView().getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
class LoadAllPatients extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_patients, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Patients: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PATIENT_ID).toUpperCase();
String name = c.getString(TAG_PATIENT_NAME).toUpperCase();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT_ID, id);
map.put(TAG_PATIENT_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
Collections.sort(productsList, new Comparator<Map<String, String>>() {
public int compare(Map<String, String> o1, Map<String, String> o2) {
String name1 = o1.get("patient_name");
String name2 = o2.get("patient_name");
if (name1 == null) return -1;
return name1.compareTo(name2);
}
});
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item1, new String[] { TAG_PATIENT_ID,
TAG_PATIENT_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
//setListAdapter(adapter);
setListAdapter(adapter);
inputSearch = (EditText)getView().findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//ListView lv = getListView();
((SimpleAdapter) getListAdapter()).getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
}
这是PrescAct FragmentActivity:
public class PrescAct extends FragmentActivity {
/** Called when the activity is first created. */
static AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
SearchView mSearchView;
MenuItem menuSearch;
Boolean flag = false;
String pid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prescact);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupActionBar();
//getActionBar().setTitle("All Patients");
// Getting value of pid from all patient
Intent i = getIntent();
Bundle extras = i.getExtras();
pid = extras.getString("TAG_PATIENT_ID");
System.out.println("Pid in prescact"+pid);
// Bundle bundle = new Bundle();
/* bundle.putString("TAG_PATIENT_ID",pid);
Intent m = new Intent(PrescAct.this,DocPresc1.class);
m.putExtras(bundle);*/
//Passing pid value to the list fragment
Bundle b = new Bundle();
b.putString("TAG_PATIENT_ID1",pid);
Fragment f = new DocPresc1();
f.setArguments(b);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager1);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setCurrentItem(2);
mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
public void onPageSelected(int position)
{
//mAppSectionsPagerAdapter.getItemPosition(getFragmentManager().findFragmentById(position));
//getActionBar().setTitle(mAppSectionsPagerAdapter.getPageTitle(position));
// getActionBar().setTitle(getTitle(position));
//mAppSectionsPagerAdapter.notifyDataSetChanged();
if(position==0){
getActionBar().setTitle("Prescription1");
flag = true;
// menuSearch.setVisible(true);
//menuSearch.
invalidateOptionsMenu();
}
if(position==1){
getActionBar().setTitle("Prescription2");
flag=false;
// menuSearch.setVisible(false);
invalidateOptionsMenu();
}
else
System.out.println("today fragment");
getActionBar().setTitle("Today's Prescription");
invalidateOptionsMenu();
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageScrollStateChanged(int state)
{
if (state == ViewPager.SCROLL_STATE_DRAGGING)
{
}
if (state == ViewPager.SCROLL_STATE_IDLE)
{
}
}
});
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new AllPatient();
case 1:
//Intent intent = new Intent(MainActivity.this,abc.class);
return new AllDoctors();
case 2:
System.out.println("today fragment called");
return new DocPresc1();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
这是DocPresc片段:
public class DocPresc1 extends ListFragment {
//public static Context ctx;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String,String>>();
String pid;
JSONArray products = null;
EditText ailm,date,comment;
Button delete;
ListAdapter adapter;
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_patient_presc = "http://192.168.44.208/get_prescription.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
// private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_AIL = "ailment";
private static final String[] TAG_MED = {"medicine_id","medicine_id2"};
private static final String TAG_D1 = "qty1";
private static final String TAG_D2 = "qty2";
private static final String TAG_D3 = "qty3";
private static final String TAG_DATE = "prescription_date";
private static final String TAG_COM = "comment";
private static final String TAG_PRESCRIPTION = "prescription_id";
//private static final String TAG_DID = "dosage_id";
// private static final String TAG_MED1_D1 = "m1dosage";
private static final String[] TAG_MED_D = {"m1dosage","m2dosage"};
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.docpresc1, container, false);
// setContentView(R.layout.docpresc);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
// Intent i = getIntent();
//Intent i = new Intent(getApplicationContext);//,PrescAct.class);
/* Bundle extras = i.getExtras();
pid = extras.getString("TAG_PATIENT_ID");*/
Bundle b = getArguments();
pid = b.getString("TAG_PATIENT_ID1");
// System.out.println("Docpresc"+pid);
// pid=getArguments().getString("TAG_PATIENT_ID1");
System.out.println("Docpresc"+pid);
// return inflater.inflate(R.layout.fragment, container, false);
ailm = (EditText)getView().findViewById(R.id.ailment1);
date = (EditText)getView().findViewById(R.id.date1);
comment = (EditText)getView().findViewById(R.id.comment1);
// if (savedInstanceState == null) {
new LoadPrescriptions().execute();
// }
return view;
// return inflater.inflate(R.layout.fragment, container, false);
}
class LoadPrescriptions extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
//pid=getArguments().getString("TAG_PATIENT_ID1");
// System.out.println("Docpresc"+pid);
// getting JSON string from URL
params.add(new BasicNameValuePair("patient_id",pid));//search1.getText().toString()));
System.out.println("database"+pid);
JSONObject json = jParser.makeHttpRequest(url_patient_presc, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Patients: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
//-----------------------------------
/*JSONObject product = products.getJSONObject(0);
ailm = (EditText)findViewById(R.id.ailment1);
ailm.setText(product.getString(TAG_AIL));*/
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
for(int m =0;m<2;m++){
String medicine = c.getString(TAG_MED[m]).toUpperCase();
String prescription = c.getString(TAG_PRESCRIPTION);
//String medicine[] = ((String) c.get(TAG_MED[i])).toUpperCase();
// String qty1 = c.getString(TAG_D1).toUpperCase();
// String qty2 = c.getString(TAG_D2).toUpperCase();
// String qty3 = c.getString(TAG_D3).toUpperCase();
String dosage = c.getString(TAG_MED_D[m]);
// String dsg_id = c.getString(TAG_DID).toUpperCase();
//String ail = c.getString(TAG_AIL).toUpperCase();
//getting 3 bytes from dosage1
String do1 = Character.toString(dosage.charAt(0));
String do2 = Character.toString(dosage.charAt(1));
String do3 = Character.toString(dosage.charAt(2));
//char do2 = dosage1.charAt(1);
//char do3 = dosage1.charAt(2);
ailm.setText(c.getString(TAG_AIL));
date.setText(c.getString(TAG_DATE));
comment.setText(c.getString(TAG_COM));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
System.out.println("medicine"+medicine+m);
if(medicine.equals("NULL")==false){
System.out.println("medicine in if"+medicine+m);
map.put(TAG_MED[i], medicine);
map.put(TAG_MED_D[i],dosage);
map.put(TAG_D1,do1);
map.put(TAG_D2,do2);
map.put(TAG_D3,do3);
map.put(TAG_PRESCRIPTION,prescription);
// map.put(TAG_DID,dsg_id);
//if(map.containsValue(null)==false)
// adding HashList to ArrayList
productsList.add(map);
//if (productsList.get(m).containsValue(null))
// productsList.remove(m);
System.out.println("productsList"+m+productsList);
}
}
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
//ListAdapter
adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item2, new String[] {
TAG_MED[0],TAG_D1,TAG_D2,TAG_D3,TAG_MED_D[0],TAG_PRESCRIPTION},
// TAG_MED,TAG_MED1_D1},
new int[] {R.id.med,R.id.d1,R.id.d2,R.id.d3,R.id.dos1,R.id.pres});
// new int[] {R.id.med,R.id.dos1});
// updating listview
//setListAdapter(adapter);
setListAdapter(adapter);
}
});
}
}
这是堆栈跟踪:
06-20 12:44:34.767: E/AndroidRuntime(9394): FATAL EXCEPTION: main
06-20 12:44:34.767: E/AndroidRuntime(9394): java.lang.NullPointerException
06-20 12:44:34.767: E/AndroidRuntime(9394): at com.example.actionbar.DocPresc1.onCreateView(DocPresc1.java:104)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1374)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.View.measure(View.java:15479)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.View.measure(View.java:15479)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4828)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.View.measure(View.java:15479)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.View.measure(View.java:15479)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4828)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-20 12:44:34.767: E/AndroidRuntime(9394): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2359)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.View.measure(View.java:15479)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1968)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1214)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1387)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4464)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.Choreographer.doFrame(Choreographer.java:525)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.os.Handler.handleCallback(Handler.java:615)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.os.Handler.dispatchMessage(Handler.java:92)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.os.Looper.loop(Looper.java:137)
06-20 12:44:34.767: E/AndroidRuntime(9394): at android.app.ActivityThread.main(ActivityThread.java:4895)
06-20 12:44:34.767: E/AndroidRuntime(9394): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 12:44:34.767: E/AndroidRuntime(9394): at java.lang.reflect.Method.invoke(Method.java:511)
06-20 12:44:34.767: E/AndroidRuntime(9394): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
06-20 12:44:34.767: E/AndroidRuntime(9394): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
06-20 12:44:34.767: E/AndroidRuntime(9394): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
ailm = (EditText)getView().findViewById(R.id.ailment1);
date = (EditText)getView().findViewById(R.id.date1);
comment = (EditText)getView().findViewById(R.id.comment1);
return view;
Fragment.getView()返回您在onCreateView中返回的内容,因此在onCreateView返回之前无法使用。改变这种方式
ailm = (EditText)view.findViewById(R.id.ailment1);
date = (EditText)view.findViewById(R.id.date1);
comment = (EditText)view.findViewById(R.id.comment1);
来自Android documentation:
Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.
Returns
The fragment's root view, or null if it has no layout.