2017-02-11 89 views
-1

我正在開發一個電子商務應用程序,其中大部分的Java類文件使用異步任務從服務器獲取數據,我在所有Java類中使用片段。我的問題是,當我點擊OnBackPressed它顯示了在異步任務線錯誤,因爲它再次需要一定的時間間隔從服務器獲取數據..onBackPressed()不幸的應用程序已停止在Android手機

MainActivity.java

package com.prashant; 
import android.app.SearchManager; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.graphics.Color; 
import android.graphics.drawable.ColorDrawable; 
import android.support.v4.app.Fragment; 

import android.support.v4.app.FragmentManager; 
import android.support.v4.view.MenuItemCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.SearchView; 

import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.AdapterView; 
import android.os.Handler; 
import android.widget.GridView; 
import android.widget.ProgressBar; 
import android.widget.RelativeLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

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


public class MainActivity extends AppCompatActivity implements android.support.v7.app.ActionBar.OnNavigationListener { 
    TextView txtView; 
    private static MainActivity sMainActivity; 
    ProgressBar prgLoading; 
    RelativeLayout drawerPane; 
    DrawerLayout drawerLayout; 

    GridView lvNav; 

    TextView Customer_name; 
    TextView Customer_email; 
    TextView Customer_mob; 

    List<NavItem> listNavItems; 
    List<Fragment> listFragment; 
    private Boolean exit = false; 

    ActionBarDrawerToggle actionBarDrawerToggle; 

    public int hot_number = Constants.ProductCart_Id.size(); 
    private TextView ui_hot = null; 

    private boolean mNaviFirstHit = true; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     sMainActivity = this; 
     // Styling Action Bar 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

     getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.rgb(7,112,200))); 


     drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     //Getting Session Information Of Customer 
     String MyPREFERENCES = "CustomerData"; 
     SharedPreferences sharedpreferences =getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 

     Constants.Customer_FirstName= sharedpreferences.getString("Customer_FirstName",""); 
     Constants.Customer_LastName=sharedpreferences.getString("Customer_LastName", ""); 
     Constants.Customer_MobileNo=sharedpreferences.getString("Customer_MobileNo", ""); 

     Constants.Customer_Id=sharedpreferences.getInt("Customer_Id", 0); 
     Constants.Customer_Email=sharedpreferences.getString("Customer_Email", ""); 
     Customer_email.setText(Constants.Customer_Email); 

     //Asigning FRagment names of sidebar 
     listNavItems = new ArrayList<NavItem>(); 
     listNavItems.add(new NavItem("Home", null, R.drawable.pras)); 
     for(int i=0;i<Constants.Category_name.size();i++){ 
      listNavItems.add(new NavItem(Constants.Category_name.get(i),null,R.drawable.teju)); 
     } 



     NavListAdapter navListAdapter = new NavListAdapter(getApplicationContext(), R.layout.item_nav_list, listNavItems); 

     lvNav.setAdapter(navListAdapter); 

     listFragment = new ArrayList<Fragment>(); 
     listFragment.add(new MyHome()); 
     for(int i=0;i<Constants.Category_name.size();i++){ 
      listFragment.add(new ProductsListFragment()); 
     } 
     listFragment.add(new MyHome()); 
     listFragment.add(new ActivityCart()); 
     listFragment.add(new LoginFragment()); 
     listFragment.add(new MyAbout()); 



     //Asigning FRagment names of sidebar 

     //Saving fragment data as constants for my home categories 
     Constants.listNavItems=listNavItems; 
     Constants.listFragment=listFragment; 
     //Saving fragment data as constants for my home categories 

     //Load first fragment as default: 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     fragmentManager.beginTransaction().replace(R.id.main_content, listFragment.get(0)).commit(); 

     setTitle(listNavItems.get(0).getTitle()); 
     lvNav.setItemChecked(0, true); 
     drawerLayout.closeDrawer(drawerPane); 



     // create listener for drawer layout 
     actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open , R.string.drawer_close) 
     { 
      @Override 
      public void onDrawerOpened(View drawerView) 
      { 
       invalidateOptionsMenu(); 
       super.onDrawerOpened(drawerView); 
      } 
      @Override 
      public void onDrawerClosed(View drawerView) 
      { 
       invalidateOptionsMenu(); 
       super.onDrawerClosed(drawerView); 
      } 
     }; 

     drawerLayout.setDrawerListener(actionBarDrawerToggle); 

    } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     final Menu mMenu = menu; 
     MenuInflater mif = getMenuInflater(); 
     mif.inflate(R.menu.actionbar_icon_menu, menu); 

     // Cart Icon in Action Bar 
     final View menu_hotlist = menu.findItem(R.id.cart_icon).getActionView(); 
     ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_Cart_hot); 
     updateHotCount(hot_number); 

     menu_hotlist.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Constants.lastDetails = false; 
       FragmentManager fragmentManager = getSupportFragmentManager(); 
       ActivityCart cart = new ActivityCart(); 
       fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit(); 
       setTitle("Cart"); 
       drawerLayout.closeDrawer(drawerPane); 
      } 
     }); 




     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item){ 
     if(actionBarDrawerToggle.onOptionsItemSelected(item)) 
      return true; 
     // Take appropriate action for each action item click 
     switch (item.getItemId()) { 

      case R.id.cart_icon: 
       // search action 
       FragmentManager fragmentManager = getSupportFragmentManager(); 
       ActivityCart cart = new ActivityCart(); 
       fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit(); 
       setTitle("Cart"); 
       drawerLayout.closeDrawer(drawerPane); 
       return true; 
       case R.id.action_search: 

       return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 


    @Override 
    protected void onPostCreate(Bundle savedInstanceState) { 

     super.onPostCreate(savedInstanceState); 
     actionBarDrawerToggle.syncState(); 
    } 

    @Override 
    public void onBackPressed() { 
     if (getFragmentManager().getBackStackEntryCount() >0) { 
      getFragmentManager().popBackStack(); 
     } else { 
      super.onBackPressed(); 
     } 
    } 




    @Override 
    public boolean onNavigationItemSelected(int itemPosition, long itemId) { 
     if (mNaviFirstHit) { 
      mNaviFirstHit = false; 
      return true; 
     } 
     else { 
      if(itemPosition == 0) 
       Constants.isCallParent = true; 
      else 
       Constants.isCallParent = false; 

      Constants.SubCatposition = itemPosition; 
      ProductsListFragment productsListFragment = new ProductsListFragment(); 
      FragmentManager fragmentManager = getSupportFragmentManager(); 
      fragmentManager.beginTransaction().replace(R.id.main_content, productsListFragment).commit(); 
      //lvNav.setItemChecked(position, true); 
      drawerLayout.closeDrawer(drawerPane); 
      //Toast.makeText(this, "Clicked at: " + itemPosition, Toast.LENGTH_LONG).show(); 
      //mNaviFirstHit = true; 
      return true; 
     } 
    } 

    public void setLoginDetails(){ 
     Customer_email.setText(Constants.Customer_Email); 
     Customer_name.setText("Welcome, " + Constants.Customer_FirstName); 
     Customer_name.setText(Constants.Customer_LastName); 
    } 
} 

ProductListFragment.java

package com.prashant; 

import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.support.v4.app.Fragment; 
import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.FragmentManager; 
import android.support.v7.app.AppCompatActivity; 
import android.view.LayoutInflater; 

import android.view.View; 
import android.view.ViewGroup; 

import android.widget.Button; 
import android.widget.GridView; 

import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 
import org.xmlpull.v1.XmlPullParserException; 

import java.io.IOException; 
import java.util.ArrayList; 

/** 
* Created by prashant. 
*/ 
public class ProductsListFragment extends Fragment { 

    ProgressDialog pdialog; 
    View v; 
    Button sort,filter; 
    //ListView list; 
    GridView list; 

    LazyImageLoadAdapter adapter; 
    private static ProductsListFragment sProductsListFragment; 

    // Title navigation Spinner data 
    private ArrayList<SpinnerNavItem> navSpinner; 

    // Navigation adapter 
    private TitleNavigationAdapter titleNavigationAdapter; 

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

     //((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null); 
     //((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true); 
     // Action Bar 
     ((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false); 
     ((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_LIST); 

    } 

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

     v = inflater.inflate(R.layout.productlistfragment, container, false); 
     sProductsListFragment = this; 
     list=(GridView)v.findViewById(R.id.list); 
     sort = (Button) v.findViewById(R.id.btn_sort); 
     sort.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       startActivity(new Intent(getActivity(),Pop.class)); 

      } 
     }); 

     //clearData(); 
     return v; 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null); 
     ((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true); 
     } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     ((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true); 
    } 

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

     Constants.cartEntry=0; 

     //check Product Description fragment is called or not 
     if (!Constants.lastDetails) { 
      clearData(); 
      new getDataTask().execute(); 
     } 
     else{ 
      String[] images=new String[Constants.Product_image.size()]; 
      images=Constants.Product_image.toArray(images); 
      adapter = new LazyImageLoadAdapter(getActivity(), images); 
      //Set adapter to listview 
      list.setAdapter(adapter); 
      Constants.lastDetails = false; 
     } 


    } 
    // clear arraylist variables before used 
    void clearData(){ 
     Constants.Product_ID.clear(); 
     Constants.Product_name.clear(); 
     Constants.Product_price.clear(); 
     Constants.Product_image.clear(); 
     Constants.Product_qty.clear(); 
     Constants.Product_specialPrice.clear(); 
     Constants.Product_desc.clear(); 
    } 


    @Override 
    public void onDestroy() 
    { 
     // Remove adapter refference from list 
     //list.setAdapter(null); 
     //Refresh cache directory downloaded images 
     //adapter.imageLoader.clearCache(); 
     //adapter.notifyDataSetChanged(); 
     super.onDestroy(); 
    } 

    public View.OnClickListener listener=new View.OnClickListener(){ 
     @Override 
     public void onClick(View arg0) { 

      //Refresh cache directory downloaded images 
      adapter.imageLoader.clearCache(); 
      adapter.notifyDataSetChanged(); 

     } 
    }; 


    public void onItemClick(int mPosition) 
    { 


     /* 
     Intent intent = new Intent(getActivity(), ProductDescription.class); 
     intent.putExtra("descposition", mPosition); 
     startActivity(intent);*/ 

     Constants.product_position = mPosition; 
     ProductDescription productDescription=new ProductDescription(); 
     getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, productDescription, null).addToBackStack("productDescription").commit(); 
     //((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(Constants.Product_name.get(mPosition)); 
     getActivity().setTitle("Product Details"); 
    } 

    // Image urls used in LazyImageLoadAdapter.java file 

    public class getDataTask extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      if (pdialog==null){ 
       pdialog=new ProgressDialog(getActivity()); 
       pdialog.setMessage("Loading..."); 
       pdialog.setCanceledOnTouchOutside(getRetainInstance()); 
       pdialog.setCancelable(false); 
       pdialog.show(); 
      } 
     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // TODO Auto-generated method stub 
      // parse json data from server in background 
      parseJSONData(); 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 

      // Create custom adapter for listview 
      String[] images=new String[Constants.Product_image.size()]; 
      images=Constants.Product_image.toArray(images); 
      adapter = new LazyImageLoadAdapter(getActivity(), images); 

      //Set adapter to listview 
      list.setAdapter(adapter); 

      if (!Constants.isSubCategory) { 
       Constants.isSubCategory = true; 
       // Spinner title navigation data 
       navSpinner = new ArrayList<SpinnerNavItem>(); 
       navSpinner.add(new SpinnerNavItem(Constants.Category_name.get(Constants.position - 1), R.drawable.icon)); 
       for (int i = 0; i < Constants.SubCategory_ID.size(); i++) { 
        navSpinner.add(new SpinnerNavItem(Constants.SubCategory_name.get(i), R.drawable.icon)); 
       } 

       // title drop down adapter 
       titleNavigationAdapter = new TitleNavigationAdapter(getActivity(), navSpinner); 
       // assigning the spinner navigation 
       ((MainActivity) getActivity()).getSupportActionBar().setListNavigationCallbacks(titleNavigationAdapter, ((MainActivity) getActivity())); 
      } 

      if (pdialog.isShowing()){ 
       pdialog.dismiss(); 
       pdialog=null; 
      } 

      if (Constants.Product_ID.isEmpty()){ 
       // Toast.makeText(getActivity(), "No products found!!Check your internet connection!!", Toast.LENGTH_LONG).show(); 
       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
       builder.setTitle("No Product Found!!").setMessage("Slow Internet/Check Your Internet Settings").create().show(); 
      } 

      /*for (int i = 0; i < Constants.Product_ID.size(); i++) { 
       Toast.makeText(getActivity(), "__" + Constants.Product_ID.get(i) + "__" + i, Toast.LENGTH_SHORT).show(); 
      }*/ 
      // if internet connection and data available show data on list 
      // otherwise, show alert text 

     } 
    } 

    // method to parse json data from server 
    public void parseJSONData(){ 

     SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryAssignedProducts"); 
      String Catid; 
      // add paramaters and values 
      request.addProperty("sessionId", Constants.sessionId); 
      if ((!Constants.isSubCategory) || Constants.isCallParent) { 
       Constants.isCallParent = false; 
       request.addProperty("categoryId", String.valueOf(Constants.Category_ID.get(Constants.position - 1))); 
       Catid=String.valueOf(Constants.Category_ID.get(Constants.position - 1)); 
      } 
      else { 
       request.addProperty("categoryId", String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1))); 
       Catid=String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1)); 
      } 

     api_calls call=new api_calls(); 
     call.getCategoryProducts(Catid); 


      if (!Constants.isSubCategory) { 
       Constants.SubCategory_ID.clear(); 
       Constants.SubCategory_name.clear(); 
       parseJSONDataSubCategory(); 
      } 


    } 

    // method to parse json data from server 
    public void parseJSONDataSubCategory(){ 

     try { 


      SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryTree"); 

      // add paramaters and values 
      request.addProperty("sessionId", Constants.sessionId); 
      request.addProperty("parentId", Constants.Category_ID.get(Constants.position-1)); 
      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.dotNet = true; 
      envelope.setOutputSoapObject(request); 

      //Web method call 
      HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL); 
      androidHttpTransport.debug = true; 
      androidHttpTransport.call("", envelope); 
      //get the response 
      SoapObject result2 = (SoapObject) envelope.getResponse(); 
      SoapObject pii2 = (SoapObject) result2.getProperty(5); 
      for (int i = 0; i < pii2.getPropertyCount(); i++) { 
       //JSONObject object = data.getJSONObject(i); 
       SoapObject pii = (SoapObject)pii2.getProperty(i); 
       //JSONObject category = object.getJSONObject("Category"); 
       Constants.SubCategory_ID.add(Long.parseLong(pii.getProperty(0).toString())); 
       Constants.SubCategory_name.add(pii.getProperty(2).toString()); 
      } 


     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (XmlPullParserException e) { 
      e.printStackTrace(); 
     } 
    } 

    // Making Sub Drawer for Sub Category 
    public static ProductsListFragment getInstance() { 
     return sProductsListFragment; 
    } 
    public void onBackPressed() 
    { 
     FragmentManager fm = getActivity().getSupportFragmentManager(); 
     fm.popBackStack(); 
    } 

} 

logcat的

02-11 12:39:57.838 12954-14579/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5 
                Process: com.softonetech.www.takenick, PID: 12954 
                java.lang.RuntimeException: An error occurred while executing doInBackground() 
                 at android.os.AsyncTask$3.done(AsyncTask.java:309) 
                 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) 
                 at java.util.concurrent.FutureTask.setException(FutureTask.java:223) 
                 at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                 at java.lang.Thread.run(Thread.java:818) 
                Caused by: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1 
                 at java.util.ArrayList.get(ArrayList.java:310) 
                 at com.prashant.ProductsListFragment.parseJSONData(ProductsListFragment.java:250) 
                 at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:185) 
                 at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:167) 
                 at android.os.AsyncTask$2.call(AsyncTask.java:295) 
                 at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)  
                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)  
                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)  
                 at java.lang.Thread.run(Thread.java:818)  
+1

請分享你的日誌 –

+0

什麼錯誤是你gett ING?日誌請 –

+0

我分享我的日誌,請檢查 –

回答

1

嘗試取消您的異步任務Ë在xecution onBackPressed()

聲明:本

Public getDataTask asyncFetchData; 

asyncFetchData = new getDataTask(); 
asyncFetchData.execute(); 
在片段

現在:

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

     super.onViewCreated(view, savedInstanceState); 
     getView().setFocusableInTouchMode(true); 
     getView().requestFocus(); 
     getView().setOnKeyListener(new View.OnKeyListener() { 
      @Override 
      public boolean onKey(View v, int keyCode, KeyEvent event) { 
       if (event.getAction() == KeyEvent.ACTION_DOWN) { 
        if (keyCode == KeyEvent.KEYCODE_BACK) { 
         if (asyncFetchData!= null) 
          asyncFetchData.cancel(true); 
         Toast.makeText(getActivity(), "Back pressed...", Toast.LENGTH_SHORT).show(); 
         return true; 
        } 
       } 
       return false; 
      } 
     }); 
    } 

另外在doInBackground通知AsyncTask取消執行

@Override 
protected Void doInBackground(Void... arg0) { 
    // TODO Auto-generated method stub 
    // parse json data from server in background 
    parseJSONData(); 
    if (isCancelled()) break; 
    return null; 
} 
+0

打破外部交換機或循環此消息顯示中斷;並且從不使用onKeyDown。 –

+0

@PrashantDas檢查修改後的onKeyEvent代碼 – rafsanahmad007

相關問題