ArrayList<String> getIntent().getStringArrayListExtra - java

I want to get an ArrayList from one Fragment to another, I use the Intentmethod, like this:
Fragment where I want to get it from
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putStringArrayListExtra("server_name_list", server_name_list);
If I debug this, I can see the new entry I did. But in the Fragment where I use getIntent().getStringArrayListExtra there is no new entry.
What did I wrong?
Here is the code from the Fragment where I use the method:
/* Server Name Spinner */
ArrayList<String> server_name_list = getIntent().getStringArrayListExtra("server_name_list");
if (server_name_list != null) {
spinner = (Spinner) view.findViewById(R.id.server_spinner);
;
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Edit: Whole code
public class MainActivity extends AppCompatActivity implements AddServerFragment.Callback {
static WebView myWebView;
Fragment AddServerFragment, WebViewFragment;
ArrayList<String> server_name_list;
#Override
public ArrayList<String> getArrayListFromActivity() {
WebViewFragment frag = (WebViewFragment) getSupportFragmentManager().findFragmentByTag("AddServerFragment");
if (frag != null) {
server_name_list = frag.getArrayListFromWebViewFragment();
}
return server_name_list;
}
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.webview:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WebViewFragment() {
})
.commit();
return true;
case R.id.add_server:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AddServerFragment() {
})
.commit();
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.container) != null) {
if (savedInstanceState != null) {
return;
}
AddServerFragment = new Fragment();
WebViewFragment = new Fragment();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WebViewFragment() {
})
.commit();
}
/*WebView Fragment*/
public class WebViewFragment extends Fragment {
String selected;
Spinner spinner;
public WebViewFragment(){
}
private Callback callback;
public interface Callback {
public ArrayList<String> getArrayListFromActivity();
}
#Override
public void onAttach(Activity activity) {
callback = (Callback) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
/* WebView */
myWebView = (WebView) view.findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
/* JavaScript Enable */
webSettings.setJavaScriptEnabled(true);
/* Server Name Spinner */
ArrayList<String> server_name_list = callback.getArrayListFromActivity();
if (server_name_list != null) {
spinner = (Spinner) view.findViewById(R.id.server_spinner);
;
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
return view;
}
}
/*Add Server Fragment*/
public class AddServerFragment extends Fragment
implements View.OnClickListener {
#Override
public void onClick(View view) {
}
public AddServerFragment(){
}
Button btn_back, btn_add;
EditText server_ip, server_name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_ip, container, false);
server_ip = (EditText) view.findViewById(R.id.edit_server_address);
server_name = (EditText) view.findViewById(R.id.edit_server_name);
btn_back = (Button) view.findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WebViewFragment() {
})
.commit();
}
});
btn_add = (Button) view.findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String new_server_ip = null, new_server_name = null;
ArrayList<String> server_name_list = new ArrayList<>();
ArrayList<String> server_ip_list = new ArrayList<>();
new_server_ip = server_ip.getText().toString();
server_ip_list.add(new_server_ip);
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
return view;
}
}
/* WebView Client */
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}

You can store your ArrayList as a member variable of your container activity :
private ArrayList<String> server_name_list;
Add a getter:
public ArrayList<String> getArrayList() {
return server_name_list;
}
And in your fragments, you access it this way: (supposing that the container activity's name is MainActivity)
ArrayList<String> arraylist = ((MainActivity)getActivity()).getArrayList();

JDev's answer is correct in so far as it will give you the result you want with the smallest amount of code. It is also, conceptually, the easiest method to understand. However, the technique recommended by Android Developers for a Fragment to communicate with its hosting Activity is via an interface.
It is worth learning this technique IMO, even if you are unfamiliar with interfaces in Java and Android. This is because interfaces are used in all but the most basic of projects, and they underpin many recommended design patterns, so you can be sure they will turn up sooner or later :)
Here is how you would solve your problem with an interface:
public class MyFragment extends Fragment {
private Callback callback;
public interface Callback {
public ArrayList<String> getArrayListFromActivity();
}
#Override
public void onAttach(Activity activity) {
callback = (Callback) activity;
//NB: The above will throw ClassCastException if your Activity
//Does not implement MyFragment.Callback
}
//Later in your code, whenever you want to grab the ArrayList<String> from your Activity:
ArrayList<String> arrList = callback.getArrayListFromActivity();
Inside MainActivity:
public class MainActivity extends AppCompatActivity implements MyFragment.Callback {
ArrayList<String> arrayList;
#Override
public ArrayList<String> getArrayListFromActivity() {
//If the ArrayList is in your Activity, then use:
return arrayList;
//If the ArrayList is in another Fragment, then use:
FragmentTwo frag = (FragmentTwo) getSupportFragmentManager().findFragmentByTag("tag_of_fragment_two");
if (frag != null) {
arrayList = frag.getArrayListFromFragmentTwo();
return arrayList;
}
}
}

ArrayList<String> server_name_list;//declare variable
... void onCreate(...)
{
.
.
.
server_name_list = getIntent().getStringArrayListExtra("server_name_list");//assign value
}
try this.if doesn't work try
intent.putExtra("server_name_list", server_name_list);
instead of
intent.putStringArrayListExtra("server_name_list", server_name_list);

you can simply pass any parameter through static instance of that fragment.
intent is normally used to transfer data among activities not fragments
DestinationFragment Frag = DestinationFragment.getInstance(yourArrayList);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (shouldAddToBackStack)
ft.addToBackStack(tag);
else {
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
ft.replace(R.id.container, Frag, tag)
.commit();
getSupportFragmentManager().executePendingTransactions();
in your DestinationFragment
public static DestinationFragment getInstance(ArrayList yourArrayList){
DestinationFragment fragment=new DestinationFragment();
Bundle args = new Bundle();
args.putString(args, yourArrayList);
fragment.setArguments(args);
return fragment;
}

Related

How to create an custom alertDialog from a tabbed fragment?

Problem:
I'm trying to open a custom dialog after pressing a button in my tabbed fragment.
It's seems like my MainActivity activity is sent to the dialog while i want my tabbed fragment(GroupFragment) to be sent so i can change the editText(for now) in this fragment.
Code:
public class GroupFragment extends Fragment implements AddGroupDialog.AddGroupDialogListener {
private Button addGroupButton;
private TextView textViewNoGroups;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_group, container, false);
addGroupButton = view.findViewById(R.id.addGroupButton);
textViewNoGroups = view.findViewById(R.id.textViewNoGroups);
addGroupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewGroupDialog();
}
});
scaleAnimation(addGroupButton);
return view;
}
private void scaleAnimation(View v){
Animator scale = ObjectAnimator.ofPropertyValuesHolder(v,
PropertyValuesHolder.ofFloat(View.SCALE_X, 0, 1.2f, 1),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 0, 1.2f, 1)
);
scale.setDuration(600);
scale.start();
}
private void addNewGroupDialog(){
AddGroupDialog dialog = new AddGroupDialog();
assert getFragmentManager() != null;
dialog.show(getFragmentManager(), "add new group dialog");
}
#Override
public void applyString(String groupName) {
textViewNoGroups.setText(groupName);
}
}
public class AddGroupDialog extends AppCompatDialogFragment {
private EditText editTextGroupName;
private AddGroupDialogListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_add_new_group_dialog, null);
builder.setView(view)
.setTitle("")
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String groupName = editTextGroupName.getText().toString();
listener.applyString(groupName);
}
});
editTextGroupName = view.findViewById(R.id.editTextGroupName);
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (AddGroupDialogListener) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString() +
"Must implement AddGroupDialogListener");
}
}
public interface AddGroupDialogListener{
void applyString(String groupName);
}
}
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new GroupFragment();
break;
case 1:
fragment = new AttendanceFragment();
break;
case 2:
fragment = new StatisticsFragment();
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
return TAB_TITLES.length;
}
}
Error:
java.lang.ClassCastException: com.example.attendencetaker.MainActivity#26602bcMust implement AddGroupDialogListener
I hope my explanation of the problem is clear. Thank you!
Make the activity implement your interfaces and so on and then pass all data to the fragment with an method on the fragment. You will need an reference to actual Fragment that is displayed.
In your fragment add a method similar to this:
public void updateData(String data) {
editText.setText(data);
}
And in the override method of the interface in your activity to this:
#Override
public void update(String data) {
fragment.updateData(data);
}
Update
Use this Adapter instead:
public class SectionTabAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments = new ArrayList<>();
private ArrayList<String> titles = new ArrayList<>();
public SectionTabAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public void addFragment(Fragment fragment, String title) {
fragments.add(fragment);
titles.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
In your activity then do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionTabAdapter = new SectionTabAdapter(this, getSupportFragmentManager());
Fragment groupFragment = new GroupFragment();
Fragment attendanceFragment = new AttendanceFragment();
Fragment statisticsFragment = new StatisticsFragment();
sectionTabAdapter.addFragment(groupFragment, context.getString(R.string.title_1);
sectionTabAdapter.addFragment(attendanceFragment, context.getString(R.string.title_2);
sectionTabAdapter.addFragment(statisticsFragment, context.getString(R.string.title_3);
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionTabAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}

Fragments - tag, condition and show

I will be very grateful for the analysis of these lines of code, because I do not understand the relationship between them. Especially if I
I will change tags to 2 different tags, nothing changes in the application. In addition, if the condition if is removed, there are also no changes. In the comments I have a brief translation, I am still unable to understand these three lines.
Fragment fr = manager.findFragmentByTag("AddCity");
What role does this condition fulfill?
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();
}
And:
fr2.show(manager, "AddCity");
This is the whole code snippet
/*
I create a variable manager, and then I get a FragmentManager and assign it to the variable manager,
thanks to the variable manager, I can run actions on fragments
*/
FragmentManager manager = getSupportFragmentManager();
Fragment fr = manager.findFragmentByTag("AddCity");//I created fr variable and ???
Fragment1 fr1 = (Fragment1)
manager.findFragmentById(R.id.list); // I created fr1 variable and assigned fragment list to the variable fr1
if (view.equals(b1)) {
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();//Creates a new transaction to change fragments at runtime, removes an existing fragment, plans to commit the transaction.
}
Fragment2 fr2 = new Fragment2();//Created object Fragment2
fr2.show(manager, "AddCity");//Display the dialog box by adding the fragment to the given FragmentManager.
}
EDIT:
This is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button b1, b2;
static int itemSelected;
static boolean isSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button1);
b2 = findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FragmentManager manager = getSupportFragmentManager();//
Fragment fr = manager.findFragmentByTag("addCity");
Fragment1 fr1 = (Fragment1)
getSupportFragmentManager().findFragmentById(R.id.list);
if (view.equals(b1)) {
if (fr != null) {
manager.beginTransaction().remove(fr).commit();
}
Fragment2 fr2 = new Fragment2();
fr2.show(manager, "");
}
if (view.equals(b2)) {
if (!fr1.cities.isEmpty()) {
if (isSelected) {
fr1.cities.remove(itemSelected);
fr1.adapter.notifyDataSetChanged();
itemSelected = 0;
isSelected = false;
fr1.getListView()
.setSelector(android.R.color.transparent);
} else {
Toast.makeText(this, "Select city to be deleted",
Toast.LENGTH_LONG).show();
}
}
}
}
}
Fragment1:
public class Fragment1 extends ListFragment {
ArrayList<String> cities = new ArrayList<>();
ArrayAdapter<String> adapter;
String name;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1,
viewGroup, false);
adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, cities);
setListAdapter(adapter);
return view;
}
public void onListItemClick(ListView listView, View view,
int position, long id) {
MainActivity.itemSelected = position;
MainActivity.isSelected = true;
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
Fragment2:
public class Fragment2 extends DialogFragment {
EditText et;
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment2, viewGroup, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
et = view.findViewById(R.id.editText);
Button b = view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String country = et.getText().toString();
Fragment1 fr1 = (Fragment1)
getFragmentManager().findFragmentById(R.id.list);
if (!country.equals("")) {
fr1.cities.add(country);
fr1.adapter.notifyDataSetChanged();
}
getActivity().getSupportFragmentManager().beginTransaction()
.remove(Fragment2.this).commit();
}
});
}
}
You are adding another fragment in the same name. Can you try changing the name to something else and try?
Like
fr2.show(manager, "Add District");
so that you can find the difference.
Adding a fragment
Fragment fr2 = new Fragment();
FragmentManager manger = getSupportFragmentManager();
FragmentTransaction ft = manger.beginTransaction();
ft.add(R.id.placeHolder, fr2,tag);
ft.commitAllowingStateLoss();
if(fr2.isAdded()){
fr2.show(manager, "");
}
Before calling show, you have to add the fragment.

android value passing from fragment to fragment using recyclerview not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am developing an app i want to pass value from one fragment to another fragment. Here i am using Recyclerview Adapter. My code is shown below.
FriendsFragment.java
public class FriendsFragment extends android.support.v4.app.Fragment {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://192.168.43.7/work/ecom/2/1.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
String JSON_IMAGE_ID = "id";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
// Inflate the layout for this fragment
return rootView;
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("LOGTAG", "Response :"+response);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setImageId(json.getString(JSON_IMAGE_ID));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static String categoryId;
Context context;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
private final View.OnClickListener mOnClickListener = new MyOnClickListener();
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
v.setOnClickListener(mOnClickListener);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView imageid;
public NetworkImageView networkImageView ;
public CardView cardView ;
public ViewHolder(final View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1);
cardView = (CardView) itemView.findViewById(R.id.cardview1);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
MessagesFragment fragobj=new MessagesFragment();
fragobj.setArguments(bundle);
}
});
}
}
private class MyOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
GetDataAdapter getDataAdapter = new GetDataAdapter();
TextView textView = (TextView) v.findViewById(R.id.textView_item) ;
}
}
}
GetAdapter.java
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String ImageId;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
public String getImageId() {
return ImageId;
}
public void setImageId(String ImageId) {
this.ImageId = ImageId;
}
}
SampleHolder.java
public class SampleHolder extends RecyclerView.ViewHolder {
public SampleHolder(View itemView) {
super(itemView);
}
}
when i using
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
//set Fragmentclass Arguments
MessagesFragment fragobj=new MessagesFragment();
fragobj.setArguments(bundle);
it is not passing value to message fragment or not going to message fragment.
How it possible plese help me.
try this in your Adapter class:
//in On click
MessagesFragment fragobj=new MessagesFragment();
Bundle bundle=new Bundle()
bundle.putString("message", "From Activity");
fragobj.setArguments(mBundle);
switchFragment(R.id.container, fragobj); //replace container ID
public void switchFragment(int id, Fragment fragment) {
if (context == null)
return;
//MainActivity is your activity where FriendsFragment is called
if (context instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) context;
mainActivity.loadFragment(id, fragment);
}
}
now in your activity write this code:
public void loadFragment(int id, Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(id, fragment, fragment.toString());
ft.addToBackStack(null);
ft.commit();
}
You should create a FragmentTransaction and then commit() the transaction to go to any fragment
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
//set Fragmentclass Arguments
MessagesFragment fragobj=new MessagesFragment();
fragobj.setArguments(bundle);
context.getSupportFragmentManager()//context should be an Activity cotext
.beginTransaction()
.replace(R.id.container, fragObj)//R.id.container is id of container where the current fragment is added
.commit();

Passing results (serializable class) from DialogFragment to Fragment

I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}

Custom listview and Sherlock List Fragment

In my application I'm trying to make navigation between pages by Dropdown navigation menu, but when i'm running the application there is no items in my list
Main Activity
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
//----------------------------------New Variables
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
//----------------------------------
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>(act.getThemedContext(),
android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText( "http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf
/Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
downloadservice.addandstart(value);
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
return false;
}
Custom adapter and SherlockFragmentList
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
//private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
// this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.downloads.get(position).getName());
progressbar.setBottom(downloadservice.downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
Anyone can tell me how to implement my list right and where is my mistake ?
thx a lot
Don't set the layout from your fragment big no no!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActivity().setContentView(R.layout.downloadlist); // Never do this!
// Also this will do nothing remove this! This should be in your `onActivityCreated()`
// setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
Don't override onCreateView in your Fragment, SherlockListFragment creates the ListView layout for you.
If you want to set the adapter, remove your onCreateView and set you adapter in onActivityCreated()
#Override
public void onActivityCreated(Bundle saveState){
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
Setting your setListAdapter(listadapter ); in your Adapter getView is wrong too. If you update your List<?> of data make sure you call notifyDataSetChanged() from the mainThread after you update the list.
Otherwise make sure you layout has a ListView with android:id="#android:id/list" defined otherwise SherlockListView won't have a view to set the adapter too.

Categories