listview findviewbyId返回null。当片段生成布局时

时间:2014-05-09 04:11:30

标签: android listview android-fragments

我试图将布局加载到由片段生成的列表视图中。在加载了listview的片段之后。我调用异步来在mainactivity中由fragment生成的listview中插入数据。但是listview在这里返回null是我的代码。

主要活动:当用户选择导航栏的菜单时,会调用该片段。

package medapp.app;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
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.ArrayAdapter;
import android.widget.ListView;

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


public class MainActivity extends Activity
{
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mActions;

    public JSONArray blogPostData;
    View v;

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

        mTitle = mDrawerTitle = getTitle();
        mActions = getResources().getStringArray(R.array.action_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mActions));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null)
        {
            selectItem(0);

        }



    }

    //public void onItemClick(AdapterView<?> adapter, View view,int position, long id)
    //{
    //    Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
    //            Toast.LENGTH_SHORT).show();
    //}

    public void articleList()
    {
        if (blogPostData == null)
        {
            //
        }
        else
        {
            try
            {
                String[] blogPostTitle = new String[blogPostData.length()];
                for (int i = 0; i < blogPostData.length(); i++)
                {
                    JSONObject jsonObject = blogPostData.getJSONObject(i);
                    String title = jsonObject.getString("title");
                    title = Html.fromHtml(title).toString();
                    blogPostTitle[i] = title;
                }

                ListView listView1 = (ListView) findViewById(R.id.article_list);

                ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this, R.layout.layout_listitem, R.id.titleTV, blogPostTitle);
                listView1.setAdapter(arrayAdapter1);
                Log.e("MESSAGE", "JSON " + blogPostData);


            } catch (JSONException e) {
                Log.e("TAG", "Exception Caught: ", e);
            }
        }
    }

    public void signInClick(View v) {
        //Button button = (Button) v;
        //startActivity(new Intent(getApplicationContext(), PatientActivity.class));
    }

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

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        //boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        return super.onPrepareOptionsMenu(menu);
    }


    /* */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
                return super.onOptionsItemSelected(item);
    }


    /* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        int pos;

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
            v = view;
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments

        Fragment fragment = new ActionFragment();
        Bundle args = new Bundle();
        args.putInt(ActionFragment.ARG_ACTION1_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mActions[position]);
        mDrawerLayout.closeDrawer(mDrawerList);

        if (position == 1)
        {
            PostController postController = new PostController();
            postController.execute();
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

这是调用要显示的布局然后返回主活动的片段。

package medapp.app;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ActionFragment extends Fragment
{
    protected View rootView;

    public static final String ARG_ACTION1_NUMBER = "Fragment_layout";

    /*public JSONArray blogData;
    public String[] blogPostTitle;*/

    public ActionFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_layout, container, false);
        int i = getArguments().getInt(ARG_ACTION1_NUMBER);

        if (i == 0)
        {
            rootView = inflater.inflate(R.layout.fragment_layout, container, false);
        }
        else if (i == 1) {
            rootView = inflater.inflate(R.layout.fragment_articles, container, false);


            //ListView listView1 = (ListView) rootView.findViewById(R.id.article_list);
            //ArrayAdapter<Layout> arrayAdapter1 = new ArrayAdapter<Layout>(getActivity(), R.layout.layout_listitem);
            //listView1.setAdapter(arrayAdapter1);

        } else if (i == 2)
        {
            rootView = inflater.inflate(R.layout.fragment_news, container, false);
        } else if (i == 3) {
            rootView = inflater.inflate(R.layout.fragment_signin, container, false);
        }
        return rootView;
    }
}

然后主活动调用异步背景来获取数据。

package medapp.app;

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;

/**
 * Created by MacBookPro on 5/8/14.
 */
public class PostController extends AsyncTask<Object, Void, JSONArray> {



    @Override
    protected JSONArray doInBackground(Object... arg0)
    {

        String result = "No data available";
        JSONArray jsonResponse = null;

        try
        {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            //TODO: URL ADDRESS for Articles.
            HttpGet httpGet = new HttpGet("http://localhost/medapp/public/webservices/post");
            httpGet.setHeader("Content-type", "application/json");

            InputStream inputStream = null;

            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            result = sb.toString();
            jsonResponse = new JSONArray(result);

            // TODO: Remove log.
            Log.d("TAG", String.valueOf(jsonResponse));
        }
        catch (MalformedURLException e)
        {
            Log.e("TAG", "exception caught: ", e);
        }
        catch (IOException e)
        {
            Log.e("TAG", "exception caught: ", e);
        }
        catch (Exception e)
        {
            Log.e("TAG", "exception caught: ", e);
        }
        return jsonResponse;
    }

    @Override
    protected void onPostExecute(JSONArray result)
    {
        MainActivity mainActivity = new MainActivity();
        mainActivity.blogPostData = result;

        mainActivity.articleList();
    }
}

日志文件::

05-09 05:59:59.249    1474-1474/medapp.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: medapp.app, PID: 1474
    java.lang.NullPointerException
            at android.app.Activity.findViewById(Activity.java:1884)
            at medapp.app.MainActivity.articleList(MainActivity.java:116)
            at medapp.app.PostController.onPostExecute(PostController.java:82)
            at medapp.app.PostController.onPostExecute(PostController.java:22)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案