ArrayList get方法导致应用程序崩溃

时间:2016-06-23 13:40:55

标签: android arraylist menu

我正在从JSON中提取包含其名称和ID的菜单。我写过Fragment5,用于调用JSON的URL。在那个网址中我想调用菜单的id。 这是我的代码。如果我正在评论两行

,代码运行正常
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);


MainActivity.java

package com.latrodealz.wowwdealz;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.latrodealz.wowwdealz.adapter.SlidingMenuAdapter;
import com.latrodealz.wowwdealz.fragment.Fragment1;
import com.latrodealz.wowwdealz.fragment.Fragment2;
import com.latrodealz.wowwdealz.fragment.Fragment3;
import com.latrodealz.wowwdealz.fragment.Fragment4;
import com.latrodealz.wowwdealz.fragment.Fragment5;
import com.latrodealz.wowwdealz.model.ItemSlideMenu;

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

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

/**
 * Created by NgocTri on 10/18/2015.
 */
public class MainActivity extends AppCompatActivity {

    private List<ItemSlideMenu> listSliding;
    private SlidingMenuAdapter adapter;
    private ListView listViewSliding;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;


    //Web api url
    public static final String MENU_URL = "http://69.89.31.191/~webtech6/android_wow/menu_dtls.php";
    //Tag values to read from json
    public static final String MENU_ID = "menu_id";
    public static final String MENU_NM = "menu_nm";
    //ArrayList for Storing menu ids and names
    private ArrayList<String> menu_ids;
    private ArrayList<String> menu_nms;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


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

        menu_ids = new ArrayList<>();
        menu_nms = new ArrayList<>();

        //Calling the getMenuData method
        getMenuData();

        //Init component
        listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        listSliding = new ArrayList<>();
        //Add item for sliding list
        listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "Home"));
        adapter = new SlidingMenuAdapter(this, listSliding);
        listViewSliding.setAdapter(adapter);

        //Display icon to open/ close sliding list
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //Set title
        setTitle(listSliding.get(0).getTitle());


        //item selected
        listViewSliding.setItemChecked(0, true);
        //Close menu
        drawerLayout.closeDrawer(listViewSliding);

        //Display fragment 1 when start
        replaceFragment(0);
        //Handle on item click

        listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Set title
                setTitle(listSliding.get(position).getTitle());

                //item selected
                listViewSliding.setItemChecked(position, true);
                //Replace fragment
                replaceFragment(position);
                //Close menu
                drawerLayout.closeDrawer(listViewSliding);
            }
        });

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                invalidateOptionsMenu();
            }
        };

        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }


    private void getMenuData() {
        //Showing a progress dialog while our app fetches the data from url
        final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);

        //Creating a json array request to get the json from our api
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(MENU_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing the progressdialog on response
                        loading.dismiss();

                        //Displaying our grid
                        showMenu(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );

        //Creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //Adding our request to the queue
        requestQueue.add(jsonArrayRequest);
    }


    private void showMenu(JSONArray jsonArray) {
        //Looping through all the elements of json array
        for (int i = 0; i < jsonArray.length(); i++) {
            //Creating a json object of the current index
            JSONObject obj = null;
            try {
                //getting json object from current index
                obj = jsonArray.getJSONObject(i);
                //getting menuid and menuname from json object
                menu_ids.add(obj.getString(MENU_ID));
                menu_nms.add(obj.getString(MENU_NM));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        //Add item for sliding list


        for (int i = 0; i < menu_ids.size(); i++) {
            listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, menu_nms.get(i)));
        }
        adapter = new SlidingMenuAdapter(this, listSliding);
        listViewSliding.setAdapter(adapter);


        //Add item for sliding list
        listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY CART"));
        listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ACCOUNT"));
        listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ORDERS"));
        adapter = new SlidingMenuAdapter(this, listSliding);
        listViewSliding.setAdapter(adapter);

        //Display Array List
        // Toast.makeText(getBaseContext(), menu_ids + "", Toast.LENGTH_LONG).show();
        // Toast.makeText(getBaseContext(), menu_nms + "", Toast.LENGTH_LONG).show();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
            case R.id.action_search:
                // User chose the "Settings" item, show the app settings UI...
                Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
                startActivityForResult(intent, 0);
                //Toast.makeText(this, "You have selected Search Search Menu", Toast.LENGTH_SHORT).show();

                return true;

            case R.id.action_kart:
                // User chose the "Favorite" action, mark the current item
                // as a favorite...
                Toast.makeText(this, "You have selected Search KART Menu", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.action_notifications:
                // User chose the "Favorite" action, mark the current item
                // as a favorite...
                Toast.makeText(this, "You have selected Search Notifications Menu", Toast.LENGTH_SHORT).show();
                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

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

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    /**
     * Called when the user clicks the Search Menu
     * public void callSearchActivity(View view) {
     * Intent intent = new Intent(this, SearchActivity.class);
     * startActivity(intent);
     * }
     */
    //Create method replace fragment
    private void replaceFragment(int pos) {
        Fragment fragment = null;

        int menu_size = menu_ids.size();
        String scat = menu_nms.get(0);
        int cat = Integer.parseInt(scat);
        if (pos == 0) {
            fragment = new Fragment1();
        } else if (pos > 0 && pos <= menu_size) {

            SharedPreferences sharePref = getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
            sharePref.edit().remove("menu_id").commit();

            SharedPreferences.Editor editor = sharePref.edit();
            editor.putInt("menu_id", pos);
            editor.apply();
            fragment = new Fragment5();
        } else if (pos == (menu_size + 1)) {
            fragment = new Fragment2();
        } else if (pos == (menu_size + 2)) {
            fragment = new Fragment3();
        } else if (pos == (menu_size + 3)) {
            fragment = new Fragment4();
        } else {
            fragment = new Fragment1();
        }


        if (null != fragment) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.main_content, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}

Fragment5.java

package com.latrodealz.wowwdealz.fragment;

import android.app.Fragment;



import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;



import com.latrodealz.wowwdealz.R;

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

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


public class Fragment5 extends Fragment {

    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";

    public Fragment5() {

    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment5, container, false);

        //TextView menu_id = (TextView)rootView.findViewById(R.id.textid);

        //SharedPreferences sharePref =  this.getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
        //int menuId = sharePref.getInt("menu_id", 0);

       // menu_id.setText(String.valueOf(menuId));

        ImageView purple=(ImageView)rootView.findViewById(R.id.gridicon);
        purple.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.main_content, new Fragment4())
                        .commit();
            }
        });

        new DownloadJSON().execute();


        return rootView;
    }


    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(getActivity());
            // Set progressdialog title
            mProgressDialog.setTitle("Fetching data...");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            SharedPreferences sharePref =  getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
            int menuId = sharePref.getInt("menu_id", 0);

            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions
                    .getJSONfromURL("http://69.89.31.191/~webtech6/android_wow/load.php?catId="+menuId);

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("worldpopulation");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("rank", jsonobject.getString("rank"));
                    map.put("country", jsonobject.getString("country"));
                    map.put("population", jsonobject.getString("population"));
                    map.put("flag", jsonobject.getString("flag"));
                    // Set the JSON Objects into the array

                    //Toast.makeText(getActivity().getBaseContext(), map + "", Toast.LENGTH_LONG).show();
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) getActivity().findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(getActivity(), arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

也许你在JSON解析期间遇到异常。你可以包围Integer.parseInt(scat);如果Json没有这样的字段,则使用try-catch捕获ParsingException。 但更简洁的解决方案是将GSON与Retrofit一起使用,这样您就可以自动解析对jsonschema2pojo.com创建的java对象的响应