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);
}
};
Related
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();
}
//
}
}
My Code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Uri uri = Uri.parse("Home");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
LinearLayout linearLayout = (LinearLayout) rootView.findViewById(R.id.mesage_linear1);
final TextView message = new TextView(getActivity());
number_view.setText("Long Text");
int m_width = message.getMeasuredWidth();
int m_height = message.getMeasuredHeight();
Toast.makeText(getActivity(),"Height : "+m_height+"\nWidth : "+m_width,Toast.LENGTH_LONG).show();
return rootView;
}
I want to get the height and width of the programmatically created TextView.
Output is Height : 0 and Width : 0
At that point the View hasn't been laid out yet. You have to manually measure it (via View.measure()) or to wait until it is laid out:
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int height = textView.getHeight();
int width = textView.getWidth();
}
});
TextView tv=(TextView)findViewById(R.id.text);
tv.setText("Android");
tv.measure(0, 0);
tv.getMeasuredWidth();
tv.getMeasuredHeight();
tv.getTextSize();
I'm quite new in android and i have a problem trying to develop an app.
I want to make a countdown timer in my activity but i need to do it within a fragment, so i need to put a for loop that count from 0 - 10 and refresh a TextView inside that fragment.
I need the fragment to do it independently from the activity.
thanks for your collaboration
public class fragmento_3 extends Fragment {
int count= 10;
TextView texto_count;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragmento_3, container, false);
texto_count = (TextView)v.findViewById(R.id.texto_count);
return v;
}
}
and I want to put this inside
for(int x = count; x >= 0 ; x--){
texto_count.setText(String.valueOf(x));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
thanks,
It is better to use Timer for periodic tasks rather than using Thread.sleep.
Try this code
public class fragmento_3 extends Fragment{
int count= 10;
TextView texto_count;
Timer t;
View v;
TimerTask timer= new TimerTask(){
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
count--;
if(count >= 0) {
texto_count.setText(Integer.toString(count));
}
}
});
if (count <= 0) {
t.cancel();
}
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragmento_3, container, false);
texto_count = (TextView)v.findViewById(R.id.texto_count);
t = new Timer();
t.scheduleAtFixedRate(timer , 0 , 2000);
return v;
}
}
Its probably because you are using the wrong variable texto_conteo. You have declared texto_count as the instance variable so you probably want to use that.
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);
}
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?