如何在片段中显示api服务

时间:2015-07-30 15:44:09

标签: java android api android-fragments

我在MainActivity中通过片段制作了3个标签,我想在其中一个片段中使用Yahoo weather API来显示简单的天气预报。当我运行代码时,应用程序已停止并获得 NullPointerException

07-30 16:27:34.719  11633-11633/com.example.frank.prototype3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.example.frank.prototype3.fragments.ActivityFragment.onCreate(ActivityFragment.java:73)
            at android.support.v4.app.Fragment.performCreate(Fragment.java:1766)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
            at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:846)
            at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:860)
            at android.support.v4.app.FragmentStatePagerAdapter.setPrimaryItem(FragmentStatePagerAdapter.java:152)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1103)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
            at android.view.View.measure(View.java:15483)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
            at android.view.View.measure(View.java:15483)
            at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:868)
            at android.view.View.measure(View.java:15483)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4843)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:15483)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4843)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
            at android.view.View.measure(View.java:15483)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4843)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:15483)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4843)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
            at android.view.View.measure(View.java:15483)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4843)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2192)
            at android.view.View.measure(View.java:15483)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1891)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1286)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4293)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
            at android.view.Choreographer.doCallbacks(Choreographer.java:555)
            at android.view.Choreographer.doFrame(Choreographer.java:525)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4866)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

这是我的MainActivity

public class MainActivity extends ActionBarActivity {

private Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;

public static final int ACTIVITY = 0;
public static final int GROUP = 1;
public static final int RECORD = 2;


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

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);

    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
    mTabs.setDistributeEvenly(true);
    mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabText);

    mTabs.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
    mTabs.setViewPager(mPager);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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;
    }

    if(id == R.id.navigate){
        startActivity(new Intent(this, SubActivity.class));
    }

    return super.onOptionsItemSelected(item);
}

class MyPagerAdapter extends FragmentStatePagerAdapter {

    int icons[] = {R.mipmap.ic_action_record, R.mipmap.ic_action_bike, R.mipmap.ic_action_group};
    String[] tabText = getResources().getStringArray(R.array.tabs);

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        tabText = getResources().getStringArray(R.array.tabs);
    }

    @Override
    public Fragment getItem(int num) {
        Fragment fragment = null;
        switch(num){
            case RECORD:
                 fragment = RecordFragment.newInstance("","");
                break;
            case ACTIVITY:
                  fragment = ActivityFragment.newInstance("","");
                break;
            case GROUP:
                 fragment = GroupFragment.newInstance("","");
        }
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Drawable drawable = getResources().getDrawable(icons[position]);
        drawable.setBounds(0,0,36,36);
        ImageSpan imageSpan = new ImageSpan(drawable);
        SpannableString spannableString = new SpannableString(" ");
        spannableString.setSpan(imageSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @Override
    public int getCount() {
        return 3;
    }
}

public static class MyFragment extends Fragment {
    private TextView textView;

    public static MyFragment getInstance(int position){
        MyFragment myFragment = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("position",position);
        myFragment.setArguments(args);
        return myFragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_my, container, false);
        textView = (TextView) layout.findViewById(R.id.position);
        Bundle bundle = getArguments();
        if(bundle !=null){
            textView.setText("The page selected is" + bundle.getInt("position"));
        }
        return layout;
    }
}

}

这是我想要参与api,ActivityFragment

的片段类之一
public class ActivityFragment extends Fragment implements WeatherServiceCallBack{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private ImageView weatherIconImageView;
private TextView temperatureTextView;
private TextView conditionTextView;
private TextView locationTextView;

private WeatherService service;
private ProgressDialog dialog;

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;


/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment ActivityFragment.
 */
// TODO: Rename and change types and number of parameters
public static ActivityFragment newInstance(String param1, String param2) {
    ActivityFragment fragment = new ActivityFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    weatherIconImageView = (ImageView) getView().findViewById(R.id.weatherIconImageView);
    temperatureTextView = (TextView) getView().findViewById(R.id.temperatureTextView);
    conditionTextView = (TextView) getView().findViewById(R.id.conditionTextView);
    locationTextView = (TextView) getView().findViewById(R.id.locationTextView);

    service = new WeatherService(this, getActivity());
    dialog = new ProgressDialog(getActivity());
    dialog.setMessage("Loading...");
    dialog.show();

    service.refreshWeather("Austin, TX");
}

@Override
public void serviceSuccess(Channel channel) {
    dialog.hide();

    Item item = channel.getItem();

    int resourceId = getResources().getIdentifier("drawable/icon_" + item.getCondition().getCode(), null, getActivity().getPackageName());

    @SuppressWarnings("deprecation")
    Drawable weatherIconDrawble = getResources().getDrawable(resourceId);

    weatherIconImageView.setImageDrawable(weatherIconDrawble);

    temperatureTextView.setText(item.getCondition().getTemperature() + "\u00B0" + channel.getUnits().getTemperature());
    conditionTextView.setText(item.getCondition().getDescription());
    locationTextView.setText(channel.getLocation());
}

@Override
public void serviceFailure(Exception exception) {
    dialog.hide();
    Toast.makeText(getActivity(), exception.getMessage(), Toast.LENGTH_LONG).show();
}

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

我是Android的初学者,现在非常困惑。我需要你们的帮助,非常感谢!

0 个答案:

没有答案