Progress Dialog does not appear - java

I have a fragment that, when is pressed a button should show a Progress Dialog and execute a method that contains an AsyncTask but when I press the button, the Progess Dialog does not appear on the screen but the async task is executed. This is the code of the fragment
public class ParcheggiaFragment extends Fragment {
private Button button;
ProgressDialog progressDialog1;
SharedPreferences prefs;
HttpGetNoleggio httpGetNoleggio;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View layout = inflater.inflate(R.layout.fragment_parcheggia, container, false);
button = (Button) layout.findViewById(R.id.button);
prefs = this.getActivity().getSharedPreferences(Keys.SHARED_PREFERENCES, Context.MODE_PRIVATE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog1.show();
int a = checkNoleggioCompletato();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_principale, new ResultFragment());
fragmentTransaction.commit();
}
});
return layout;
}
private int checkNoleggioCompletato() {
final int id = prefs.getInt(Keys.ID_UTENTE, -1);
Integer[] noleggio;
int idNoleggio = -1;
try {
String str = "here i put the url that i have to use" + id;
URL url = new URL(str);
noleggio = httpGetNoleggio.execute(url).get();
idNoleggio = noleggio[0];
int idBici = noleggio[1];
int noleggioResult = idNoleggio;
} catch (MalformedURLException | ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return idNoleggio;
}
#Override
public void onStart() {
progressDialog1 = new ProgressDialog(this.getActivity());
progressDialog1.setIndeterminate(true);
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
httpGetNoleggio = new HttpGetNoleggio(this.getActivity());
}
#Override
public void onResume() {
super.onResume();
}
}
The code seems correct and I can't understand why the ProgressDialog does not appear.
HttpNoleggio is another class that extends AsyncTask and implements the doInBackground method

As per your code you are displaying the progress bar in ParcheggiaFragment and then replacing this fragment with ResultFragment. As ResultFragment replaced ParcheggiaFragment so that progress bar is not displaying. Just comment the following code:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_principale, new ResultFragment());
fragmentTransaction.commit();
Then, progressbar will be visible.

Related

I want to Send Data Activity to fragment But InterFace Method Never Called

i implements my interface in Two fragments i want to send Data from Activity to both Fragments..when i do this my data send in Second Fragment not in First Fragment. it called only Second Fragments interface method..not call first Fragment interface method i d'nt UnderStand Please Some One Help....
This is Main Activity
public class MainActivity extends AppCompatActivity implements FragmentCommunication {
TextView textView;
ReceiveMessage receiveMessage;
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textAcitivity);
editText = findViewById(R.id.editActivity);
button = findViewById(R.id.buttonActivity);
if (findViewById(R.id.fragment1)!= null)
{
if (savedInstanceState != null)
{
return;
}
}
FirstFragment firstFragment = new FirstFragment();
SecondFragment secondFragment = new SecondFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction()
.add(R.id.fragment1, firstFragment, null);
fragmentTransaction.commit();
FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction().add(R.id.fragment2, secondFragment,null);
fragmentTransaction1.commit();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText.getText().toString().trim();
receiveMessage.receiveMessage(name, 3);
}
});
}
#Override
public void onAttachFragment(#NonNull Fragment fragment) {
super.onAttachFragment(fragment);
try {
receiveMessage = (ReceiveMessage) fragment;
} catch (ClassCastException e) {
throw new ClassCastException(fragment.toString() + " must implement receiveMessage..");
}
}
}
This is my interface
public interface ReceiveMessage {
void receiveMessage(String message, int from);
}
This is my First Fragment
public class FirstFragment extends Fragment implements ReceiveMessage {
private View view;
private TextView textView;
private EditText editText;
private Button button;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.firstfragment, container, false);
textView = view.findViewById(R.id.textView10);
editText = view.findViewById(R.id.Edit1);
button = view.findViewById(R.id.button1);
return view;
}
#Override
public void receiveMessage(String message, int from) { // THIS METHOD NAVER CALLED WHEN I SEND dATA
FROM aCTIVITY
if (from == 3)
{
textView.setText(message);
}
}
}
This is my Second Fragment
public class SecondFragment extends Fragment implements ReceiveMessage {
private View view;
private TextView textView;
private EditText editText;
private Button button;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.secondfragment, container, false);
textView = view.findViewById(R.id.textView2);
editText = view.findViewById(R.id.editText2);
button = view.findViewById(R.id.button);
return view;
}
#Override
public void receiveMessage(String message, int from) {
if (from == 3)
{
textView.setText(message);
}
}
}
Every time when you add a new fragment, the "onAttachFragment" of activity gets called again. So when you added the second fragment, you resetted the value of "receiveMessage" object to the interface implementation of second fragment.Hence you should rewrite your code as :
ReceiveMessage firstReceiver;
ReceiveMessage secondReceiver;
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof FirstFragment) {
firstReceiver = (ReceiveMessage) fragment;
} else if (fragment instanceof SecondFragment) {
secondReceiver = (ReceiverMessage) fragment;
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText.getText().toString().trim();
firstReceiver.receiveMessage(name, 3);
secondReceiver.receiveMessage(name, 3);
}
});

NextActivity onCreate() is skipped

I am creating a social app and the users can upload an image and then write a caption on the next screen right after. My problem is that the activity where the user creates the caption, gets completely skipped over and goes to the profile page. The image goes to the firebase storage but I can't write a caption.
07-10 15:23:21.150 30970-31309/tabian.com.hash E/ImageLoader: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
java.lang.UnsupportedOperationException: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromOtherSource(BaseImageDownloader.java:280)
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:99)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.downloadImage(LoadAndDisplayImageTask.java:291)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryCacheImageOnDisk(LoadAndDisplayImageTask.java:274)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:230)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:136)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
GalleryFragment.Java
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: Started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the gallery screen.");
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
if (isTaskRoot()) {
Intent intent = new Intent(GalleryFragment.this.getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
GalleryFragment.this.startActivity(intent);
} else {
Intent intent = new Intent(GalleryFragment.this.getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
GalleryFragment.this.startActivity(intent);
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
}
});
init();
return view;
}
NextActivity.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = (EditText) findViewById(R.id.caption) ;
setupFirebaseAuth();
ImageView backArrow = (ImageView) findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the activity");
finish();
}
});
TextView share = (TextView) findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
ProfileActivity.Java :
public class ProfileActivity extends AppCompatActivity implements
ProfileFragment.OnGridImageSelectedListener ,
ViewPostFragment.OnCommentThreadSelectedListener,
ViewProfileFragment.OnGridImageSelectedListener{
private static final String TAG = "ProfileActivity";
#Override
public void onCommentThreadSelectedListener(Photo photo) {
Log.d(TAG, "onCommentThreadSelectedListener: selected a comment thread");
ViewCommentsFragment fragment = new ViewCommentsFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_comments_fragment));
transaction.commit();
}
#Override
public void onGridImageSelected(Photo photo, int activityNumber) {
Log.d(TAG, "onGridImageSelected: selected an image gridview: " + photo.toString());
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
args.putInt(getString(R.string.activity_number), activityNumber);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_post_fragment));
transaction.commit();
}
private static final int ACTIVITY_NUM = 4;
private static final int NUM_GRID_COLUMNS = 3;
private Context mContext = ProfileActivity.this;
private ProgressBar mProgressBar;
private ImageView profilePhoto;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d(TAG, "onCreate: started.");
init();
}

How to send data from DialogFragment to DialogFragment?

I have a problem with sending data from fragment to fragment. I have DialogFragment named fmonday, it is Viewpager's fragment.
I call other DialogFragment, named AlertDFragment to add some data to my fragment. I can read the data from spinner, it's working good.
Now I need to send one variable, type string, from AlertDFragment to fmonday.
Here is the code of fmonday:
public class fmonday extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor> {
DB db;
Button button12;
DialogFragment dlg1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fmonday, container, false);
button12 = (Button) rootView.findViewById(R.id.button12);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dlg1.show(getFragmentManager(), "dlg1");
}
});
return rootView;
}
And code of AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
getDialog().dismiss();
}
});
return adb.create();
}
I can't find the way to send this string1 variable to my fmonday DialogFragment, because simple intent doesn't work with non-activity things. Also read some advices about bundle, but couldn't find out how to work with it.
Thanks
UPDATE
fmonday:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
string1 = getArguments().getString("latitude");
}
AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
Bundle bundle = new Bundle();
bundle.putString("latitude", string1);
fmonday alertdfragment= new fmonday();
alertdfragment.setArguments(bundle);
getDialog().dismiss();
}
});
return adb.create();
}
To Set Data:
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
To Get Data
String latitude = getArguments().getString("latitude")
You can crate a setter to your second dialogFragment ex:
public void setSmth(String value)
{
this.myData = value;
}
, than on your first dialog
DialogFragment dlg1 = new AlertDFragment();
dlg1.setSmth(your data here);
before showing the second one;

Fragment returning null from intent

So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"
Class sending the intent
public class Intennt extends ActionBarActivity {
Button bt1,bt2,bt3,bt4;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intennt);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
startActivity(i);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,
ItemDetailFragment.ACTION_2);
startActivity(i);
}
});
}
Fragment receiving the intent and extras
public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem =
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(getActivity(), "id is null!",
Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(getActivity(), "Aloha from button 1!",
Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_3) {
Log.i("TAG", "Hello from button 3");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_4) {
Log.i("TAG", "Hello from button 4");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
return rootView;
}
}
To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :
FragmentClass fragment = new FragmentClass();
getFragmentManager()
.beginTransaction()
.replace(R.id.your_fragment_view, fragment)
.commit();
You can proceed to every action right in the current activity (as it stays the main activity).
public class Questions extends DialogFragment {
private static Button Submit;
public int count = 0;
public interface DialogListener {
void onQuestionsFinish(ArrayList<xmlQuestion> l);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Submit = (Button) rootView.findViewById(R.id.SubmitButton);
Submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
for(int i = 0; i<questionList.size(); i++)
{
questionList.get(i).setAnswer();
}
DialogListener activity = (DialogListener) getActivity();
activity.onQuestionsFinish(questionList);
Questions.this.dismiss();
}
});
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
yInch = metrics.ydpi;
pixHeight = metrics.heightPixels;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point(); display.getSize(size);
screenWidth=size.x; screenHeight=size.y;
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
BodyLayout.setLayoutParams(bodyParams);
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.height=screenHeight; wmlp.width=screenWidth;
getDialog().getWindow().setAttributes(wmlp);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.dimAmount=0.4f;
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getDialog().setCanceledOnTouchOutside(true);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
}
public Questions()
{
}
}
You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...
Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");

How do I update a ListView in a Fragment?

I´m trying to udate a ListView in a Fragment the only way it actually will work is if I instanciate the fragment new. adpter.notifyDataSetChanged() is not working? Whay not? Here the Code an Activity and the Fragment:
public class TimerList extends Activity{
private DataSource datasource;
TimerListFragment timerfragment;
IntervalListFragment intervalfragment;
public List<TimerObject> values;
public String name;
public String intervals;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interval_fragment_container);
datasource = new DataSource(this);
datasource.open();
values = datasource.getAllComments();
if (savedInstanceState == null) {
Toast.makeText(getApplicationContext(), "MADE NEW FRAGMENTS", Toast.LENGTH_SHORT).show();
timerfragment = new TimerListFragment();
intervalfragment = new IntervalListFragment();
}
}
public void delete(Long position){
TimerObject timerobject = datasource.getTimerObject(position);
datasource.deleteComment(timerobject);
values = datasource.getAllComments();
}
#Override
protected void onStart() {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, timerfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
super.onStart();
}
And my Fragment :
public class TimerListFragment extends ListFragment {
List<TimerObject> values ;
Activity a;
ArrayAdapter<TimerObject> adapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
values = ((TimerList)getActivity()).getValues();
setBar();
adapter = new ArrayAdapter<TimerObject>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
super.onCreate(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((TimerList)getActivity()).play(Long.valueOf(position));
super.onListItemClick(l, v, position, id);
}
public void setBar(){
ActionBar actionbar = getActivity().getActionBar();
actionbar.setTitle("Timer List");
}
public void update(){
setBar();
Toast.makeText(getActivity(), "UPDATE", Toast.LENGTH_LONG).show();
values = ((TimerList)getActivity()).getValues();
adapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.interval_timer_list,
container, false);
return view;
}
#Override
public void onStart() {
update();
lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
final TimerObject selected = adapter.getItem(position);
final Dialog d = new Dialog(getActivity());
d.setContentView(R.layout.interval_deletetimer_dialog);
d.setTitle("Delete " + selected.getComment() + "?" );
ImageButton delete = (ImageButton) d.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((TimerList)getActivity()).delete(Long.valueOf(selected.getId()));
update();
}
});
d.show();
return true;
}
});
super.onStart();
}
I tried to do something similar, and I solved this problem by simply redoing the fragment transaction.
In your case, you could accomplish this within your onListItemClick() method.
you could copy this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, timerfragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
into your onListItemClick() method in your fragment
This resets the fragment. Unfortunately, this would also set your list to null. A way around this would be to make the values list a private static variable of the TimerListFragment class. That way, any changes made to the list will remain 'saved', and when you reload your fragment, it will be populated with the newly updated list.
hope this helps

Categories

Resources