How to Refresh the fragment, when Internet Connection is Resume - android

I had a fragment, in which first I check for availability for internet connection. If its available its fine, otherwise, I want to refresh the page by clicking on retry button. The problem which comes is, I am not able to refresh the fragment
This is my fragment code.
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homework, container, false);
listView = rootView.findViewById(R.id.home_list);
adapter = new HomeWorkAdapter(getContext(), R.layout.home_single, arrayList);
listView.setAdapter(adapter);
cal = rootView.findViewById(R.id.date_select);
boolean x = handleNetworkConnection();
if (x == true) {
methodListener();
SharedPreferences preferences = getActivity().getSharedPreferences("user_login", Context.MODE_PRIVATE);
HashMap<String, String> map = new HashMap<>();
map.put("school_id", preferences.getString("school_id", ""));
map.put("class", preferences.getString("classes", ""));
map.put("sec", "homeera");
defaultfetch(map);
}
else
{
final LinearLayout ll = new LinearLayout(getActivity());
TextView textView = new TextView(getActivity());
Button button = new Button(getActivity());
ImageView image = new ImageView(getActivity());
ll.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
ll.setBackgroundColor(Color.parseColor("#ecf0f1"));
image.setImageResource(R.drawable.errorsq);
button.setBackgroundColor(Color.parseColor("#02b48a"));
button.setText("Try Again");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(getActivity().).attach(this).commit();
*/
}
});
ll.addView(textView);
ll.addView(image);
ll.addView(button);
ll.setOrientation(LinearLayout.VERTICAL);
View rootview = ll;
return rootview;
}
return rootView;
}
In this code, I had applied a way to refresh the fragment, but the problem is that after refreshing UI comes blank. Nothing is there on the screen.

You should not refresh the fragment but refresh the list when you get an internet connection.
Since your method handleNetworkConnection() returns synchronously, you could organize the code as follows:
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homework, container, false);
listView = rootView.findViewById(R.id.home_list);
adapter = new HomeWorkAdapter(getContext(), R.layout.home_single, arrayList);
listView.setAdapter(adapter);
cal = rootView.findViewById(R.id.date_select);
prepareList();
}
void prepareList() {
boolean x = handleNetworkConnection();
if (x == true) {
// same code as now, load the list content and display it
} else {
// same code as now except the click listener:
public void onClick(View view) {
prepareList();
}
//
}
}

Related

Saving a cardview programmatically even after closing the activity

I am very new to android and I am trying to make CardView by programmatically, I am using Fragment. By setting an OnClick on the button I am able to create cards in my layout. The issue is after closing the activity cards are not showing.
How can I save the cards, so after closing the activity cards should be there?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle("Okhlee");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.hawker_jobs_fragment_layout, container, false);
context = getContext();
button = (Button) view.findViewById(R.id.hawker_job_add_card_view_button);
button.setOnClickListener(this);
relativeLayout = (RelativeLayout) view.findViewById(R.id.hawker_job_relative_layout);
return view;
}
#Override
public void onClick(View v) {
createCardView();
}
/*Adding cardview programmatically function */
private void createCardView() {
CardView addedCardView = new CardView(context);
layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, height);
addedCardView.setLayoutParams(layoutParams);
addedCardView.setPadding(10 ,10, 10, 10);
addedCardView.setRadius(15);
addedCardView.setCardBackgroundColor(Color.BLUE);
addedCardView.setMaxCardElevation(30);
addedCardView.setMaxCardElevation(6);
relativeLayout.addView(addedCardView);
}
Sorry for my bad English.
You can use SharedPreferences in order to know whether you should display the card.
Here's a sample code using your original one -
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.hawker_jobs_fragment_layout, container, false);
context = getContext();
button = (Button) view.findViewById(R.id.hawker_job_add_card_view_button);
button.setOnClickListener(this);
relativeLayout = (RelativeLayout) view.findViewById(R.id.hawker_job_relative_layout);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean shouldDisplayCard = sharedPref.getBoolean("should_display_card", false);
if(shouldDisplayCard)
createCardView();
return view;
}
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("should_display_card", true);
editor.apply();
createCardView();
}

How to change view after getting successful request android?

I have this piece of code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
tableView = inflater.inflate(R.layout.fragment_table, container, false);
View layout = inflater.inflate(R.layout.fragment_1, container, false);
if (roomArray == null || roomArray.isEmpty()) {
roomArray = getTablesList(new VolleyCallback() {
#Override
public void onSuccess(ArrayList<RoomsClass> result) {
Toast.makeText(getActivity(), "onSuccess", Toast.LENGTH_LONG).show();
}
});
} else {
ArrayList<View> tableList = new ArrayList<>();
ArrayList<Tables> tables;
Toast.makeText(getActivity(), "IsNotNull", Toast.LENGTH_LONG).show();
tables = roomArray.get(0).getTables();
GridLayout gridLayout = (GridLayout) layout.findViewById(R.id.grid_layout);
for (int i = 0; i < 1; i++) {
tableView = inflater.inflate(R.layout.fragment_table, container, false);
TextView textView = (TextView) tableView.findViewById(R.id.table_number);
textView.setText(tables.get(i).getTableNumber());
GridLayout.Spec row = GridLayout.spec(i / 5);
GridLayout.Spec col = GridLayout.spec(i);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(row, col);
gridLayout.addView(tableList.get(i), i, params);
}
}
return layout;
}
so I have onSuccess, but I cant add views to my fragment. I need to somehow call all methods after onSuccess, but its inner class so I can't handle anything there. So what is the right way of doing this?
Are you inflating two fragments in createView?
tableView = inflater.inflate(R.layout.fragment_table, container, false);
View layout = inflater.inflate(R.layout.fragment_1, container, false);
have u try to use handler to solve this problem , the use of handler can avoid do something in a inner class.
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case a:
//do somthing
break;
}
super.handleMessage(msg);
}
};

update spinner from dialogfragment

I have a Spinner in my class TelaEntrada.java loading normally.
public class TelaEntrada extends Fragment {
public Fragment newInstance(Context context) {
TelaEntrada telaEntrada = new TelaEntrada();
return telaEntrada;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.telaentrada, container, false);
DbEntrada banco = new DbEntrada(getActivity().getApplicationContext());
List<Tipo> tipos = banco.todosTipos();
List<String> item = new ArrayList<String>();
for(Tipo tipo : tipos){
item.add(tipo.getDescricao().toString());
}
final Spinner spn_Entrada = (Spinner) root.findViewById(R.id.spnEntradaTipo);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, item);
spn_Entrada.setAdapter(adapter2);
I too have one DialogFragment in another class. Code is below.
public class DialogTipo extends DialogFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
final View root = (View) inflater.inflate(R.layout.dialog_tipo, container, false);
final EditText txtDialogTipo = (EditText)root.findViewById(R.id.txtDialogTipo);
Button btnDialogTipoAdd = (Button) root.findViewById(R.id.btnDialogTipoAdd);
Button btnDialogTipoCancel = (Button) root.findViewById(R.id.btnDialogTipoCancel);
btnDialogTipoAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DbEntrada banco = new DbEntrada(getActivity().getApplicationContext());
banco.insereTipo(txtDialogTipo.getText().toString());
//I want update my spinner here!
dismiss();
}
});
getDialog().setTitle("Inserir Novo Tipo");
return root;
}
}
I wanted to add a new item, the spinner was directly updated the database to display the new information in the User spinner. Thanks. Sorry for my english!

Android: NullPointerException when changing fragment

I have two fragments in my activity. I'm implementing actionbarsherlock TabNavigation and each tab has separate fragment. I'm performing network operation and place the results in a TextView.
If I change the fragment after the current fragment is completely loaded, it works fine. The NullPointerException only occurs if I change the fragment while the current fragment is still loading. Please help.
FRAGMENT 1:
public class Fragment1 extends SherlockFragment {
public static Fragment1 newInstance() {
Fragment1 f = new Fragment1 ();
return f;
}
private static LinearLayout mainll;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub4
final View V = inflater.inflate(R.layout.fragment_1, container, false);
AsyncHttpClient client = new AsyncHttpClient();
client.get(((MainActivity) act).getUrl(), new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Document document = Jsoup.parse(response);
Element results = document.getElementById("search_results");
mainll = (LinearLayout) V.findViewById(R.id.content);
LayoutParams mainllParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainllParams.setMargins(10, 5, 0, 0);
if(results != null) {
TextView tv= new TextView(getActivity()); //NPE occurs here
tv.setLayoutParams(mainllParams);
tv.setText(results.ownText());
tv.setGravity(Gravity.CENTER_HORIZONTAL);
mainll.addView(tv);
}
});
return V;
}
}
FRAGMENT 2:
public class Fragment2 extends SherlockFragment {
public static Fragment2 newInstance() {
Fragment2 f = new Fragment2 ();
return f;
}
private static LinearLayout mainll;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub4
final View V = inflater.inflate(R.layout.fragment_1, container, false);
AsyncHttpClient client = new AsyncHttpClient();
client.get(((MainActivity) act).getUrl(), new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Document document = Jsoup.parse(response);
Element results2 = document.getElementById("more_results");
mainll = (LinearLayout) V.findViewById(R.id.content);
LayoutParams mainllParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainllParams.setMargins(10, 5, 0, 0);
if(results2 != null) {
TextView tv2 = new TextView(getActivity()); //NPE Occurs here
tv2.setLayoutParams(mainllParams);
tv2.setText(results.ownText());
tv2.setGravity(Gravity.CENTER_HORIZONTAL);
mainll.addView(tv2);
}
});
return V;
}
}
Thanks in advance
Well, you already answered your own question: NPE occurs because current fragment is in detached state, it's mean it detached from activity and have no link to it -> getActivity() returns null.
You could add several extra options for your check to verify that your fragment is still visible and attached:
if(results2 != null && getActivity()!=null && isVisible()) {
TextView tv2 = new TextView(getActivity()); //NPE Occurs here
tv2.setLayoutParams(mainllParams);
tv2.setText(results.ownText());
tv2.setGravity(Gravity.CENTER_HORIZONTAL);
mainll.addView(tv2);
}

my custom View control not Redrawing in Fragment

I have created my custom view control which extends from the View control, only drawing some information in the onDraw method.
Everything works if I create the control on a regular activity layout. But if I create this control in onCreateView() of Fragment, it paints while creating and then my View "freezes". It works and resolves but is not calling onDraw(). I'm trying to call invalidate() but nothing.
Any ideas?
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.button, container, false);
mAgatButton = (agatButton) v.findViewById(R.id.agatButton1);
mAgatButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// This not Repainted
final GraphViewSeries TahoSer = mGraphTaho.getSeries((byte)0);
mGraphTahoPos++;
TahoSer.appendData(new GraphViewData(mGraphTahoPos, 50d), true);
//This Work correct
mTahoLabel.setText(String.format(getString(R.string.button_rpm), (int)(Math.random()*1000)));
Log.d(agatButton.class.toString(),"Click Detected: "+TahoSer.size());
}
});
final Context context = getActivity().getApplicationContext();
LinearLayout graphView = (LinearLayout) v.findViewById(R.id.graph_lay_taho);
graphView.addView(mGraphTaho = getGraphView(context,"Taho"));
mTahoLabel = (TextView) v.findViewById(R.id.tahoText);
mTahoLabel.setText(String.format(getString(R.string.button_rpm), 0));
return v;
}
private GraphView getGraphView(Context context, String Name)
{
final GraphView tmpView = new LineGraphView(context,Name);
tmpView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
List<GraphViewData> initalSeriesData = new ArrayList<GraphViewData>();
for (byte i=0;i<20;i++)
initalSeriesData.add(new GraphViewData(i, 0d));
final GraphViewSeries tahoSeries = new GraphViewSeries(initalSeriesData);
((LineGraphView) tmpView).setDrawBackground(true);
tmpView.addSeries(tahoSeries);
tmpView.setViewPort(1, 20);
tmpView.setScalable(false);
tmpView.setManualYAxis(true);
tmpView.setManualYAxisBounds(100, 0);
return tmpView;
}
If I don't use Fragment everything works. What is wrong?

Categories

Resources