当我按下后退按钮时,我的活动重新开始

时间:2016-01-14 06:52:52

标签: android android-activity

我有两项活动ABA是父级,B是子级活动。我使用活动Volley Stringrequest中的A加载数据,并在Recyclerview中显示这些项目。当我点击单个项目时,它会将我带到B。但是当我使用A按钮返回活动Home/Back时,活动会重新启动并再次发送Stringrequest重新加载数据。

但是当我使用设备返回按钮返回活动A时,它不会发送Stringrequest

如何通过点击A按钮停止活动B从活动Home/Back返回时发送请求?

这是我的父活动

    public class MyContactsActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ContactsAdapter adapter;
    private NetworkChecker networkChecker;
    private SessionManager sessionManager;
    private AppConfig appConfig;
    private RelativeLayout loading;
    AlertHelper alertHelper;
    final ArrayList<Contact> contactArrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_contacts);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        loading = (RelativeLayout) findViewById(R.id.loadingPanel);

        alertHelper = new AlertHelper(this);
        networkChecker = new NetworkChecker(this);
        sessionManager = new SessionManager(this);
        appConfig = new AppConfig();

        String phone = sessionManager.getLoggedInUserPhone();
        String url = appConfig.getApiUrlForSpecificContacts(phone);

        recyclerView = (RecyclerView) findViewById(R.id.contactsView);
        adapter = new ContactsAdapter(getApplicationContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        sendJsonRequest(url);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        TextView phone = (TextView) view.findViewById(R.id.contact_phone);
                        TextView name = (TextView) view.findViewById(R.id.contact_name);
                        Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
                        i.putExtra("selected_user_phone", phone.getText());
                        i.putExtra("selected_user_name", name.getText());
                        startActivity(i);
                    }
                })
        );

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void sendJsonRequest(String url) {
        if (networkChecker.networkAvailable()) {
            loading.setVisibility(View.VISIBLE);
            RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    loading.setVisibility(View.GONE);
                    try {
                        JSONArray jsonArray = new JSONArray(response);

                        if(jsonArray != null){
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject currentContact = jsonArray.getJSONObject(i);

                                String name = currentContact.getString("name");
                                String phone = currentContact.getString("phone");
                                String city = currentContact.getString("city");
                                String address = currentContact.getString("address");
                                Boolean verified = currentContact.getBoolean("verified");

                                Contact contact = new Contact(name, phone, city, address, verified);

                                contactArrayList.add(contact);

                            }
                            adapter.setContactsList(contactArrayList);
                        }
                        else{
                            alertHelper.displayDialog("No Contacts Found.");
                        }
                    }catch (Exception e){
                        alertHelper.displayDialog(e.getMessage());
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.setVisibility(View.GONE);
                    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                        alertHelper.displayDialog(getString(R.string.connection_failed));
                    } else {
                        alertHelper.displayDialog(error.toString());
                    }
                }
            });

            requestQueue.add(stringRequest);

        } else {
            alertHelper.displayDialog(getString(R.string.network_not_available));
        }
    }
}

这是儿童活动

public class ContactProfileActivity extends AppCompatActivity {

    String received_name;
    String received_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_profile);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Intent i = getIntent();
        Bundle b = i.getExtras();

        if(b != null){
            received_name = b.getString("selected_user_name");
            received_phone = b.getString("selected_user_phone");
        }

        CollapsingToolbarLayout toolBarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        toolBarLayout.setTitle(received_name);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                Toast.makeText(this, "Home Clicked", Toast.LENGTH_LONG).show();
                finish();
        }
        return (super.onOptionsItemSelected(menuItem));
    }
}

1 个答案:

答案 0 :(得分:8)

请勿拨打finish(),您可以使用onBackPressed()

case android.R.id.home:
   /* finish();*/
   onBackPressed();
   return true;

阅读https://developer.android.com/reference/android/app/Activity.html