android spinner doesn't work. it selected nothing - java

I'm using a Spinner in a Fragment. When the activity is created, the spinner doesn't show anything. It has no item when I click on the spinner, but the items are shown correctly.
When I select on the item nothing happens even though I call a Toast message.
P.S. The items come from an ArrayList of String from a database.
This is the code of the fragment:
public class RegStudentFragment extends Fragment {
private Spinner uniSpinner;
private RegistrationStudent activity;
private ArrayList<String> listaUni;
private int pos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.regs_frag, container, false);
uniSpinner=(Spinner) view.findViewById(R.id.spinnerUni);
System.out.println("fvfebeer");
manageUSpinner();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (RegistrationStudent) activity;
}
#Override
public void onActivityCreated(Bundle savedInstancestate) {
super.onActivityCreated(savedInstancestate);
listaUni = new ArrayList<String>();
new RequestFtp().setParameters(activity, "univer.php", "spinnerUni", RegStudentFragment.this).execute();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, getListaUni());
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
uniSpinner.setAdapter(adapter);
uniSpinner.setPrompt("Seleziona tra le seguenti:");
}
private void manageUSpinner() {
uniSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(activity.getApplicationContext(),"you selected ",Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(activity.getApplicationContext(),"No select ",Toast.LENGTH_SHORT).show();
}
});
System.out.println("vvsvsvsvsvs");
}
public void numeroel(ArrayList<ObjDb> result) {
ObjDb res= result.get(0);
String str=res.get("num");
int num=Integer.parseInt(str);
//numUni=new String[num];
}
public void arrayU(ArrayList<ObjDb> result){
int i=0;
while(i<result.size()) {
ObjDb res = result.get(i);
String str=res.get("nome");
listaUni.add(str);
i++;
}
}
public ArrayList<String> getListaUni(){
return listaUni;
}
}

Related

Tasks list not getting updated in real time

EDIT: after running the same code in the MainActivity the public void handleDialogClose(DialogInterface dialog) worked and everything got updated. so now the main problem is why its not running in other fragment?
The only difference I see is that on MainActivity the code is running in protected void onCreate(Bundle savedInstanceState)
While on Assignment fragment its running in public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
My task list is not getting updated after adding a new task or updating an existing task unless I go from one fragment to another and then come back, but the delete task function does work and removes the task from the list without going to the other fragments.
Note: it did worked when the code was in MainActivity
I tried to log the public void handleDialogClose(DialogInterface dialog)
but it didn't worked, so I assume maybe that's why...
Here is the code from my fragment:
public class AssignmentFragment extends Fragment implements DialogCloseListener {
public static Context context;
private FragmentAssignmentBinding binding;
private FloatingActionButton fab;
private RecyclerView tasksRecyclerView;
private ToDoAdapter tasksAdapter;
private List<ToDoModel> taskList;
private DatabaseHandler db;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentAssignmentBinding.inflate(inflater, container, false);
View root = binding.getRoot();
AssignmentFragment.context = getContext();
db = new DatabaseHandler(getContext());
db.openDatabase();
taskList = new ArrayList<>();
tasksRecyclerView = root.findViewById(R.id.tasksRecyclerView);
tasksRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
tasksAdapter = new ToDoAdapter(db,this, null);
tasksRecyclerView.setAdapter(tasksAdapter);
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new RecyclerItemTouchHelper(tasksAdapter));
itemTouchHelper.attachToRecyclerView(tasksRecyclerView);
fab = root.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddNewTask.newInstance().show(getChildFragmentManager(), AddNewTask.TAG);
}
});
return root;
}
#Override
public void handleDialogClose(DialogInterface dialog){
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
tasksAdapter.notifyDataSetChanged();
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
Here is the code for Adding a new task:
Here I did tried to log the public void onDismiss(DialogInterface dialog) but its also not responding.
public class AddNewTask extends BottomSheetDialogFragment {
public static final String TAG = "ActionBottomDialog";
private EditText newTaskText;
private Button newTaskSaveButton;
private DatabaseHandler db;
public static AddNewTask newInstance(){
return new AddNewTask();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.DialogStyle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view =inflater.inflate(R.layout.new_task, container, false);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
newTaskText = getView().findViewById(R.id.newTaskText);
newTaskSaveButton = getView().findViewById(R.id.newTaskButton);
boolean isUpdate = false;
final Bundle bundle = getArguments();
if(bundle != null){
isUpdate = true;
String task = bundle.getString("task");
newTaskText.setText(task);
if(task.length()>0) {
newTaskSaveButton.setTextColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_dark));
}
}
db = new DatabaseHandler(getActivity());
db.openDatabase();
newTaskText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
if(s.toString().equals("")){
newTaskSaveButton.setEnabled(false);
newTaskSaveButton.setTextColor(Color.GRAY);
}
else{
newTaskSaveButton.setEnabled(true);
newTaskSaveButton.setTextColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_dark));
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
final boolean finalIsUpdate = isUpdate;
newTaskSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = newTaskText.getText().toString();
if(finalIsUpdate){
db.updateTask(bundle.getInt("id"), text);
}
else{
ToDoModel task = new ToDoModel();
task.setTask(text);
task.setStatus(0);
db.insertTask(task);
}
dismiss();
}
});
}
#Override
public void onDismiss(DialogInterface dialog){
Activity activity = getActivity();
if(activity instanceof DialogCloseListener){
((DialogCloseListener)activity).handleDialogClose(dialog);
}
}
}
When you add a new task, you should write the following code immediately after;
tasksAdapter.notifyDataSetChanged();
This code refreshes the database.

How to setOnClickListener in adapter using RecyclerView to display inside fragment

I cannot access the ID of the item to view it in ToastMessage, or even store it in the database (use Room DataBase)
I have tried but the message does not appear
I need the reference ID to use for database storage and complete the process for storing the shopping cart
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ItemViewHolder> {
private Context context;
private ArrayList<Items> arrayList;
private AdapterView.OnItemClickListener listener;
public itemAdapter(Context context, ArrayList<Items> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
holder.name.setText(arrayList.get(position).getItemName());
holder.desc.setText(arrayList.get(position).getItemDesc());
holder.price.setText(arrayList.get(position).getItemPrice());
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT);
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
TextView name, desc, price;
ImageView remove, add;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
desc = itemView.findViewById(R.id.tvDesc);
price = itemView.findViewById(R.id.tvPrice);
remove = itemView.findViewById(R.id.btnDelete);
add = itemView.findViewById(R.id.btnAdd);
}
}
}
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated( View view, Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Try the following instead
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT).show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT).show();
}
});
The static method makeText of Toast is used to create the Toast object and show() method on the Toast object is used to display the Toast

How can I pass a ArrayList<String> created in a fragment to the main activity

I have a drawer menu with 3 items (Restaurant, Movie, Food). They are basically 3 to do lists. Each list has its on fragment and in the view there is a way to add items to the list.
The restaurant list, the movie list ad the groceries list.
I need to be able to share that list (via any share-channel) by clicking the share icon that is in the toolbar.
This is my fragment where i populate the items list that i want to use when i click the share icon that is on the toolbar. Basically i need to pass "items" to the MainActivity and use it.
package com.example.mylists;
import android.content.Intent;
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "FoodFragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onCreateView ");
View view = inflater.inflate(R.layout.fragment_food, container, false);
lvItems = (ListView) view.findViewById(R.id.lvItems);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(view.getContext(),android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
if (items.isEmpty())
items.add("Dummy Item");
final EditText newTask = (EditText) view.findViewById(R.id.etNewItem);
Button btnAdd = (Button) view.findViewById(R.id.btnAddItem);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemText = newTask.getText().toString();
itemsAdapter.add(itemText);
newTask.setText("");
writeItems();
Log.i(TAG, "in on send data ");
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onViewCreated ");
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "in on onActivityCreated ");
super.onActivityCreated(savedInstanceState);
OnItemLongClickListener listener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
//Log.i(TAG, "in on onItemLongClick ");
//Toast.makeText( getActivity().getBaseContext() , "Long Clicked " , Toast.LENGTH_SHORT).show();
items.remove(position);
itemsAdapter.notifyDataSetChanged();
writeItems();
//return true;
return false;
}
};
lvItems.setOnItemLongClickListener(listener);
}
private void readItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should declare ArrayList<String> items in your MainActivity. Then create a public setter method for items.
public void setItems(ArrayList<String> items){
this.items = items;
}
Then you should call setItems() method in your fragment.
((MainActivity) getActivity()).setItems(items);
Interface for Callback
interface MyInterface {
void setItems(ArrayList<String> items);
}
In your activity:
class MyActivity {
ArrayList<String> items;
MyInterface itemsCallback = new MyInterface(){
#Override
void setItems(ArrayList<String> items){
this.items = items;
}
}
myFragment.setItemsCallback(itemsCallback);
}
And then in fragment
class MyFragment {
private MyInterface itemsCallback;
public void setItemsCallback(MyInterface itemsCallback){
this.itemsCallback = itemsCallback;
}
private void readItems(){
...
itemsCallback.setItems(items);
}
}
I guess it's better then public setter in MainActivity. Because, you know, it's like more SOLID code. In this case your Fragment doesnt hold reference to Activity and doesnt even know about it existence.
1.Define an interface , 2.Let your Activity implements the interface 3.use (interface)getActivity() to cast your Activity to that interface,then you can call the method in the interface to send your ArrayList "items"

How to implement text counter inside firestore recyclerview

I'm trying to implement text counter where an integer will be incremented and decremented inside each firestore RecyclerView item for example 0 to 100. I've tried taking an int[] and Button onClick. I did holder.tvqty.setText(String.valueOf(a[position]++));. Here on Button click, all TextViews are successfully incremented with individual items. But the main problem is that when I click on first item button if the first position is the same, it's actually also incrementing last position i.e, in short, the first and last RecyclerView items are getting incremented together however rest of the items are working without any problem.
Please help me debug this any help will be appreciated.
This is my java class:
public class OrderItemFragment extends Fragment{
Context context;
int i=0;
// private List<Ex> exlist;
RecyclerView recyclerView;
FirebaseFirestore db;
FirestoreRecyclerAdapter adapter;
ArrayList<String> list = new ArrayList<String>();
int [] a;
public static OrderItemFragment newInstance() {
OrderItemFragment fragment = new OrderItemFragment();
return fragment;
}
public OrderItemFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orderitem, container, false);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recorder);
recyclerView.setLayoutManager(layoutManager);
initializeData();
//initializeAdapter();
db=FirebaseFirestore.getInstance();
return view;
}
private void initializeData()
{
db=FirebaseFirestore.getInstance();
Query query = db.collection("Items");
FirestoreRecyclerOptions<FriendsResponse> response = new FirestoreRecyclerOptions.Builder<FriendsResponse>()
.setQuery(query, FriendsResponse.class)
.build();
adapter = new FirestoreRecyclerAdapter<FriendsResponse, FriendsHolder>(response) {
#Override
public void onBindViewHolder(FriendsHolder holder, int position, FriendsResponse model) {
/* for (int i=0;i < ids.size();i++)
{
holder.exname.setText(ids.get(i));
}*/
//Toast.makeText(getContext(),String.valueOf(getItemCount()),Toast.LENGTH_LONG).show();
// String id = getSnapshots().getSnapshot(position).getId();
String id = getSnapshots().getSnapshot(position).getId();
for (i=0;i<getSnapshots().size();i++) {
list.add(getSnapshots().getSnapshot(position).getId());
}
a= new int [list.size()];
holder.exname.setText(id);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.tvqty.setText(String.valueOf(a[position]++));
}
});
holder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public FriendsHolder onCreateViewHolder(ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.menu_item, group, false);
return new FriendsHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView exname,tvqty;
ImageView add,remove;
public FriendsHolder(View itemView) {
super(itemView);
exname= itemView.findViewById(R.id.menuname);
add=itemView.findViewById(R.id.additem);
remove=itemView.findViewById(R.id.removeitem);
tvqty=itemView.findViewById(R.id.tvqty);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
/*
public class Ex {
String name;
int logoId;
int count=0;
Ex(String name, int logoId) {
this.name = name;
this.logoId = logoId;
}
}
*/
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
In this line of code holder.tvqty.setText(String.valueOf(a[position]++)), does a[position]++ the job ? Try to store the value of a[position] in a integer,and after that set it to tvqty.
int current_value = a[position];
and then
holder.tvqty.setText(String.valueOf((current_value++)));

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