2014-10-08 37 views
0

我在viewpager中有3個選項卡片段。我將數據從第一個和第二個片段發送到第三個片段。 我已經實現了使用第一個片段中的自定義畫廊的圖像選擇(在這點擊圖像視圖上顯示自定義畫廊活動,然後選定的圖像顯示在第一個片段) 我有其他形式的數據,我檢索onPause()方法,我通過接口將此值傳遞給第三個片段(第一個fragment-> activity-> 3rd片段獲取數據)NullPointerException異常,同時檢索onPause中的編輯文本值

現在,當我不點擊圖像視圖(即不去圖像自定義活動)所有其他表單數據都傳遞給第三個片段而沒有問題。

但是當我點擊的ImageView,並參觀定製畫廊活動選擇圖像和回來我的第一fragment..obviously的onPause之前去畫廊活動.. 這裏我使用的try-catch

處理異常被稱爲

但是問題出在這之後,我在第一個片段中填充的其他表單數據沒有被傳遞到第三個片段,即使我先選擇圖像後填充它們。

當我從第一個訪問自定義圖庫活動時,我在第三個片段中獲得了空值。

我使用日誌調試值..我發現,表單數據值之一是印刷,但在非常下一刻它顯示「++ LOG:項損壞或截斷」

我研究了這個錯誤,我發現這種情況發生時,無論是價值太大或價值爲空.. 也我收到無效的數字格式:無效int「」在我的第三個片段,我試圖讓其中之一形式數據的第一個片段的整數值.Log和上面的異常清楚地表明它的原因是我在我的第三個片段中得到了空值..

請幫我用什麼方法?爲了達到我需要的。因爲我是在片段一個新手,我錯了地方..

這是我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)); 
    } 


} 

這是我的第一個片段 - > 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(); 
      } 
    } 


} 

第二個片段也有一些3-4場,然後把這些數據到第3段..

這是我的第三個片段 - > 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. 

你也可以在堆棧跟蹤中看到..

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

post_quantity值正在打印,而post_details.get(2)是空的..不理解此行爲。

更新:我發現問題(這是不正當的異常處理)..當我從我的第一個片段去自定義畫廊活動.. onPause被調用..並且在這裏我沒有正確處理異常我的列表正在填充空數據..所有的add函數都被調用,然後拋出異常拋出異常的行

info.pass_post_details(post_details); 
在passFormInputs

()方法..所以這行之前的代碼,現在實際上我真正的價值被添加在onPause時再次調用下一次無論如何.. executed..now在下面的列表中的空值。我在mmy列表中總共有10個值,當我試圖打印第11個值時,我打印了第一個值。

+0

一些代碼,堆棧跟蹤將有助於診斷此問題。 – 2014-10-08 15:40:05

+0

okk會添加幾個 – 2014-10-09 05:44:40

回答

0

由於堆棧跟蹤提示。這是一個NumberFormatException, invalid int ""。在PersonalInfoFragment

你的代碼的問題是你在調用Integer.valueOf()之前從來沒有通過調用post_items.get(2);來檢查返回的是什麼。

我的建議是檢查什麼是從post_items.get(2)返回調用Integer.valueOf()之前,敷Integer.valueOf在try-catch塊

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 
    } 
} 
+0

其給予無效的int「」..因爲值是空的..cz我甚至試圖打印它的字符串值附加它與hello..hello正在打印,但不是這個值..這意味着該字符串是空的..我試圖將一個空值轉換爲整數,因此導致numberformatexception .. – 2014-10-09 07:27:46

+0

我添加了這個在我的按鈕點擊.. String quantityStr = post_details.get(5); \t \t \t \t \t \t如果(quantityStr!= NULL && quantityStr.length()> 0) \t \t \t \t \t \t { \t \t \t \t \t \t嘗試{ \t \t \t \t \t \t INT數量=整數.valueOf(quantityStr); \t \t \t \t \t \t //做你的邏輯。 \t \t \t \t \t \t Log.d(「personal(insidesubmit)」,「qty is not null」); \t \t \t \t \t \t toastActivity。displayToast(getActivity(),「qty不爲空」); \t \t \t \t \t \t}趕上(NumberFormatException的E) \t \t \t \t \t \t { \t \t \t \t \t \t //無法解析,而不是一個有效的int \t \t \t \t \t \t}} 其他{ \t \t \t \t \t \t \t Log.d(「personal(insidesubmit)」,「qty is null」);} 和我的「qty爲null」在我的日誌中。 – 2014-10-09 07:37:54