在片段中的onPause中检索edittext值时发生NullPointerException

时间:2014-10-08 14:26:45

标签: android android-fragments nullpointerexception

我在viewpager中有3个标签片段。我将数据从第1和第2个片段发送到第3个片段。 我已经在第一个片段中使用自定义图库实现了图像选择(在此单击图像视图时,将显示自定义图库活动,然后所选图像显示在第一个片段中) 我有其他表单数据,我在onPause()方法中检索,我通过接口将此值传递给第3个片段(第1个片段 - >活动 - >第3个片段获取数据)

现在,当我没有点击imageview(即不去自定义图库活动)时,所有其他表单数据都会传递给第3个片段而没有任何问题。

但是当我点击imageview并访问自定义图库活动选择图像并回到我的第一个片段时..显然onPause在进入图库活动之前被调用.. 我使用try-catch处理异常的地方

但问题是在我之后我填写第一个片段的其他表单数据没有被传递到第三个片段,即使我在首先选择图像后填充它们。

当我从第一个片段访问自定义图库活动时,我在第三个片段中获得空值。

我使用log来调试值..我发现其中一个表单数据值被打印但是在下一刻它显示" ++ LOG:条目损坏或截断"

我研究了这个错误,我发现当值太大或值为null时会发生这种情况。 此外,我在第3个片段中收到无效数字格式:无效的int"" ,其中我试图获取第1个片段的表单数据整数值之一。日志和上面的异常清楚地表明了它,因为我在我的第3个片段中得到了空值..

请帮助我应该采用什么方法?实现我的需要。因为我是碎片的新手我在某个地方出错了..

这是我的TabActivity - > SubmitPostActivity

    package com.jbandroid;

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

import com.jbandroid.model.TabsPagerAdapter;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import com.jbandroid.fragment.*;
import com.jbandroid.gallery.CustomGallery;

public class SubmitPostActivity extends FragmentActivity implements ActionBar.TabListener,PostInfoFragment.setPostInfo,LocationInfoFragment.setLocationInfo{

    private ViewPager viewpager;
    private ActionBar actionBar;
    private TabsPagerAdapter mAdapter;
     FragmentManager manager;
     PersonalInfoFragment frag;


    //Tab titles
    private String[] tabs  = {"Post Info" , "Location Info" , "Personal Info" };


    //defining form input variables
    /*private String post_title,post_desc,post_start_date,post_end_date,post_country,post_city,post_area,
    post_user_name,post_user_email,post_user_phone;

    private int post_category_id, post_image,post_price, post_quantity;*/

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

        viewpager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        manager = getSupportFragmentManager();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
        //viewpager.setOffscreenPageLimit(2);
        viewpager.setAdapter(mAdapter);

        //actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        for (String tab : tabs){
            actionBar.addTab(actionBar.newTab().setText(tab).setTabListener(this));
        }

        if(savedInstanceState != null){
            actionBar.setSelectedNavigationItem( savedInstanceState.getInt("tab",0));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */

        viewpager.setOnPageChangeListener(new 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
    protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }


    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view

        viewpager.setCurrentItem(tab.getPosition());

    }


    @Override
    public void pass_location_details(String country, String city, String area) {

         frag = (PersonalInfoFragment) manager.findFragmentByTag("android:switcher:" + viewpager.getId() + ":" + 2);
        frag.get_post_location_details(country, city, area);
        Log.d("submitarea", area);
    }

    @Override
    public void pass_post_details(List<String> post_details) {
         frag = (PersonalInfoFragment) manager.findFragmentByTag("android:switcher:" + viewpager.getId() + ":" + 2);
            frag.get_post_details(post_details);
            Log.d("submitpostinfo","hello"+ post_details.get(5));
    }


}

这是我的第一个片段 - &gt; PostInfoFragment。我试图缩短代码。

  package com.jbandroid.fragment;

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

import com.jbandroid.R;
import com.jbandroid.SubmitPostActivity;
import com.jbandroid.gallery.Action;
import com.jbandroid.gallery.CustomGallery;
import com.jbandroid.gallery.CustomGalleryAdapter;


import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import android.support.v4.app.Fragment;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.ViewSwitcher;

public class PostInfoFragment extends Fragment {

    private MenuItem myActionMenuItem;
      private Button myActionButton;
      private ActionBar actionBar;
      private String post_title,post_desc,post_price,post_quantity,post_category_id;
    //  int  post_category_id = 0;

      private EditText submit_post_title,submit_post_desc,
      submit_post_total_price,submit_post_total_quantity;

    private SubmitPostActivity s;
    setPostInfo info;
    List<String> post_details;

    private LinearLayout submit_post_total_quantity_linear;

    ImageView submit_post_img;
    private ImageLoader imageLoader;
    private Handler handler;
    private GridView gridGallery;
    private CustomGalleryAdapter adapter;
    private ViewSwitcher viewSwitcher;
    private ImageView imgSinglePick;
    private ArrayList<CustomGallery> dataT;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_post_info, container, false);
        initImageLoader();
        gridGallery = (GridView)rootView.findViewById(R.id.imgGridGallery);

handler = new Handler();

        gridGallery.setFastScrollEnabled(true);
        adapter = new CustomGalleryAdapter(getActivity(), imageLoader);
        adapter.setMultiplePick(false);
        gridGallery.setAdapter(adapter);

        viewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher);
        viewSwitcher.setDisplayedChild(1);

        imgSinglePick = (ImageView)rootView. findViewById(R.id.imgSinglePick);


        //s = (SubmitPostActivity)getActivity();
         submit_post_title = (EditText)rootView.findViewById(R.id.submit_post_title);
         submit_post_desc = (EditText)rootView.findViewById(R.id.submit_post_description);

         submit_post_total_price  = (EditText)rootView.findViewById(R.id.submit_post_total_price);
         submit_post_total_quantity = (EditText)rootView.findViewById(R.id.submit_post_total_quantity);

         submit_post_total_quantity_linear = (LinearLayout)rootView.findViewById(R.id.submit_post_total_qty_linear);


        actionBar = getActivity().getActionBar();
        setHasOptionsMenu(true);


        post_details = new ArrayList<String>();
         res = getResources();


        setListeners();



        return rootView;

    }


    private void setListeners(){
        gridGallery.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int postion,
                    long id) {

                Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);

                startActivityForResult(i, 200);

            }
        });


imgSinglePick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
                startActivityForResult(i, 200);


                /*for single pick
                 * Intent i = new Intent(Action.ACTION_PICK);
                startActivityForResult(i, 100);*/
            }
        });


final TypedArray selectedValues = res.obtainTypedArray(R.array.categoryValues);


submit_post_total_quantity_linear.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        submit_post_total_quantity.requestFocus();
    }
});

}


    private void initImageLoader() {
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
        .cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
        .bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
        getActivity()).defaultDisplayImageOptions(defaultOptions).memoryCache(
        new WeakMemoryCache());

ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);       
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {


         if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
                String[] all_path = data.getStringArrayExtra("allpath");

                 dataT = new ArrayList<CustomGallery>();

                for (String string : all_path) {
                    CustomGallery item = new CustomGallery();
                    item.sdcardPath = string;
                    dataT.add(item);
                    Log.d("selected", string);
                }

                viewSwitcher.setDisplayedChild(0);
                adapter.addAll(dataT);
            }else if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
                adapter.clear();

                viewSwitcher.setDisplayedChild(1);
                String single_path = data.getStringExtra("single_path");
                imageLoader.displayImage("file://" + single_path, imgSinglePick);

            }else{
                super.onActivityResult(requestCode, resultCode, data);
            }


    }



    public interface setPostInfo{
        public void pass_post_details(List<String> post_details);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try{
        info = (setPostInfo)activity;
        }catch(ClassCastException e){

            throw new ClassCastException(activity.toString() + "must implemet setPostInfo");
        }
    }

    @Override
    public void onPause() {
           super.onPause();


           passFormInputs();

    }





    private void passFormInputs(){
        try{
            post_title = submit_post_title.getText().toString();
            post_desc = submit_post_desc.getText().toString();

            post_price = submit_post_total_price.getText().toString();
            post_quantity = submit_post_total_quantity.getText().toString();


            post_details.add(post_title);

            post_details.add(post_desc);

            post_details.add(post_quantity);

            post_details.add(post_price);

            post_details.add(post_category_id);
            Log.d("post_info", "hello"+ post_details.get(2) );
            Log.d("post_info1", "llo"+ post_quantity );
            info.pass_post_details(post_details);

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


}

2nd Fragment也有3-4个字段并将这些数据传递给第3个片段..

这是我的第3片段 - &gt; PersonalInfoFragment

   package com.jbandroid.fragment;

import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;

import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.jbandroid.PostActivity;
import com.jbandroid.R;
import com.jbandroid.gallery.CustomGallery;
import com.jbandroid.mobileservice.Post;
import com.jbandroid.model.ToastActivity;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableOperationCallback;
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.blob.*;

public class PersonalInfoFragment extends Fragment {

    private MenuItem myActionMenuItem;
      private Button myActionButton;
     private ActionBar actionBar;

      List<String> post_details;
      ArrayList<CustomGallery> selected;
      private MobileServiceClient mClient;
    private MobileServiceTable<Post> post_table;
    String country,city,area,user_name,user_email,user_phone;
    Post post;
    private EditText submit_post_user_name;
    private EditText submit_post_user_email;
    private EditText submit_post_user_phone;
    ToastActivity toastActivity;
    private CloudStorageAccount storageAccount;

    List<String> imageName;



    CloudBlobClient blobClient;
    CloudBlobContainer blobContainer;
    BlobContainerPermissions containerPermissions;

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

        View rootView = inflater.inflate(R.layout.fragment_personal_info,container,false);
        actionBar = getActivity().getActionBar();
        setHasOptionsMenu(true);


        imageName = new ArrayList<String>();


        submit_post_user_name = (EditText)rootView.findViewById(R.id.submit_post_user_name);
        submit_post_user_email = (EditText)rootView.findViewById(R.id.submit_post_user_email);
        submit_post_user_phone = (EditText)rootView.findViewById(R.id.submit_post_user_phone);
        toastActivity =  new ToastActivity();





        post = new Post();

        return rootView;
    }

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

    }

    public void get_post_details(List<String> post_details){
        this.post_details = post_details;
    //  this.selected = selected;
        Log.d("personalfrag(postinfo)", post_details.get(5));
    }

    public void get_post_location_details(String country,String city,String area){
        this.country = country;
        this.city = city;
        this.area = area;
        Log.d("personal", area);
    }

    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
         super.onCreateOptionsMenu(menu, inflater);

            // Inflate the menu items for use in the action bar

            inflater.inflate(R.menu.mymenu, menu);

            // Here we get the action view we defined
            myActionMenuItem = menu.findItem(R.id.my_action);
            View actionView = myActionMenuItem.getActionView();

            // We then get the button view that is part of the action view
            if(actionView != null) {
              myActionButton = (Button) actionView.findViewById(R.id.action_btn);
              myActionButton.setText(R.string.txt_submit);
              if(myActionButton != null) {
                // We set a listener that will be called when the return/enter key is pressed
                myActionButton.setOnClickListener(new OnClickListener() {


                    @Override
                    public void onClick(View v) {

                        myActionButton.setEnabled(false);

                        myActionButton.setText("Submitting..");

                        setPostItems();

                        insertintodb();

                        Log.d("postinfo",post_details.get(2));

                    //toastActivity.displayToast(getActivity(), post_details.get(0));
                    }
                });

              }
            }
    }

    public void setPostItems(){
        user_name = submit_post_user_name.getText().toString();
        user_email = submit_post_user_email.getText().toString();
        user_phone = submit_post_user_phone.getText().toString();

        //this values are from 1st fragment
        post.setPost_name(post_details.get(0));

        post.setPost_description(post_details.get(1));

        post.setPost_totalquantity((Integer.valueOf(post_details.get(2))).intValue());

        post.setPost_total_price((Integer.valueOf(post_details.get(3))).intValue());

        post.setCategory_id((Integer.valueOf(post_details.get(4))).intValue());

        //this values are from 2nd fragment
        post.setPost_country(country);
        post.setPost_city(city);
        post.setPost_area(area);

        //this values are from this fragment
        post.setPost_user_name(user_name);
        post.setPost_user_email(user_email);
        post.setPost_user_phone(user_phone);
        post.setPost_user_id(1);


    }

    public void insertintodb(){
        if(mClient == null)
        {
            return;
        }


        if(isOnline()){
            post_table.insert(post, new TableOperationCallback<Post>() {

                @Override
                public void onCompleted(Post post, Exception exception,
                        ServiceFilterResponse response) {

                    if(exception == null){

                        toastActivity.displayToast(getActivity(), "Post Submitted");

                    }else{
                        //toastActivity.displayToast(getActivity(), "Error:"+exception.toString());
                        toastActivity.displayToast(getActivity(), "Problem Connecting to Server");
                        Log.d("error",exception.toString(),exception.getCause());
                    }
                }
            });

            }else{
                toastActivity.displayToast(getActivity(), "Sorry! No internet connection");
            }

        myActionButton.setEnabled(true);
        myActionButton.setText(R.string.txt_submit);

    }


    public boolean isOnline() {
        ConnectivityManager cm =
            (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

}

堆栈跟踪:

     10-09 12:14:57.221: D/personal(546): Vasai
10-09 12:14:57.231: D/submitarea(546): Vasai
10-09 12:14:59.751: D/post_info(546): hello
10-09 12:14:59.751: D/post_info1(546): llo45
10-09 12:14:59.751: D/post_info1(546): +++ LOG: entry corrupt or truncated
10-09 12:14:59.761: D/submitpostinfo(546): hello
10-09 12:15:08.260: D/AndroidRuntime(546): Shutting down VM
10-09 12:15:08.260: W/dalvikvm(546): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
10-09 12:15:08.300: E/AndroidRuntime(546): FATAL EXCEPTION: main
10-09 12:15:08.300: E/AndroidRuntime(546): java.lang.NumberFormatException: Invalid int: ""
10-09 12:15:08.300: E/AndroidRuntime(546):  at java.lang.Integer.invalidInt(Integer.java:138)
10-09 12:15:08.300: E/AndroidRuntime(546):  at java.lang.Integer.parseInt(Integer.java:359)
10-09 12:15:08.300: E/AndroidRuntime(546):  at java.lang.Integer.parseInt(Integer.java:332)
10-09 12:15:08.300: E/AndroidRuntime(546):  at java.lang.Integer.valueOf(Integer.java:490)
10-09 12:15:08.300: E/AndroidRuntime(546):  at com.jbandroid.fragment.PersonalInfoFragment.setPostItems(PersonalInfoFragment.java:198)
10-09 12:15:08.300: E/AndroidRuntime(546):  at com.jbandroid.fragment.PersonalInfoFragment$1.onClick(PersonalInfoFragment.java:177)
10-09 12:15:08.300: E/AndroidRuntime(546):  at android.view.View.performClick(View.java:3480)
10-09 12:15:08.300: E/AndroidRuntime(546):  at android.view.View$PerformClick.run(View.java:13983)
10-09 12:15:08.300: E/AndroidRuntime(546):  at android.os.Handler.handleCallback(Handler.java:605)
10-09 12:15:08.300: E/AndroidRuntime(546):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-09 12:15:08.300: E/AndroidRuntime(546):  at android.os.Looper.loop(Looper.java:137)
10-09 12:15:08.300: E/AndroidRuntime(546):  at android.app.ActivityThread.main(ActivityThread.java:4340)
10-09 12:15:08.300: E/AndroidRuntime(546):  at java.lang.reflect.Method.invokeNative(Native Method)
10-09 12:15:08.300: E/AndroidRuntime(546):  at java.lang.reflect.Method.invoke(Method.java:511)
10-09 12:15:08.300: E/AndroidRuntime(546):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-09 12:15:08.300: E/AndroidRuntime(546):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-09 12:15:08.300: E/AndroidRuntime(546):  at dalvik.system.NativeStart.main(Native Method)
10-09 12:15:11.705: D/gralloc_goldfish(576): Emulator without GPU emulation detected.

你也可以在stacktrace中看到..

Log.d("post_info", "hello"+ post_details.get(2) );
Log.d("post_info1", "llo"+ post_quantity );
当post_details.get(2)为空时,正在打印post_quantity值。不能理解这种行为。

更新:我发现了问题(这是不正确的异常处理)..当我从第一个片段开始自定义图库活动时... onPause被调用..在这里我不处理正确的例外,因为我的列表正在填充空数据..所有的add函数都被调用,然后抛出异常..行中抛出异常

    info.pass_post_details(post_details);

在passFormInputs()方法..所以这行之前的代码无论如何都要执行..下次再次调用onPause时..现在实际上我的实际值被添加到空值下面的列表中。我在mmy列表中总共有10个值,当我尝试打印第11个值时,我打印了第一个值..

1 个答案:

答案 0 :(得分:0)

正如堆栈跟踪所示。这是一个NumberFormatException, invalid int ""。在PersonalInfoFragment

您的代码问题在于,您在调用post_items.get(2);之前调用Integer.valueOf()时从未检查过返回的内容。

我的建议是在调用post_items.get(2)之前检查从Integer.valueOf()返回的内容,并在try-catch块中包装Integer.valueOf

String quantityStr = post_details.get(2);
if(quantityStr != null && quantityStr.length() > 0)
{
    try{
        int qty = Integer.valueOf(quantityStr);
        //Do your logic.
    }catch(NumberFormatException e)
    {
        //Unable to parse, not a valid int
    }
}