ViewPager 片段

ViewPager Fragments

我的应用程序包含 3 个片段,第一个是从外部数据库填充的 ListFragment,第二个是地图,第三个是将报告添加到数据库中,这是我的代码:

MainActivity 的代码:

package info.androidhive.tabsswipe;

import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "My interventions", "MAP", "My report" };

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

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}

ListFragment 的代码:

package info.androidhive.tabsswipe;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class TopRatedFragment extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View myFragmentView = inflater.inflate(R.layout.fragment_top_rated,
                container, false);

        return myFragmentView;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }
    ArrayList<HashMap<String, String>> interventionsList;
    // Progress Dialog
    private ProgressDialog pDialog;
 // url to get all interventions list
    private static String url_all_interventions = "http://10.0.2.2/Scripts/liste_interventions.php";
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

     // interventions JSONArray
    JSONArray interventions = null;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        this.getListView().setTextFilterEnabled(true);

        // Hashmap for ListView
        interventionsList = new ArrayList<HashMap<String, String>>();

        // Loading interventions in Background Thread
        new LoadAllInterventions().execute();
    }
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllInterventions extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Loading interventions. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONArray json = jParser.makeHttpRequest(url_all_interventions, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Interventions: ", json.toString());

            try {

                    // Getting Array of interventions
                    JSONArray interventions = json;

                    // looping through All interventions
                    for (int i = 0; i < interventions.length(); i++) {
                        JSONObject c = interventions.getJSONObject(i);

                        // Storing each json item in variable
                        String  id = c.getString("id");
                        String name = c.getString("name");

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put("Int_id",   id);
                        map.put("Int_name", name);

                        // adding HashList to ArrayList
                        interventionsList.add(map);
                    }

            } 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
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            getActivity(), interventionsList,
                            R.layout.list_item, new String[] { "Int_id",
                                    "Int_name"},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                    Log.e("LIST", "setListAdapter is done");
                }
            });

        }

    }
    public void runOnUiThread(Runnable runnable) {
        // TODO Auto-generated method stub

    }

}

MoviesFragment 代码:

package info.androidhive.tabsswipe;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class MoviesFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View myFragmentView = inflater.inflate(R.layout.fragment_movies,
                container, false);

        return myFragmentView;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

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

        Button ajout=(Button)getActivity().findViewById(R.id.button1);
        ajout.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
              EditText code=(EditText)getActivity().findViewById(R.id.editText1);
              EditText lib=(EditText)getActivity().findViewById(R.id.editText2);
              EditText desc=(EditText)getActivity().findViewById(R.id.editText3);
              EditText st=(EditText)getActivity().findViewById(R.id.editText4);
              EditText act=(EditText)getActivity().findViewById(R.id.editText5);
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
              StringBuffer adresse= new StringBuffer("http://10.0.2.2:8080/Scripts/Create_Rapport.php?");
              adresse.append("code="+code.getText().toString());
              adresse.append("&lib="+lib.getText().toString());
              adresse.append("&desc="+desc.getText().toString());
              adresse.append("&state="+st.getText().toString());
            adresse.append("&action="+act.getText().toString());
              getPage(adresse.toString());
          }});
    }
    public void getPage(String adresse) {
    new Requete().execute(adresse);
}

    private class Requete extends AsyncTask<String, Void, String> { 
        @Override 
        protected String doInBackground(String... urls) {
            String response = ""; 
            for (String url : urls) { 
                DefaultHttpClient client = new DefaultHttpClient(); 
                HttpGet httpGet = new HttpGet(url); 
                try { 
                    HttpResponse execute = client.execute(httpGet);
                } 
                catch (Exception e) { 
                    e.printStackTrace(); 
                } 
            } 
            return response;
        } 
    }    
}

JSONParser 的代码:

package info.androidhive.tabsswipe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jArr = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONArray makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON array
        try {
            jArr = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jArr;

    }
}

TabsViewPager class的代码:

package info.androidhive.tabsswipe.adapter;

import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            // Top Rated fragment activity
            return new TopRatedFragment();
        case 1:
            // Games fragment activity
            return new GamesFragment();
        case 2:
            // Movies fragment activity
            return new MoviesFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 3;
    }

}

这是第三个片段的代码:

package info.androidhive.tabsswipe;

import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class GamesFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_games, container, false);

        return rootView;
    }
}

这也是 movies_fragment 布局的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#99E7E5"
    android:orientation="vertical">

   <Button
        android:id="@+id/btnCreateRapport"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Créer Rapport" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="Nom de l'intervention"
        android:textSize="17dip" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="19dp"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="Etat"
        android:textSize="17dip" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="20dp"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="Description"
        android:textSize="17dip" />

    <EditText
        android:id="@+id/inputAction"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/inputState"
        android:layout_margin="5dip"
        android:ems="10"
        android:singleLine="true" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="16dp"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="Action corrective"
        android:textSize="17dip" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="17dp"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:text="Date"
        android:textSize="17dip" />

    <EditText
        android:id="@+id/inputState"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/inputName"
        android:layout_margin="5dip"
        android:ems="10"
        android:singleLine="true" />

    <EditText
        android:id="@+id/inputDesc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/inputAction"
        android:layout_margin="5dip"
        android:ems="10"
        android:singleLine="true" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/inputDate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/inputDesc"
        android:layout_margin="5dip"
        android:ems="10"
        android:inputType="numberDecimal"
        android:singleLine="true" />

    <EditText
        android:id="@+id/inputName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_margin="5dip"
        android:ems="10"
        android:singleLine="true" />

</RelativeLayout>

当我 运行 应用程序时,第一个片段不会出现数据库中的列表,当我滑动到另一个片段时,应用程序关闭并且出现在 LogCat :

I/Choreographer(1708): Skipped 38 frames!  The application may be doing too much work on its main thread.
10-26 21:54:30.778: 
D/All Interventions:(1708): [{"id":"2","name":"request 2"},{"id":"1","name":"request 1"}]
10-26 21:54:44.788: 
I/Choreographer(1708): Skipped 60 frames!  The application may be doing too much work on its main thread.
10-26 21:54:48.671: 
D/AndroidRuntime(1708): Shutting down VM
10-26 21:54:48.671: 
W/dalvikvm(1708): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-26 21:54:48.948: 
E/AndroidRuntime(1708): FATAL EXCEPTION: main
10-26 21:54:48.948: 
E/AndroidRuntime(1708): java.lang.NullPointerException
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at info.androidhive.tabsswipe.MoviesFragment.onActivityCreated(MoviesFragment.java:41)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1486)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:550)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:509)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:490)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at info.androidhive.tabsswipe.MainActivity.onTabSelected(MainActivity.java:70)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:579)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1081)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:519)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.view.View.performClick(View.java:4204)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.view.View$PerformClick.run(View.java:17355)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.os.Handler.handleCallback(Handler.java:725)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.os.Looper.loop(Looper.java:137)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at android.app.ActivityThread.main(ActivityThread.java:5041)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at java.lang.reflect.Method.invokeNative(Native Method)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at java.lang.reflect.Method.invoke(Method.java:511)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-26 21:54:48.948: 
E/AndroidRuntime(1708):     at dalvik.system.NativeStart.main(Native Method)

有什么想法吗?

你的布局叫movies_layout还是layout_movies

在您的片段中,您将其设置为 fragment_movies 并将文件设置为 movies_fragment

在您的布局 movies_fragment.xml 中,您的按钮的 ID 为 btnCreateRapport 但在您的 MoviesFragment 代码中,您在第 40 行使用了 R.id.button1。由于此类按钮不存在,因此发生了空指针异常。将您的代码更改为

Button ajout=(Button)getActivity().findViewById(R.id.btnCreateRapport);