Somnath Pal Somnath Pal - 22 days ago 4
Android Question

Getting back from Activity to fragment

I have a TabLayout and ViewPager in an Activity. I'm using single fragment to create the pages of tabs. I'm opening an Activity from that fragment. When I click the phone's back button to go back to the TabLayout Activity (with fragment) its working fine. But when I use Toolbar's back button, the TabLayout Activity is not opening, instead a blank page is showing. When I press phone's back button now, then only the TabLayout Activity is showing. Is there something I can do to resolve this?



public class ProdDetailsActivity extends AppCompatActivity{


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proddetails);

Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()){
case android.R.id.home:
// This is not working
onBackPressed();
finish();
}
return super.onOptionsItemSelected(menuItem);
}


}

// Fragment inside TabLayout Activity

public class SubCatFrag extends Fragment{

private TextView emptytxt;
private ListView listView;
private ArrayList<Model> mListData=new ArrayList<>();
private CustomListAdapter adapter;
private ConnectionDetector cd;
public String userid;
SharedPreferences sharedpreferences;
private ProgressDialog pd;
private static final int RQST_ONE = 1;
private static final int RQST_TWO = 2;

public static SubCatFrag newInstance(int index) {
SubCatFrag myFragment = new SubCatFrag();

Bundle args = new Bundle();
args.putInt("index", index);
myFragment.setArguments(args);

return(myFragment);
}

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

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.subcatfrag, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);


((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("LIST PRODUCT");

emptytxt = (TextView)view.findViewById(R.id.emptytxt);

listView = (ListView)view.findViewById(R.id.list);

pd = new ProgressDialog(getActivity());
cd = new ConnectionDetector(getActivity());

if(cd.isConnectingToInternet()){
fetchDetails();
}else{
Toast.makeText(getActivity(), "No Internet Available", Toast.LENGTH_SHORT).show();
}

adapter = new CustomListAdapter(getActivity(), R.layout.productlistrowlayout, mListData);
listView.setAdapter(adapter);
listView.setEmptyView(emptytxt);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

String prod=mListData.get(position).getProd_id();
String title=mListData.get(position).getTitle();
Intent intent = new Intent(getActivity(), ProdDetailsActivity.class);
intent.putExtra("prd_id",prod);
intent.putExtra("title",title);
startActivityForResult(intent,RQST_TWO);
}
});


}

private void fetchDetails() {

pd.setMessage("Please wait..");
pd.show();

sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
userid=sharedpreferences.getString("userid","");
System.out.println("usersam_"+" "+userid);

if(mListData!=null )mListData.clear();

StringRequest stringRequest = new StringRequest(Request.Method.POST, URLUtil.FETCHLIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

pd.dismiss();

try {

JSONObject obj1 = new JSONObject(response);
JSONArray jsonArray = obj1.getJSONArray("allProducts");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);

if(obj.length() != 0 ){
Model model = new Model();
model.setImage(obj.getString("prd_img"));
model.setTitle(obj.getString("title"));
model.setDate(obj.getString("date"));
model.setPrice(obj.getString("price"));
model.setProd_id(obj.getString("id"));
double rate = i + (i*0.1);
model.setRate(String.valueOf(rate));

mListData.add(model);
}


}

adapter.notifyDataSetChanged();


} catch (JSONException e) {
e.printStackTrace();
//Toast.makeText(HomeActivity.this, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
pd.dismiss();
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getActivity(),getActivity().getString(R.string.error_network_timeout),Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();

params.put("user_id", userid);
return params;
}

};

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(resultCode==RESULT_OK && requestCode==RQST_ONE){
fetchDetails();
}else if(resultCode==RESULT_OK && requestCode==RQST_TWO){
fetchDetails();
}
}
}




Answer

Try this code instead of onOptionsItemSelected..... Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent goBack = new Intent(getApplicationContext(),YourActivity.class);
            startActivity(goBack);
            finish();
        }
    });
Comments