Parent activity loses data when onBackPressed() is called

风流意气都作罢 提交于 2019-12-11 06:36:32

问题


I have a listview in subsection activity when I click on it, it opens up tabbed activity. Now when I press up navigation button on top left corner and go back to parent activity, the listview becomes empty. But when I press back button on the keypad the parent activity does not lose its data. The listview is populated using the database.

Please help me!

SubSectionActivity.java (Parent Activity)

package com.suvariyaraj.algorithms;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListViewCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.suvariyaraj.algorithms.Database.DBPARAM;
import com.suvariyaraj.algorithms.Database.ExternalDbOpenHelper;
import java.util.ArrayList;

public class SubSectionActivity extends AppCompatActivity {

ListView listView;
String[] array;
private SQLiteDatabase database;
DBPARAM dbparam = new DBPARAM ();
ArrayList<String> titles;
String section;
public static final String MyPREFERENCES = "MyPrefsAlgorithmApp" ;
SharedPreferences sharedPreferences;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Intent i = getIntent();
    section = i.getStringExtra("Section");
    Toast.makeText(getApplicationContext(), section, Toast.LENGTH_SHORT).show();
    sharedPreferences = getSharedPreferences ("myprefAlgoApp", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit ();
    editor.putString ("Section",section);
    editor.commit ();


    ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper (this, dbparam.DB_NAME);
    database = dbOpenHelper.openDataBase();

    getDistinctSubSections ();
    ArrayAdapter adapter = new ArrayAdapter(this, R.layout.single_list_view_item, titles);
    listView = (ListView) findViewById(R.id.subsection_listview);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getApplicationContext(), AlgorithmActivity.class);
            i.putExtra("Subsection", titles.get (position));
            i.putExtra ("Section", section);
            startActivity (i);
        }


    });
}

private void getDistinctSubSections() {
    titles = new ArrayList<String> ();
    Cursor cursor = database.query(true, dbparam.TABLE_NAME, new String[] {dbparam.COLOUMN_SUBSECTION}, dbparam.COLOUMN_SECTION+" = '"+section+"'", null, null, null, null, null);
    if(cursor!=null) {
        cursor.moveToFirst();
        if (!cursor.isAfterLast()) {
            do {
                String name = cursor.getString(cursor.getColumnIndex(dbparam.COLOUMN_SUBSECTION));
                titles.add(name);
            } while (cursor.moveToNext());
        }
    }
    cursor.close();
}
}

AlgorithmActivity.java (child activity)

package com.suvariyaraj.algorithms;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.suvariyaraj.algorithms.Database.DBPARAM;
import com.suvariyaraj.algorithms.Database.ExternalDbOpenHelper;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class AlgorithmActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

private static SQLiteDatabase database;
static DBPARAM dbparam = new DBPARAM ();
ArrayList<String> titles;
static ArrayList<String> array;
static String section;
static String subsection;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;
String title;

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


    Intent i = getIntent();
    subsection = i.getStringExtra("Subsection");
    section = i.getStringExtra("Section");

    ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper (this, dbparam.DB_NAME);
    database = dbOpenHelper.openDataBase();

    //Toast.makeText(getApplicationContext(), title, Toast.LENGTH_SHORT).show();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    if (mViewPager != null) {
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    if (tabLayout != null) {
        tabLayout.setupWithViewPager(mViewPager);
    }

    FloatingActionButton fab_copy = (FloatingActionButton) findViewById (R.id.fab_copy);
    FloatingActionButton fab_share = (FloatingActionButton) findViewById (R.id.fab_share);
    FloatingActionButton fab_doubt = (FloatingActionButton) findViewById (R.id.fab_doubt);
    final FloatingActionsMenu fab_menu = (FloatingActionsMenu) findViewById (R.id.fab_menu);

    if (fab_copy != null) {
        fab_copy.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                String s = "C Code : \n"+array.get(1).replace ("~~", "")+ "\n\nJava Code : \n"+array.get(2).replace ("~~", "");
                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("Shared Content", s);
                clipboard.setPrimaryClip(clip);
                Toast.makeText (getApplicationContext (),"Content Copied",Toast.LENGTH_SHORT).show ();
                if (fab_menu != null) {
                    fab_menu.collapse ();
                }
            }
        });
    }

    if (fab_share != null) {
        fab_share.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                String s = "Algorithm Name : "+subsection+"\n\nC Code : \n"+array.get(1).replace ("~~", "")+ "\n\nJava Code : \n"+array.get(2).replace ("~~", "");
                if (fab_menu != null) {
                    fab_menu.collapse ();
                }
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, s);
                sendIntent.setType("text/plain");
                startActivity(Intent.createChooser(sendIntent, "Share using..."));
            }
        });
    }

    if (fab_doubt != null) {
        fab_doubt.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                Intent i = new Intent (getApplicationContext (), DoubtActivity.class);
                i.putExtra ("Title", title);
                if (fab_menu != null) {
                    fab_menu.collapse ();
                }
                startActivity (i);
            }
        });
    }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_algorithm, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    //if (item.getItemId() == android.R.id.home) {
    //    onBackPressed ();
    //}

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

        View rootView = inflater.inflate(R.layout.fragment_algorithm, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        array = new ArrayList<String> ();
        array.add ("Hi from description");
        array.add ("Hi from C");
        array.add ("Hi from JAVA");
        getInformation ();

        NestedScrollView scrollView = (NestedScrollView) rootView.findViewById(R.id.abcscrollView);

        LinearLayout linearLayout = new LinearLayout (rootView.getContext ());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams (params);
        params.bottomMargin=10;
        linearLayout.setOrientation (LinearLayout.VERTICAL);

        if(getArguments().getInt(ARG_SECTION_NUMBER)-1==0) {
            String temparray[] = array.get(0).split("~~");
            //array.set (0, "");
            for (int i = 0; i < temparray.length; i++) {
                if (temparray[i].startsWith("Image:")) {
                    ImageView iv = new ImageView(rootView.getContext());
                    iv.setId(i+1);
                    int itd = this.getResources().getIdentifier(temparray[i].substring(6), "drawable", getActivity().getPackageName());
                    iv.setImageResource(itd);
                    linearLayout.addView (iv);

                } else {
                    TextView tv = new TextView(rootView.getContext());
                    tv.setText(temparray[i]);
                    tv.setTextSize (24);
                    tv.setId(i+1);
                    linearLayout.addView (tv);
                }
            }
        }

        if(getArguments().getInt(ARG_SECTION_NUMBER)-1==1) {
            String temparray[] = array.get(1).toString ().split("~~");
            for (int i = 0; i < temparray.length; i++) {
                if (temparray[i].startsWith("Output:")) {
                    TextView tv = new TextView(rootView.getContext());
                    tv.setText(temparray[i]);
                    //tv.setTextSize (24);
                    tv.setId(i+100);
                    tv.setBackgroundColor (Color.GRAY);

                    linearLayout.addView (tv,params);
                } else if (temparray[i].startsWith("Input:")) {
                    TextView tv = new TextView (rootView.getContext ());
                    tv.setText (temparray[i]);
                    //tv.setTextSize (24);
                    tv.setId (i+100);
                    tv.setBackgroundColor (Color.GRAY);
                    linearLayout.addView (tv, params);
                }else {
                    if (temparray[i].trim ().equals ("")){
                        continue;
                    }
                    TextView tv = new TextView(rootView.getContext());
                    tv.setText(temparray[i].trim ());
                    //tv.setTextSize (24);
                    tv.setId(i+100);
                    linearLayout.addView (tv);
                }
            }
        }

        if(getArguments().getInt(ARG_SECTION_NUMBER)-1==2) {
            String temparray[] = array.get(2).toString ().split("~~");
            //array.set (2, "");
            for (int i = 0; i < temparray.length; i++) {
                if (temparray[i].startsWith("Output:")) {
                    TextView tv = new TextView(rootView.getContext());
                    tv.setText(temparray[i]);
                    //tv.setTextSize (24);
                    tv.setId(i+100);
                    tv.setBackgroundColor (Color.GRAY);

                    linearLayout.addView (tv,params);
                } else if (temparray[i].startsWith("Input:")) {
                    TextView tv = new TextView (rootView.getContext ());
                    tv.setText (temparray[i]);
                    //tv.setTextSize (24);
                    tv.setId (i+100);
                    tv.setBackgroundColor (Color.GRAY);
                    linearLayout.addView (tv, params);
                }else {
                    if (temparray[i].trim ().equals ("")){
                        continue;
                    }
                    TextView tv = new TextView(rootView.getContext());
                    tv.setText(temparray[i].trim ());
                    //tv.setTextSize (24);
                    tv.setId(i+100);
                    linearLayout.addView (tv);
                }
            }
        }

        NestedScrollView.LayoutParams params2 = new NestedScrollView.LayoutParams (NestedScrollView.LayoutParams.MATCH_PARENT, NestedScrollView.LayoutParams.MATCH_PARENT);
        scrollView.addView (linearLayout,params2);

        //textView.setText (array.get(getArguments ().getInt (ARG_SECTION_NUMBER) - 1));
        return rootView;
    }

    private void getInformation() {
        Cursor cursor = database.query(true, dbparam.TABLE_NAME, new String[] {dbparam.COLOUMN_DESCRIPTION, dbparam.COLOUMN_CODEC, dbparam.COLOUMN_CODEJAVA}, dbparam.COLOUMN_SECTION+"='"+section+"' AND "+dbparam.COLOUMN_SUBSECTION+"='"+subsection+"'", null, null, null, null, null);
        if(cursor!=null) {
            cursor.moveToFirst();
            if (!cursor.isAfterLast()) {
                do {
                    String discription = cursor.getString(cursor.getColumnIndex(dbparam.COLOUMN_DESCRIPTION));
                    array.set(0, discription);
                    String codeC = cursor.getString(cursor.getColumnIndex(dbparam.COLOUMN_CODEC));
                    array.set(1, codeC);
                    String codeJAVA = cursor.getString(cursor.getColumnIndex(dbparam.COLOUMN_CODEJAVA));
                    array.set(2, codeJAVA);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Description";
            case 1:
                return "C";
            case 2:
                return "Java";
        }
        return null;
    }


}
}

回答1:


This may solve your problem

Put this in your AlgorithmActivity.java and remove your code.

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}


来源:https://stackoverflow.com/questions/37642676/parent-activity-loses-data-when-onbackpressed-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!