Ive got a Array List in my CustomAdapter filled with the id of my checked element.
elementChecker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (elementChecker.isChecked()) {
checkedElements.add(id);
} else {
for (int i = 0; i < checkedElements.size() ; i++){
checkedElements.remove(id);
}
}
}
});
But how do I get access to this list from my Fragment?Thanks for your help.
EDIT: This is my getter But I cant call it from my Fragment.
public List<String> getSelectedElements(){
return checkedElements;
}
The Adapter is set in my DataListFragment:
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
EDIT2: Added The Fragment Code
public class ListViewFragment extends Fragment {
DbHelper mydb;
Spinner locationpicker;
LinearLayout qrStickerLayout;
ImageView qrCodeSticker;
TextView labelSticker;
TextView serialSticker;
private EditText roomnr;
public boolean roomNrOk = false;
public boolean locationOk = false;
public boolean listViewOk = false;
String actualLocation;
String dataList = "";
String selectedFromList;
String[] selectedElementArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
getActivity().setTitle(getString(R.string.listView));
registerForContextMenu(view);
final Context context = getContext();
mydb = new DbHelper(context);
locationpicker = (Spinner) view.findViewById(R.id.spinner_locations);
roomnr = (EditText) view.findViewById(R.id.editText_roomNr);
qrCodeSticker = (ImageView) view.findViewById(R.id.imageView_qrcode);
labelSticker = (TextView) view.findViewById(R.id.textView_QrSticker_label);
serialSticker = (TextView) view.findViewById(R.id.textView_QrSticker_serial);
qrStickerLayout = (LinearLayout) view.findViewById(R.id.linearLayout_QrCode);
Drawable drawableForFabSave = getResources().getDrawable(R.drawable.ic_save);
((MainActivity) getActivity()).fabsave.setImageDrawable(drawableForFabSave);
Drawable drawableForFabAdd = getResources().getDrawable(R.drawable.ic_add);
((MainActivity) getActivity()).fabmain.setImageDrawable(drawableForFabAdd);
((MainActivity) getActivity()).fabmain.animate().translationY(0);
((MainActivity) getActivity()).fabmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).scanQRCode();
((MainActivity) getActivity()).loadListViewFragment();
}
});
((MainActivity) getActivity()).fabdelete.animate().translationY(0);
final String locationNamesFromTableArray = mydb.getLocationNames();
if(!locationNamesFromTableArray.isEmpty()){
String[] roomNumbersFromTableArrayFinal = locationNamesFromTableArray.split("\t");
ArrayAdapter<String> adapter_locations;
adapter_locations = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, roomNumbersFromTableArrayFinal);
locationpicker.setAdapter(adapter_locations);
setFabdeleteVisible(listViewOk);
}
locationpicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
actualLocation = locationpicker.getSelectedItem().toString();
locationOk = true;
setFabsVisible(roomNrOk, true, listViewOk);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
roomnr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
Pattern p = Pattern.compile("^[0-9]{3}$");
Matcher m = p.matcher(s);
roomNrOk = m.find();
setFabsVisible(roomNrOk, locationOk, listViewOk);
}
});
dataList = mydb.getElementsWithoutRoom();
if (!dataList.isEmpty()) {
final String[] dataListArray = dataList.split("\n");
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
dataListListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedFromList = (dataListListView.getItemAtPosition(position).toString());
selectedElementArray = selectedFromList.split("\t");
dataListListView.showContextMenu();
}
});
((MainActivity) getActivity()).fabdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb.deleteAllWithoutRoom();
listViewOk = false;
dataListListView.setAdapter(dataListAdapter);
Toast toast = Toast.makeText(context, getResources().getString(R.string.toast_deleted), Toast.LENGTH_SHORT);
toast.show();
reloadListViewFragment();
}
});
}else{
TextView emptyElement = (TextView) view.findViewById(R.id.emptyElement);
emptyElement.setVisibility(View.VISIBLE);
}
((MainActivity) getActivity()).fabsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (roomNrOk && locationOk && !dataList.isEmpty()) {
String successfullSaved = getResources().getString(R.string.successfully)+ actualLocation + "-" + roomnr.getText().toString() + getResources().getString(R.string.saved);
mydb.setRoomNr(roomnr.getText().toString());
mydb.setRoomId(roomnr.getText().toString());
mydb.setLocationId(actualLocation);
Toast toast = Toast.makeText(getActivity(), successfullSaved, Toast.LENGTH_SHORT);
toast.show();
reloadListViewFragment();
} else {
Toast toast = Toast.makeText(getActivity(), getString(R.string.error_listView), Toast.LENGTH_SHORT);
toast.show();
}
}
});
((MainActivity) getActivity()).fabexport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File myDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + getResources().getString(R.string.sdcard_path));
if (!myDir.exists()) {
myDir.mkdir();
}
String fileName = getResources().getString(R.string.roomname) + actualLocation + getResources().getString(R.string.underline) + roomnr.getText().toString() + getResources().getString(R.string.roomname_ending);
File file = new File(myDir, fileName);
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter fos = new OutputStreamWriter(fOut);
fos.write(dataList);
fos.close();
fOut.close();
Toast toast = Toast.makeText(getActivity(), fileName + getResources().getString(R.string.saved), Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return view;
}
public void reloadListViewFragment(){
Fragment fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment = new ListViewFragment();
ft.replace(R.id.container, fragment);
ft.commitAllowingStateLoss();
}
}
OK. I got that, the issue is because the dataListAdapter is of type ListAdapter where you are initializing with CustomListAdapter. So, it gave you the error Cannot resolve method. To resolve this you can do it two ways:-
You can change this line
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
to
final CustomListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
While accessing the getSelectedElements(), write like this
((CustomListAdapter)dataListAdapter).getSelectedElements();
Please check with the current answer and let me know for further.
Related
I have a code that calls a fragment as an activity. From that fragment I select a data then give it back to the activity caller and here is my code.
Heres how I open the dialog
fragment_customer_list dialog = new fragment_customer_list();
dialog.show(getFragmentManager(),"CustomerList");
And here is how I return the value
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
add callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
}
});
I will call a function from the activity that calls the dialog to update the edittext.
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
The problem is the dialog is fixed in one activity. My question is how can I return the data from the activity caller? Since this fragment will be used by many activity
============================updated=============================
Here is how I open my fragment and i open it as a dialog
/* Open Customer List */
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
show_customer_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment_customer_list dialog = new fragment_customer_list();
dialog.setOnClickItemListener(new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
dialog.show(getFragmentManager(),"CustomerList");
}
});
And here is the whole code fragment_customer_list
public class fragment_customer_list extends DialogFragment {
private static final String TAG = "CustomerList";
DatabaseHelper myDb;
String pattern_email;
SimpleAdapter adapter;
private DialogInterface.OnClickListener listener;
private OnClickItemListener mListener;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
final ListView listView = (ListView) view.findViewById(R.id.customer_list);
myDb = new DatabaseHelper(getActivity());
pattern_email = credentials.email;
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer(pattern_email);
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
// add_activity callingActivity = (add_activity ) getActivity();
// callingActivity.onUserSelectValue(customer_name, customer_address);
if (mListener != null) {
mListener.value(customer_name, customer_address);
}
getDialog().dismiss();
}
});
android.widget.Button clickButton = (android.widget.Button) view.findViewById(R.id.close);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
}
});
/* Search customer */
EditText customer_search = (EditText) view.findViewById(R.id.search_customer);
customer_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer_search(cs.toString(),pattern_email);
if (data.getCount() == 0) {
//Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), R.style.WideDialog);
}
public void setOnClickItemListener(OnClickItemListener l) {
mListener = l;
}
interface OnClickItemListener {
void value(String name, String address);
}
}
As you can see on the code above there is Listview that has a code that same as this
add_activity callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
The code above will get the value from listview and call the onUserSelectValue from add_activity then close the dialog
and this is onUserSelectValue and it is located at add_activity
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
Here is my question.
How can I return the value of the listview to the textfield of the activity who opens the fragment(where the list view is located).
UPDATED CODE
I created a class called DialogHelper.java and this is the code
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
}
fragment_customer_list dialog = wr.get();
dialog.OnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null) return;
wr.get().dismiss();
}
}
In my customer_fragment_list.java I have a listview listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
TextView position3 = (TextView) view.findViewById(R.id.list_code);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
String customer_code = position3.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address,customer_code );
}
}
});
together with this
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address,String KUNNR);
}
public interface OnClickItemListener { void value(String name, String address, String code); }
and on my Activity this the code on how i open the dialog
/* Open Customer List */
DialogHelper.userSelectValue(add_covplan.this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(name);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(address);
}
});
you can do this. Don't know if you mean this?
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
private static WeakReference<Activity> wrActivity;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null || wrActivity == null || wrActivity.get() == null || wrActivity.get() != context) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
wrActivity = new WeakReference<>(context);
}
fragment_customer_list dialog = wr.get();
dialog.setOnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null || !wr.get().isShowing()) return;
wr.get().dismiss();
}
}
use
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
DialogHelper.userSelectValue(this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
edit answer
// Suppose this is a FragmentDialog
public class FragmentList {
private OnClickListener listener;
private ListView listView;
// Suppose this has your list listener
public void onResume() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address);
}
}
});
}
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address);
}
}
// Suppose this is a Activity
class YourActivity extends Activity
{
private FragmentList fragmentList;
EditText customer_address;
EditText customer_name;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
fragmentList = new FragmentList();
customer_address = (EditText) findViewById(R.id.address);
customer_name = (EditText) findViewById(R.id.cusname);
fragmentList.setOnClickListener(new FragmentList.OnClickListener()
{
#Override
public void click(String name, String address)
{
// ...
customer_name.setText(name);
customer_address.setText(address);
}
});
}
}
You can use a ViewModel class implementation to share resources between Activity and Fragment. Share the single context across multiple usages of ViewModel, each sharing a the same ViewModel. It works with the observer and observable pattern and perfect for this use case. You can check details on how to implement it here
I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()
I have currently implemented a listview, which when you click an item opens a second activity. In the second activity I have another listview which i can add items to, but when i go back to the first list and click another item, all the items from the second list appear for this one as well.
Any ideas how to sort this out? Can post code if needed
Here is the code for the first activity:
public class MainActivity extends Activity {
private ArrayList<String> entries;
private ArrayAdapter<String> entriesAdapter;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createListView();
createListViewListener();
}
private void createListView() {
list = (ListView) findViewById(R.id.diaryListView);
entries = new ArrayList<>();
readEntries();
entriesAdapter = new CustomAdapter(this, entries);
list.setAdapter(entriesAdapter);
}
private void createListViewListener() {
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
entries.remove(position);
entriesAdapter.notifyDataSetChanged();
writeEntries();
return true;
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("entry", entries.get(position));
startActivity(intent);
}
});
}
public void addEntry(View v) {
EditText entryEditText = (EditText) findViewById(R.id.entryEditText);
String diaryText = entryEditText.getText().toString();
entriesAdapter.add(diaryText);
entryEditText.setText("");
writeEntries();
}
private void readEntries() {
File filesDir = getFilesDir();
File journalEntriesFile = new File(filesDir, "journalEntries.txt");
try {
entries = new ArrayList<>(FileUtils.readLines(journalEntriesFile));
} catch (IOException e) {
entries = new ArrayList<>();
}
}
/**
* Method to save a list of tasks
*/
private void writeEntries() {
File filesDir = getFilesDir();
File journalEntriesFile = new File(filesDir, "journalEntries.txt");
try {
FileUtils.writeLines(journalEntriesFile, entries);
} catch (IOException e) {
e.printStackTrace();
}
}
and the second:
public class SecondActivity extends Activity {
private String entryName;
private TextView entryTitle;
private ArrayList<String> entryTask;
private ArrayAdapter<String> entryTaskAdapter;
private ListView entryTaskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
displayEntryTitle();
createEntryTaskListView();
createEntryTaskListViewListener();
}
private void displayEntryTitle() {
entryTitle = (TextView) findViewById(R.id.entryTitle);
Intent intent = getIntent();
entryName = intent.getStringExtra("entry");
entryTitle.setText("" + entryName);
}
private void createEntryTaskListView() {
entryTaskList = (ListView) findViewById(R.id.entryTaskListView);
entryTask = new ArrayList<>();
readEntryTasks();
entryTaskAdapter = new CustomAdapter2(this, entryTask);
entryTaskList.setAdapter(entryTaskAdapter);
}
private void createEntryTaskListViewListener() {
entryTaskList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
entryTask.remove(position);
entryTaskAdapter.notifyDataSetChanged();
writeEntryTasks();
return true;
}
});
entryTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
View view2 = (LayoutInflater.from(SecondActivity.this)).inflate(R.layout.alert_dialog, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SecondActivity.this);
alertBuilder.setTitle("Edit Journal Task Entry");
alertBuilder.setView(view2);
final EditText editEntryTaskText = (EditText) view2.findViewById(R.id.editEntryTask);
alertBuilder.setCancelable(true).setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String editEntry = editEntryTaskText.getText().toString();
editEntryTaskText.setText("" + editEntry);
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
});
}
public void onAddEntryTask(View v) {
EditText editText = (EditText) findViewById(R.id.entryTaskEditText);
String entryTaskText = editText.getText().toString();
entryTaskAdapter.add(entryTaskText);
editText.setText("");
writeEntryTasks();
}
private void readEntryTasks() {
File filesDir = getFilesDir();
File taskEntriesFile = new File(filesDir, "taskEntries.txt");
try {
entryTask = new ArrayList<>(FileUtils.readLines(taskEntriesFile));
} catch (IOException e) {
entryTask = new ArrayList<>();
}
}
private void writeEntryTasks() {
File filesDir = getFilesDir();
File taskEntriesFile = new File(filesDir, "taskEntries.txt");
try {
FileUtils.writeLines(taskEntriesFile, entryTask);
} catch (IOException e) {
e.printStackTrace();
}
}
Without seeing how you get back to the first activity from the second activity I can only assume that ArrayList entrytask is getting inserted into ArrayList entries when you return so based on the limited information I have the best answer I can come up with is
private void createListView() {
list = (ListView) findViewById(R.id.diaryListView);
entries = new ArrayList<>();
list.setAdapter(null);
//ArrayList<String> entries = null;
readEntries();
entriesAdapter = new CustomAdapter(this, entries);
list.setAdapter(entriesAdapter);
}
i hope you guys can help me. it`s drivin me crazy find the solution...
i already read some question that similar with my problems, but none solved mine.
here`s the problems
1 have 2 activity...
first --> i have activity that contain a view pager which hold 3 tab fragment.
in this first activity i extends with fragmentActivity
and here the code
public class A_BonRokok_Add_Main_Paged extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Header", "Item", "Info"};
MainActivity main = new MainActivity();
FragmentManager manager;
FragmentTransaction transaction;
Dialog alert;
LayoutInflater li;
LinearLayout someLayout;
Button btnSave_dialog;
Button btnCancel_dialog;
public EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_bon_rokok_add_main_paged);
FragmentPagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
getActionBar().setDisplayHomeAsUpEnabled(true);
pager.setOffscreenPageLimit(3);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_print) {
Toast.makeText(this, "print", Toast.LENGTH_SHORT).show();
}
else if (item.getItemId() == R.id.edit_save) {
Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
}
else{
createDialogConfirm();
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
public void onBackPressed(){
createDialogConfirm();
}
public void createDialogConfirm(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert.show();
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(ChildFragmentPaged.POSITION_KEY, position);
return ChildFragmentPaged.newInstance(args);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
}
public static A_BonRokok_Add_Main_Paged newInstance() {
return new A_BonRokok_Add_Main_Paged();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.save_print, menu);
return super.onCreateOptionsMenu(menu);
}
}
the first activity manage the tab fragment using class which extends fragment...
here the code
public class ChildFragmentPaged extends Fragment {
public static final String POSITION_KEY = "FragmentPositionKey";
private int position;
View root;
static EditText txtDate, txtGudang;
static RadioGroup btnGroupGudang;
static RadioButton btnGudang1, btnGudang2;
static Button btnNewItem, btnNewItem_Cancel;
private database mySQLiteAdapter;
private A_BonRokok_Item_View view = new A_BonRokok_Item_View();
public ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
AdapterView<?> tempAdt;
int tempPos;
public EditText search;
public ArrayList<bonRokokPagedEntity> list;
public ListViewAdapter adapter;
private databasePaged databasePaged;
public static ChildFragmentPaged newInstance(Bundle args) {
ChildFragmentPaged fragment = new ChildFragmentPaged();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
position = getArguments().getInt(POSITION_KEY);
if(position == 0){
root = inflater.inflate(R.layout.t_bon_rokok_header_paged, container,false);
}if (position == 1) {
root = inflater.inflate(R.layout.t_bon_rokok_item_paged, container, false);
settingTabItem();
} else if (position == 2)
root = inflater.inflate(R.layout.t_bon_rokok_info_paged, container, false);
return root;
}
public void settingTabItem() {
listContent = (ListView) root.findViewById(R.id.vl_tab_paged);
btnNewItem = (Button) root.findViewById(R.id.btnNewItem_paged);
search = (EditText)root.findViewById(R.id.search_paged);
try{
databasePaged = new databasePaged(getActivity());
databasePaged.createDataBase();
}catch(IOException ioe){
throw new Error("Unable to craete database");
}
try{
databasePaged.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
btnNewItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(),A_BonRokok_Item_New_Paged.class);
startActivity(intent);
getActivity().finish();
}
});
list = databasePaged.Getvalue();
adapter = new ListViewAdapter(getActivity(), list);
listContent.setAdapter(adapter);
}
private void updateList() {
cursor.requery();
}
public void createMenu(){
final Cursor cursor = (Cursor) tempAdt.getItemAtPosition(tempPos);
final String header = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.d_global_edit_delete,null, false);
ListView lv = (ListView)contentView.findViewById(R.id.d_globalEditDelete_lvEditDelete);
TextView txtHeader = (TextView)contentView.findViewById(R.id.d_globalEditDelete_lblHeader);
Button btnCancel = (Button)contentView.findViewById(R.id.d_globalEditDelete_btnCancel);
txtHeader.setText(header);
ArrayList<String> tempData = new ArrayList<String>();
tempData.add("Edit");
tempData.add("Delete");
int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter tempAdapter = new ArrayAdapter<String>(getActivity(), layoutID, tempData);
lv.setAdapter(tempAdapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(contentView);
final AlertDialog alert = builder.create();
alert.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if (position == 0){ //Edit Data
passStringValue();
updateList();
Intent intent = new Intent(getActivity(),A_BonRokok_Item_View.class);
intent.putExtra("status", true);
startActivity(intent);
getActivity().finish();
}
else if (position == 1){ //Delete Data
final int item_id = cursor.getInt(cursor.getColumnIndex(database.KEY_ID));
mySQLiteAdapter.delete_byID(item_id);
updateList();
alert.cancel();
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
}
public void passStringValue(){
final String nama_Rokok = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
final String kode_Rokok = "102030";
final String pita_Cukai = cursor.getString(cursor.getColumnIndex(database.SPITACUKAI));
final String jumlah = cursor.getString(cursor.getColumnIndex(database.SJUMLAH));
view.Detail(nama_Rokok, kode_Rokok, pita_Cukai, jumlah);
}
}
and the second --> i have activity that contain an edittext.
here the code
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(contentView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
});
// txtSelop.setOnFocusChangeListener(focusSelopChange);
// txtBungkus.setOnFocusChangeListener(focusBungkusChange);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_save) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
} else {
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_print, menu);
MenuItem item = menu.findItem(R.id.edit_print);
item.setVisible(false);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
OnClickListener searchClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
createDialogSearch();
}
};
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> hm = (HashMap<String, String>)arg0.getAdapter().getItem(position);
autoCompleteBonRokok.setText(hm.get("kdRokok"));
txtNamaRokok.setText(hm.get("namaRokok"));
}
};
public void onBackPressed(){
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
OnFocusChangeListener focusBalChange = new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean isFocused) {
if(!isFocused){
if(txtBal.length()==0)
bal = 0;
else
bal = Integer.parseInt(txtBal.getText().toString());
splitValue();
}
}
};
public void saveToDatabase() {
}
private void updateList() {
cursor.requery();
}
public void createDialogSearch(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout)li.inflate(R.layout.d_bon_rokok_search_new_item, null);
DialogDummyAutoComplete[] modelItemsDialog;
final ListView lvDialog = (ListView)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_lvSearch);
modelItemsDialog = new DialogDummyAutoComplete[3];
modelItemsDialog [0] = new DialogDummyAutoComplete("1051200", "Supra need 12");
modelItemsDialog [1] = new DialogDummyAutoComplete("1051600", "Supra need 16");
modelItemsDialog [2] = new DialogDummyAutoComplete("1001200", "NY");
DialogAutoCompleteSearchRokok dialogAdapter = new DialogAutoCompleteSearchRokok(this, modelItemsDialog);
lvDialog.setAdapter(dialogAdapter);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.getWindow().getAttributes().height = LayoutParams.WRAP_CONTENT;
alert.show();
btnCancel = (Button)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
String selectedKdRokok = ((TextView)arg1.findViewById(R.id.kdRokok_dialog)).getText().toString();
String selectedNamaRokok = ((TextView)arg1.findViewById(R.id.namaRokok_dialog)).getText().toString();
autoCompleteBonRokok.setText(selectedKdRokok);
txtNamaRokok.setText(selectedNamaRokok);
alert.cancel();
}
});
}
public void splitValue(){
if (txtJumlah.length()==0)
txtJumlah.setText("0,000");
separated = txtJumlah.getText().toString().split(",");
first = separated[0];
second = separated[1];
first = Integer.toString(bal);
txtJumlah.setText(first + "," + second);
txtJumlah.clearFocus();
}
public void createDialogConfirm(){
LayoutInflater li = LayoutInflater.from(this);
LinearLayout someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
Button btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
Button btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.show();
}
}
My question is
how can i pass a value from second activity (contain edittext) to fragment in view pager, because everytime i try to insert using many way, java lang null pointer always become my nightmare...
please help me... thx you so much
Intent.putExtra("YourValueKey", datatobepassed);
on the other activity
Bundle extras = getIntent().getExtras();
if ( extras != null ){
extras.get("YourValueKey")
}
I have and android app that works on android 4.0 great, but it crashes on android 4.3 and 4.4. I get this from the logCat
01-11 14:40:27.669: E/ACRA(25835): ACRA caught a IllegalStateException exception for quran. Building report.
01-11 14:40:27.789: E/AndroidRuntime(25835): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131099688, class android.widget.ListView) with Adapter(class quran.functions.PlaylistAdapter)]
Here is my code:
public class Playlist extends FragmentActivity {
private ListView list;
private Button manager, downloadAll;
private TextView reciter;
public static PlaylistAdapter adapter;
private ArrayList<Songs> songs;
private int RECITER_ID;
private String url, title, label;
private SlidingMenu slidingMenu;
private DatabaseHelper db;
private ImageView nowPlaying, back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
initWidgets();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
intent.putExtra("songs", songs);
if (getIntent().getIntExtra("duaa", -1) == 115)
intent.putExtra("lang", 115);
intent.putExtra("position", position);
intent.putExtra("fromClass", this.getClass() + "");
// intent.putExtra("mp3link", mp3link);
startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
XmlMapParser m = new XmlMapParser(Playlist.this, RECITER_ID);
HashMap<String, ArrayList<String>> map = m.convert();
map.keySet();
label = map.get("RecitorLabel").get(0);
title = map.get("Title").get(0);
url = map.get("Link").get(0);
back = (ImageView) findViewById(R.id.playlist_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
db.openDB();
for (int i = 1; i < map.get("Link").size(); i++) {
if (db.isDownloaded(i, title, RECITER_ID)) {
songs.add(new Songs(i, map.get("Title").get(i),
Environment.getExternalStorageDirectory()
.getPath()
+ "/"
+ getString(R.string.app_name)
+ "/"
+ title
+ "/"
+ map.get("Title").get(i)
+ ".mp3", title, true, RECITER_ID,
false));
} else
songs.add(new Songs(i, map.get("Title").get(i), url
+ label + "/"
+ new DecimalFormat("000").format(i) + ".mp3",
title, false, RECITER_ID, false));
}
db.closeDB();
// Log.v("--",m.convert().get("Link").get(1));
// [RecitorLabel, Title, Link] THIS ARE THE KEYS m
// Log.v("--", map.get("RecitorLabel").get(0));
// Log.v("--", map.get("Link").get(1));
return null;
}
protected void onPostExecute(Void result) {
adapter = new PlaylistAdapter(Playlist.this, songs);
list.setAdapter(adapter);
reciter.setText(songs.get(0).getRecitorName());
};
}.execute();
}
#Override
public void onBackPressed() {
if (slidingMenu.isMenuShowing()) {
slidingMenu.toggle();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
try {
if (Tplayer.getInstance().isPlaying()) {
adapter = new PlaylistAdapter(this, songs);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
this.slidingMenu.toggle();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.slidingMenu.toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initWidgets() {
db = new DatabaseHelper(this);
manager = (Button) findViewById(R.id.playlist_download_manager);
manager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Playlist.this, DownloadManager.class);
startActivity(intent);
}
});
reciter = (TextView) findViewById(R.id.playlist_reciter_name_top);
list = (ListView) findViewById(R.id.playlist_list);
downloadAll = (Button) findViewById(R.id.playlist_download_all);
manager = (Button) findViewById(R.id.playlist_download_manager);
songs = new ArrayList<Songs>();
RECITER_ID = getIntent().getIntExtra("filename", -1);
// downloadAll.setOnClickListener(new OnClickListener() {
//
// #Override
// public void onClick(View v) {
// new DownloadAll(Playlist.this, songs);
// db.openDB();
// for (int i = 0; i < songs.size(); i++) {
// db.addDownloaded(songs.get(i).getNumber(), songs.get(i)
// .getLink(), 0, songs.get(i).getRecitorID(), "",
// songs.get(i).getTitle());
// }
// db.closeDB();
// }
// });
nowPlaying = (ImageView) findViewById(R.id.playlist_now_playing);
nowPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Tplayer tplayer = Tplayer.getInstance();
if (tplayer.isPlaying()) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
if (tplayer.isPlaying())
intent.putExtra("songs", tplayer.getSongs());
else
intent.putExtra("songs", songs);
if (tplayer.getSongs().size() == 14)
intent.putExtra("lang", 115);
intent.putExtra("position", tplayer.getPosition());
startActivity(intent);
}
}
});
// Jeremy Feinstein slidinglistadapter line 94
slidingMenu = new SlidingMenu(this);
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);
slidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);
slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
slidingMenu.setMenu(R.layout.slidingmenu);
}
}
and my playlist adapter class:
public class PlaylistAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
private ArrayList<Songs> data;
private DatabaseHelper db;
private SharedPreferences prefs;
int playpos;
int recitorID;
public PlaylistAdapter(Activity a, ArrayList<Songs> songs) {
activity = a;
data = songs;
db = new DatabaseHelper(a);
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
prefs = activity.getSharedPreferences("quantic.Quran",
Context.MODE_PRIVATE);
recitorID = prefs.getInt("recID", -1);
playpos = prefs.getInt("posPlaying", -1);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
final ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.song_item, parent, false);
ImageView download = (ImageView) vi
.findViewById(R.id.playlist_item_download);
db.openDB();
if (db.isDownloaded(data.get(position).getNumber(), data.get(position)
.getRecitorName(), data.get(position).getRecitorID()))
download.setImageResource(R.drawable.download_yes);
else {
download.setImageResource(R.drawable.download_no);
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DownloadFileFromURL(activity, data.get(position)
.getRecitorName(), data.get(position).getTitle(),
data.get(position).getLink(), data.get(position)
.getNumber(), data.get(position)
.getRecitorID()).execute();
if (!db.isDBOpen())
db.openDB();
db.addDownloaded(data.get(position).getNumber(),
data.get(position).getLink(), 0, data.get(position)
.getRecitorID(), "", data.get(position)
.getTitle());
Toast.makeText(activity,
"Downloading " + data.get(position).getTitle(),
Toast.LENGTH_SHORT).show();
}
});
}
db.closeDB();
TextView number = (TextView) vi.findViewById(R.id.playlist_item_num);
TextView reciterName = (TextView) vi
.findViewById(R.id.playlist_item_reciterName);
reciterName.setText(data.get(position).getRecitorName());
if (activity.getClass() == Playlist.class) {
reciterName.setVisibility(View.GONE);
}
TextView title = (TextView) vi.findViewById(R.id.playlist_item_reciter);
title.setText(data.get(position).getTitle());
number.setText((position + 1) + "");
ImageView eq = (ImageView) vi.findViewById(R.id.playlist_item_equlizer);
if (Tplayer.getInstance().isPlaying())
if (Tplayer.getInstance().getPosition() == position
&& data.get(position).getRecitorID() == Tplayer
.getInstance().getSong().getRecitorID()) {
eq.setVisibility(View.VISIBLE);
Ion.with(eq).load("http://darkodev.info/quran/dots.gif");
} else {
eq.setVisibility(View.GONE);
}
return vi;
}
}
Very old question, but no answer. I'm sure you have found a fix by now, but anyway.
You're changing the songs list object in background, and if Android decides to redraw your list (user scrolls your list), effectively accessing the songs list object, it may have changed and cause this exception to be thrown.
You need to use a temporary songs list and create a new adapter with it to update your list, thus not changing the current adapter list until you set a new adapter from the main UI thread.