I am developing and app, where I use ProgressDialog to show loading screen when data is being received from the socket. Here is my code for the Fragment
public class MainFragment extends Fragment {
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
public void onClick(View view) {
// do some stuff
}
} );
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog = ProgressDialog.show(getActivity(), "", "Loading..",true);
new Thread() {
public void run() {
try{
// establish socket connection and get data
}
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
progressDialog.dismiss();
}
}.start();
} );
return view
}
}
The Problem now is with respect to getActivity(). While executing the app once, the correct views are established but on the consecutive runs, the view is null, since the getActivity doesn't properly instantiate or is set.
I tried to save the activity with onAttach() and then pass this to ProgressDialog as shown below
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
But still the view returned was null. Can anyone help me on how to to achieve this? Thanks!