Android应用程序中的大型内存消耗和偶尔冻结

时间:2015-07-01 15:58:17

标签: android memory

所以我的应用程序占用80MB或RAM,偶尔在活动之间切换时,屏幕变黑,显示正确的内容需要一分钟。它所做的就是在每个活动中加载列表视图。我确保在首次启动活动时在加载屏幕中执行所有AsyncTasks,然后我使用共享首选项来存储数据并在所有活动中使用它,这样我就不必每次都执行新的Asynctask活动开始了。这就是为什么我很困惑为什么会发生这种情况。我唯一能想到的是,当我调用finish()时,活动不会被杀死,因为当我多次在活动之间切换时通常会发生这种情况。

示例活动:

public class AllGameslistActivity extends Activity {
    private Bet newBet = new Bet();
    private double stake = 0.00;
    private String name = "";
    private double newwinnings;
    private ArrayList<TipDisplayer> alltips = new ArrayList<>();
    private String newwinningstoString;
    private RecyclerView recyclerview;
    private String selection;
    private ArrayList<Integer> ids = new ArrayList<>();
    private ArrayList<BetParameters> listwriter = new ArrayList<>();

    // Progress Dialog
    private static String url_all_games = "****";

    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> gamesList;

    // url to get all products list

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_GAMELIST = "gamelist";
    private static final String TAG_ID = "ID";
    private static final String TAG_LEAGUE = "League";
    private static final String TAG_TEAMS = "Teams";
    private static final String TAG_BET = "Bet";
    private static final String TAG_ODDS = "Odds";
    private static final String TAG_DATETIMER = "DateTimer";
    private static final String TAG_COMMENTS = "Comments";
    private static final String TAG_TYPE = "Type";


    // products JSONArray
    JSONArray allgames = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_bets);
        overridePendingTransition(R.anim.push_up_out, R.anim.push_up_in);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);



        menu menu =  (menu) getFragmentManager().findFragmentById(R.id.fragment);
        menu.betnowclick();
        SessionManager session;
        session = new SessionManager(getApplicationContext());
        HashMap<String, String> user = session.getUserDetails();
        name = user.get(SessionManager.USERNAME);
        menu.updateinfo(getName());
        alltips = session.getalltips();
        PopulateList();

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

        // Loading products in Background Thread
        //new LoadAllGames().execute();

        // Get listview



    }

    private void PopulateList() {
        ArrayAdapter<TipDisplayer> adapter = new MyListAdapter(alltips);
        final ListView list = (ListView) findViewById(R.id.mylist);
        list.setAdapter(adapter);

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadAllGames extends AsyncTask<String, String, String> {


        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        /**
         * getting All products from url
         */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);

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

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Games
                    allgames = json.getJSONArray(TAG_GAMELIST);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String league = c.getString(TAG_LEAGUE);
                        String odds = c.getString(TAG_ODDS);
                        String comments = c.getString(TAG_COMMENTS);
                        String type = c.getString(TAG_TYPE);
                        String bet = c.getString(TAG_BET);
                        String datetimer = c.getString(TAG_DATETIMER);
                        String Teams = c.getString(TAG_TEAMS);
                        Double Odds = Double.parseDouble(odds);



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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_LEAGUE,league);
                        map.put(TAG_ODDS,odds);
                        map.put(TAG_COMMENTS,comments);
                        map.put(TAG_TYPE,type);
                        map.put(TAG_BET,bet);
                        map.put(TAG_DATETIMER,datetimer);
                        map.put(TAG_TEAMS, Teams);
                        Log.d("id", id);
                        Log.d("league", league);
                        Log.d("odds", odds);
                        Log.d("comments", comments);
                        Log.d("Type", type);
                        Log.d("bet", bet);
                        Log.d("datetimer", datetimer);
                        Log.d("teams",Teams);

                        alltips.add(i, new TipDisplayer(id, league, Teams, bet, odds, datetimer, comments, type));

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

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

            return "";
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            // updating UI from Background Thread
        PopulateList();


        }


    }


    class ViewHolder {
        TextView leaguetxt;
        TextView datetxt;
        TextView teamstxt;
        TextView bettxt;
        TextView betid;
        TextView typetxt;
        TextView commentstxt;
        Button oddsbtn;
        LinearLayout item;

        ViewHolder(View v) {
            leaguetxt = (TextView) v.findViewById(R.id.leaguetxt);
            datetxt = (TextView) v.findViewById(R.id.datetxt);
            teamstxt = (TextView) v.findViewById(R.id.teamstxt);
            bettxt = (TextView) v.findViewById(R.id.bettxt);
            betid = (TextView) v.findViewById(R.id.gid);
            typetxt = (TextView) v.findViewById(R.id.difficultytxt);
            commentstxt = (TextView) v.findViewById(R.id.commenttxt);
            oddsbtn = (Button) v.findViewById(R.id.oddsbutton);
            item = (LinearLayout) v.findViewById(R.id.item);
        }
    }
    private class MyListAdapter extends ArrayAdapter<TipDisplayer> {
        public MyListAdapter() {
            super(AllGameslistActivity.this, R.layout.list_item, alltips);

        }
        public MyListAdapter(ArrayList<TipDisplayer> alltips) {
            super(AllGameslistActivity.this, R.layout.list_item, alltips);
            alltips = alltips;  // declare tomee in the Adapter, don't use static

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
             View itemView = convertView;
            TipDisplayer currentwriter = alltips.get(position);
            ViewHolder holder = null;
            if (itemView == null) {
                itemView = getLayoutInflater().inflate(R.layout.list_item, parent, false);
                holder = new ViewHolder(itemView);
                itemView.setTag(holder);
                Log.d("SETTING","new holder");

            }
            else {
                holder = (ViewHolder) itemView.getTag();
                Log.d("plzwork",ids.toString());
                if (!ids.contains(Integer.parseInt(holder.betid.getText().toString()))) {
                    Log.d("doesn't contain", "doesn't contain");
                    Log.d("betid",holder.betid.getText().toString());
                    Log.d("bettxt", holder.bettxt.getText().toString());
                }
                else {
                    Log.d("recycling contains", "contains");
                    Log.d("betid", holder.betid.getText().toString());
                    Log.d("bettxt", holder.bettxt.getText().toString());
                }
                Log.d("Recycling","recycling");

            }
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LinearLayout layout = (LinearLayout) v;
                    Button b = (Button) layout.findViewById(R.id.oddsbutton);
                    ListView listView = (ListView) layout.getParent();
                    final int position = listView.getPositionForView(listView);
                    String buttontext = b.getText().toString();
                    Button lastchance = (Button) layout.findViewById(R.id.oddsbutton);
                    TextView betidtextbox = (TextView) layout.findViewById(R.id.gid);
                    String betid = betidtextbox.getText().toString();
                    TipDisplayer currentwriter = alltips.get(position + 1);
                    Log.d("plzworkkkk", newBet.toString());
                    if (ids.contains(Integer.parseInt(betid))) {
                        b.setTextColor(Color.parseColor("#000000"));
                        b.setTextSize(18);
                        ids.remove(new Integer(Integer.parseInt(betid)));
                        Log.d("plzworkkkkkkk", newBet.toString());
                        currentwriter.toggleHighlighted();
                        //checkhighlight(layout);
                        Log.d("getodds", buttontext);
                        selection = "home";

                        TextView teamss = (TextView) layout.findViewById(R.id.teamstxt);
                        String teams = teamss.getText().toString();
                        Log.d("teams", teams);
                        TextView bet = (TextView) layout.findViewById(R.id.bettxt);
                        String bettxt = bet.getText().toString();
                        Log.d("btxttext", bettxt);
                        newBet.generateoddstesting(betid, buttontext, false, teams, selection, bettxt);
                        double newodds = newBet.calculateodds();
                        TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
                        TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                        myBetOdds.setText("@" + String.format("%.2f", newodds) + "/1");
                        EditText mEdit = (EditText) findViewById(R.id.editText2);
                        if (mEdit.getText().toString().length() == 0) {
                            stake = 0.00;
                            newwinnings = 0.00;
                            potentialWinnings.setText("0.00");

                        } else {
                            mEdit.addTextChangedListener(new TextWatcher() {

                                public void beforeTextChanged(CharSequence s, int start,
                                                              int count, int after) {
                                }

                                public void onTextChanged(CharSequence s, int start,
                                                          int before, int count) {
                                    if (s.length() != 0) {
                                        stake = Double.parseDouble(s.toString());
                                        double newodds = newBet.calculateodds();
                                        newwinnings = stake * newodds;
                                        TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
                                        TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                                        myBetOdds.setText("@" + String.format("%.2f", newodds) + "/1");
                                        potentialWinnings.setText(String.format("%.2f", (newwinnings)));
                                        newwinningstoString = potentialWinnings.getText().toString();

                                    } else {
                                        stake = 0.00;
                                        newwinnings = 0.00;
                                        double newodds = newBet.calculateodds();
                                        TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
                                        TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                                        myBetOdds.setText("@" + String.format("%.2f", newodds) + "/1");
                                        potentialWinnings.setText(String.format("%.2f", (newwinnings)));
                                        newwinningstoString = potentialWinnings.getText().toString();

                                    }
                                }

                                public void afterTextChanged(Editable s) {
                                }
                            });
                            //stake = Double.parseDouble(mEdit.getText().toString());
                            newwinnings = stake * newodds;
                            potentialWinnings.setText(String.format("%.2f", (newwinnings)));
                            newwinningstoString = potentialWinnings.getText().toString();


                        }
                    } else {

                        ids.add(Integer.parseInt(betid));
                        //checkhighlight(layout);

                        b.setTextColor(Color.parseColor("#EB102E"));
                        b.setTextSize(20);
                        currentwriter.toggleHighlighted();
                        selection = "home";
                        String getodds = lastchance.getText().toString();
                        Log.d("getoddsss", getodds);
                        EditText mEdit = (EditText) findViewById(R.id.editText2);
                        if (mEdit.getText().toString().length() == 0) {
                            stake = 0.00;
                            newwinnings = 0.00;
                            TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                            potentialWinnings.setText("0.00");
                        } else {
                            mEdit.addTextChangedListener(new TextWatcher() {

                                public void beforeTextChanged(CharSequence s, int start,
                                                              int count, int after) {
                                }

                                public void onTextChanged(CharSequence s, int start,
                                                          int before, int count) {
                                    if (s.length() != 0) {
                                        stake = Double.parseDouble(s.toString());
                                        double newodds = newBet.calculateodds();
                                        newwinnings = stake * newodds;
                                        TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
                                        TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                                        myBetOdds.setText("@" + String.format("%.2f", newodds) + "/1");
                                        potentialWinnings.setText(String.format("%.2f", (newwinnings)));
                                        newwinningstoString = potentialWinnings.getText().toString();
                                    } else {
                                        stake = 0.00;
                                        double newodds = newBet.calculateodds();
                                        newwinnings = stake * newodds;
                                        TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
                                        TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                                        myBetOdds.setText("@" + String.format("%.2f", newodds) + "/1");
                                        potentialWinnings.setText(String.format("%.2f", (newwinnings)));
                                        newwinningstoString = potentialWinnings.getText().toString();
                                    }
                                }

                                public void afterTextChanged(Editable s) {
                                }
                            });
                            stake = Double.parseDouble(mEdit.getText().toString());
                            TextView teamms = (TextView) layout.findViewById(R.id.teamstxt);
                            String teams = teamms.getText().toString();
                            Log.d("teams", teams);
                            TextView bet = (TextView) layout.findViewById(R.id.bettxt);
                            String bettxt = (String) bet.getText().toString();
                            Log.d("bettxt", bettxt);
                            newBet.generateoddstesting(betid, buttontext, true, teams, selection, bettxt);
                            double newodds = newBet.calculateodds();
                            newwinnings = stake * newodds;
                            TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
                            TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
                            myBetOdds.setText("@" + String.format("%.2f", newodds) + "/1");
                            potentialWinnings.setText(String.format("%.2f", (newwinnings)));
                            newwinningstoString = potentialWinnings.getText().toString();


                        }
                    }

                }
            });





            String leaguetext = currentwriter.getLeague();
            String datetext = currentwriter.getDatetimer();
            String teamstext = currentwriter.getTeams();
            String bettext = currentwriter.getBet();
            String typetext = currentwriter.getType();
            String idtext = currentwriter.getId();
            String commentsText = currentwriter.getComments();
            String oddstext = currentwriter.getOdds();
            holder.leaguetxt.setText(leaguetext);
            holder.datetxt.setText(datetext.substring(0,datetext.lastIndexOf(":")) + " GMT");
            holder.teamstxt.setText(teamstext);
            holder.bettxt.setText(bettext);
            holder.betid.setText(idtext);
            holder.commentstxt.setText(commentsText);
            holder.oddsbtn.setText(oddstext);
            holder.typetxt.setText(typetext);
            if (typetext.equals("Low Risk")) {
                holder.typetxt.setTextColor(Color.parseColor("#067103"));
            }
            else if (typetext.equals("Medium Risk")) {
                holder.typetxt.setTextColor(Color.parseColor("#D9D216"));
            }
            else if (typetext.equals("Longshot")) {
                holder.typetxt.setTextColor(Color.parseColor("#F75528"));
            }


            return itemView;


        }
        @Override

        public int getViewTypeCount() {

            return getCount();
        }

        @Override
        public int getItemViewType(int position) {

            return position;
        }

    }





    public void clicking(View v) {

}

public void NewBetMaker(View v) {
    menu menu =  (menu) getFragmentManager().findFragmentById(R.id.fragment);
    int value = (int) stake;
    if (value == 0) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Enter Stake");
        builder.setMessage("You did not enter any stake for your bet.");

        builder.setNeutralButton("Ok.", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();

            }
        });
        builder.show();
    }

    else {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Confirm Bet Placement");
        builder.setMessage("Are you sure you would like to place this bet?");

        builder.setNegativeButton("Nope.", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("YES, BET NOW!", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // Do nothing but close the dialog
                menu menu =  (menu) getFragmentManager().findFragmentById(R.id.fragment);
                int pass = (int) stake;
                Intent i = new Intent(AllGameslistActivity.this, MyBets.class);

                HashMap<Integer, Game> listofgames = new HashMap<Integer, Game>();
                HashMap<Integer,String> betdatabasesetter = new HashMap<Integer, String>();
                listofgames = newBet.getlistofgames();
                for (Integer x : listofgames.keySet()) {
                    TextView teams = (TextView) findViewById(R.id.textView2);
                    String getTeams = listofgames.get(x).getTeams();
                    teams.setText(getTeams);
                    TextView selectionodds = (TextView) findViewById(R.id.textView3);
                    String selectedoutcome = listofgames.get(x).getSelection();
                    Double selectedoutcomeodds = listofgames.get(x).getSelectedOdds();
                    String selectedteam = "";
                    if (selectedoutcome.equals("home")) {
                        selectedteam = listofgames.get(x).getBet();
                        betdatabasesetter.put(x,"1");
                    }
                    String selection = (selectedteam + " @" + selectedoutcomeodds);
                    BetParameters y = new BetParameters(getTeams, selection);
                    listwriter.add(y);
                    Log.d("teams", getTeams);
                    Log.d("selected odds", Double.toString(selectedoutcomeodds));
                    Log.d("selected team", selectedteam);
                    Log.d("selected outcome", selectedoutcome);
                    Log.d("selection", selection);


                }
                i.putExtra("hash",new DataWrapper(betdatabasesetter));
                i.putExtra("data", new DataWrapper(listwriter));
                i.putExtra("stake", stake);
                i.putExtra("winnings",newwinningstoString);
                ((AppController) getApplicationContext()).setGamesList(gamesList);

                startActivity(i);
                finish();

            }




        });



        AlertDialog alert = builder.create();
        alert.show();
    }



}
public String getName() {
    SessionManager session;
    session = new SessionManager(getApplicationContext());
    HashMap<String, String> user = session.getUserDetails();
    name = user.get(SessionManager.USERNAME);
    return name;
}

    public void checkhighlight(View v) {
        TextView betid = (TextView) v.findViewById(R.id.gid);
        String id = betid.getText().toString();
        Button button = (Button) v.findViewById(R.id.oddsbutton);
        if (ids.contains(Integer.parseInt(id))) {
                button.setTextColor(Color.parseColor("#EB102E"));
                button.setTextSize(20);
        }
        else {
            button.setTextColor(Color.parseColor("#000000"));
            button.setTextSize(18);
        }
    }

}

0 个答案:

没有答案