Assign id to new item in listView - android

This is my activity where it contains listView and an action bar icon.
Everytime the app run, it will go through this method to load the SQLite data to listView.
public void retrieveList(String name) {
database = mdb.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + MyDatabaseHelper.TABLE__TASK + " WHERE Name = ? ", new String[]{name}, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int iD = cursor.getInt(cursor.getColumnIndex("ID"));
String month = cursor.getString(cursor.getColumnIndex("Month"));
double budget = cursor.getDouble(cursor.getColumnIndex("Budget"));
double totalUsed = cursor.getDouble(cursor.getColumnIndex("Total_Used"));
if (adapter != null) {
adapter.add(iD, month, budget, totalUsed);
listview.setAdapter(adapter);
}
}
}
}
The action bar icon (pen) will open a new dialog. Once the save button clicked, it will add new item to listView.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
mClickedPosition = -1;
final AlertDialog.Builder builder = new AlertDialog.Builder(AddMonthlyExpenses.this);
View promptView = getLayoutInflater().inflate(R.layout.dialog_in_addmonthlyexpenses, null);
save = (Button) promptView.findViewById(R.id.okBtn);
month = (EditText) promptView.findViewById(R.id.month);
budget = (EditText) promptView.findViewById(R.id.budget);
alert = builder.create();
alert.setTitle("Add Month ");
alert.setView(promptView);
alert.show();
month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog(DATE_DIALOG_ID);
}
});
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String month1 = month.getText().toString();
double budget1 = Double.parseDouble(budget.getText().toString());
if ((month1.trim().equals("")) || (String.valueOf(budget1).trim().equals(""))) {
Toast.makeText(getApplicationContext(), " Not Completed", Toast.LENGTH_SHORT).show();
} else {
adapter.add(id,month1, budget1);
Toast.makeText(getApplication(),id+"",Toast.LENGTH_SHORT).show(); // display 0
insert(name, month1, budget1);
listview.setAdapter(adapter);
alert.dismiss();
//retrieveList(String name)
}
}
}
});
break;
ExpensesAdapter
public class ExpensesAdapter extends BaseAdapter {
private static ArrayList<List> search;
private LayoutInflater mInflater;
ListView listview;
Context context;
double used = 0;
public ExpensesAdapter(Context context, ArrayList<List> searchList, ListView listview) {
this.search=searchList;
this.listview=listview;
mInflater = LayoutInflater.from(context);
this.context= context;
}
public int getCount() {
return search.size();
}
public List getItem(int position) {
return search.get(position);
}
public long getItemId(int position) {
return 0;
}
public void removeItem(int position) {
search.remove(position);
this.notifyDataSetChanged();
}
public void add(int id,String month,double budget,double used)
{
List obj = new List(id,month,budget,used);
this.used=used;
obj.setID(id);
obj.setMonthYear(" " + month);
obj.setBudget(budget);
obj.setUsed(used);
search.add(obj);
this. notifyDataSetChanged();
}
public void add(int id,String month, double budget)
{
List obj = new List(id,month,budget);
obj.setMonthYear(" " + month);
obj.setID(id);
obj.setBudget(budget);
search.add(obj);
this. notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder =null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.expenses_adapter, null);
holder= new ViewHolder();
holder.monthAndYear = (TextView) convertView.findViewById(R.id.monthAndYear);
holder.budget = (TextView) convertView.findViewById(R.id.budget);
holder.amount=(TextView)convertView.findViewById(R.id.amount);
holder.progressBar=(ProgressBar)convertView.findViewById(R.id.downloadProgressBar);
holder.balance=(TextView)convertView.findViewById(R.id.balance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.monthAndYear.setText(search.get(position).getMonthAndYear());
holder.budget.setText("RM" + "" + search.get(position).getBudget());
holder.amount.setText("RM" + "" + search.get(position).getUsed());
holder.progressBar.setProgress((int) search.get(position).getUsed());
holder.progressBar.setMax((int) search.get(position).getBudget());
double a = search.get(position).getBudget();
double b = search.get(position).getUsed();
holder.balance.setText("RM"+""+String.format("%.2f", a-b));
return convertView;
}
static class ViewHolder {
TextView monthAndYear, budget,amount,balance;
ProgressBar progressBar;
}
}
Once the new item is added in listView and I press it, I get id= 0. If I exit the app and click again then only it shows the new id. Is there a way I can make new id assign to new list item instead of exit the app or call the retrieveList method after alert.dismiss(); ?

In your adapter your not setting the id to the obj
public void add(int id,String month,double budget,double used)
{
List obj = new List(id,month,budget,used);
this.used=used;
obj.setMonthYear(" " + month);
obj.setBudget(budget);
obj.setUsed(used);
//Add this line your adapter
obj.setID(id);
search.add(obj);
this. notifyDataSetChanged();
}
public void add(int id,String month, double budget)
{
List obj = new List(id,month,budget);
obj.setMonthYear(" " + month);
obj.setBudget(budget);
//Add this line your adapter
obj.setID(id);
search.add(obj);
this. notifyDataSetChanged();
}

Your getItemId() always returns 0. To match your getItem() try returning something like:
public long getItemId(int position) {
List l = getItem(positon);
return l.getId();
}
Then of course your List must have a getId() which returns a long.

I solved by using this method
change insert(name, month1, budget1); to long id= insert(name, month1, budget1); to get the latest id. Then modify code to this
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String month1 = month.getText().toString();
double budget1 = Double.parseDouble(budget.getText().toString());
if ((month1.trim().equals("")) || (String.valueOf(budget1).trim().equals(""))) {
Toast.makeText(getApplicationContext(), " Not Completed", Toast.LENGTH_SHORT).show();
} else {
long id=insert(name, month1, budget1);
adapter.add(id,month1, budget1);
listview.setAdapter(adapter);
alert.dismiss();
check();
}
}
}
});

Related

How to increment TextView value outside ListView when ListView button is clicked in Android

I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});

Android list view change text when row is deleted

I have a ListView, which has an hidden button which become visible on user long click on row.
If someone clicks this button, the row is deleted.
My rows are composed by transactions, and in the same Activity i got a TextView displaying the amount.
When I add a transaction, my text is changed and the budget updated. My problem is updating it when an user clicks the button and deletes a row.
here is my adapter class
public class HomePageListAdapter extends ArrayAdapter<TRANSAZIONE> {
ArrayList<TRANSAZIONE> transazioni;
public HomePageListAdapter(Context context, int textViewResourceId,
ArrayList<TRANSAZIONE> objects) {
super(context, textViewResourceId, objects);
transazioni = objects;
}
TRANSAZIONE transazione;
NumberFormat formatter = new DecimalFormat("#0.00");
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapter_home_page_list, null);
TextView tvDesc = (TextView) view.findViewById(R.id.tvDescription);
TextView tvAmou = (TextView) view.findViewById(R.id.tvAmount);
final Button btnElimina = (Button) view.findViewById(R.id.btnElimina);
transazione = transazioni.get(position);
String dText = transazione.getDescription();
String aText = "";
if(transazione.getAmount() != null) {
aText = formatter.format(transazione.getAmount()) + " €";
if (transazione.getAmount() > 0) {
tvAmou.setTextColor(Color.GREEN);
} else {
tvAmou.setTextColor(Color.RED);
}
}
tvDesc.setText(dText);
tvAmou.setText(aText);
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
btnElimina.setVisibility(View.VISIBLE);
return false;
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnElimina.getVisibility() == View.VISIBLE) {
btnElimina.setVisibility(View.GONE);
}
}
});
btnElimina.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new TRANSAZIONE().Delete(TRANSAZIONE.class, getContext(), "where id = '" + transazioni.get(position).getId() + "'");
Toast.makeText(getContext(), "Transazione eliminata.", Toast.LENGTH_SHORT).show();
transazioni.remove(position);
notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(getContext(), "Errore non gestito.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
It works properly, and I have no problems updating my layout.
** And this is the method which updates my TextView's text and calls the Adapter. It's in the Activity**
public void LoadTotal() throws Exception {
#SuppressWarnings("unchecked")
ArrayList<TRANSAZIONE> transazioni = (ArrayList<TRANSAZIONE>) new TRANSAZIONE().SelectAll(TRANSAZIONE.class, getContext(), "");
Double totale = Settings.getLimitAmount();
//prendo solo quelle del mese corrente
if (transazioni.size() > 0) {
int numeroAggiornamento = Settings.getResettingDay();
Calendar today = Calendar.getInstance();
Calendar transactionDate = Calendar.getInstance();
Calendar lastChangeDate = Calendar.getInstance();
lastChangeDate.set(Calendar.DAY_OF_MONTH, numeroAggiornamento);
if (today.get(Calendar.DAY_OF_MONTH) < numeroAggiornamento) {
lastChangeDate.add(Calendar.MONTH, -1);
}
for (TRANSAZIONE t : transazioni) {
transactionDate.setTime(t.getDate());
if (transactionDate.compareTo(lastChangeDate) == -1) {
transazioni.remove(t);
} else {
totale += t.getAmount();
}
}
}
if (transazioni.size() == 0) {
transazioni.add(new TRANSAZIONE("Nessuna transazione per il mese in corso.", null, null));
}
HomePageListAdapter adapter = new HomePageListAdapter(getContext(), R.layout.adapter_home_page_list, transazioni);
lvTransactions.setAdapter(adapter);
tvBudget.setText(formatter.format(totale));
}
My problem is the following:
When I delete a row, it disappears from the list, but I can't intercept this in my Activity.
I need someway to call the method LoadTotal() when my row is deleted.
Any help will be appreciated.
Thanks all and sorry for my not perfect English.
The cleanest way of doing it is by using a DataSetObserver.
Inside your activity you have this object:
private DataSetObserver adapterObserver = new DataSetObserver() {
#Override
public void onChanged(){
// here you call your method
LoadTotal();
}
}
and then you register/unreguster this observer during onResume/onPause
#Override
public void onResume(){
super.onResume();
LoadTotal(); // update with latest values
adapter.registerDataSetObserver(adapterObserver);
}
#Override
public void onPause(){
super.onPause();
adapter.unregisterDataSetObserver(adapterObserver);
}
edit: some debug info for the op.
here is the code for notifyDataSetChanged() from BaseAdapter
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
and then inside DataSetObservable is simply looping through the list of observers
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
That means there's very little to actually go wrong there. But it's important to understand what is happening. So my suggestion is to put a breakpoint on all the method calls: onPause, onResume, onChanged and the line you call notifyDataSetChanged. And run it with the debugger, so you can see what is being called when and find out why it's not working.
In your adapter class
public class HomePageListAdapter extends ArrayAdapter<TRANSAZIONE> {
Context context;
ArrayList<TRANSAZIONE> transazioni;
public HomePageListAdapter(Context context, int textViewResourceId,
ArrayList<TRANSAZIONE> objects) {
super(context, textViewResourceId, objects);
transazioni = objects;
this.context=context;
}
TRANSAZIONE transazione;
NumberFormat formatter = new DecimalFormat("#0.00");
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapter_home_page_list, null);
TextView tvDesc = (TextView) view.findViewById(R.id.tvDescription);
TextView tvAmou = (TextView) view.findViewById(R.id.tvAmount);
final Button btnElimina = (Button) view.findViewById(R.id.btnElimina);
transazione = transazioni.get(position);
String dText = transazione.getDescription();
String aText = "";
if(transazione.getAmount() != null) {
aText = formatter.format(transazione.getAmount()) + " €";
if (transazione.getAmount() > 0) {
tvAmou.setTextColor(Color.GREEN);
} else {
tvAmou.setTextColor(Color.RED);
}
}
tvDesc.setText(dText);
tvAmou.setText(aText);
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
btnElimina.setVisibility(View.VISIBLE);
return false;
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnElimina.getVisibility() == View.VISIBLE) {
btnElimina.setVisibility(View.GONE);
}
}
});
btnElimina.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new TRANSAZIONE().Delete(TRANSAZIONE.class, getContext(), "where id = '" + transazioni.get(position).getId() + "'");
Toast.makeText(getContext(), "Transazione eliminata.", Toast.LENGTH_SHORT).show();
transazioni.remove(position);
notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(getContext(), "Errore non gestito.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
You can call the method of your activity like
((YourActivityName)context).LoadTotal();

Display ListView of selected data to next Activity in textView

In ListView here i have all my contacts with check box. When i select 2 contacts from list and hit a button then selected list's value should be display in next activity. How can i do this?
Its my Activity class :
public class ContactListActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
ContanctAdapter objAdapter = new ContanctAdapter(ContactListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position, long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
And My Adapter Class to Hold Data is
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private LayoutInflater inflater = null;
public ContanctAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(row, null);
holder.tvname = (TextView) convertView.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) convertView.findViewById(R.id.tvphone);
holder.checkbox = (ImageView) convertView.findViewById(R.id.img_checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return convertView;
ContactBean objBean = items.get(position);
holder.checkbox.setSelected((objBean.getIsSelected() == 1) ? true : false);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo() && objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
holder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
items.get(position).isSelected = (v.isSelected()) ? 0 : 1;
notifyDataSetChanged();
}
});
return convertView;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
private ImageView checkbox;
}
}
There is multiple ways to achieve that :
Method 1:
Use static class setter and getter method:
create static class and set values from first activity and get value from second activity
Method 2:
Post your values through the intent
Method 3:
Use database to store data from one activity and get data from other activity
Method 4:
Use Shared preference
Example:
Post values using Intent like this
Post values in Shared preference
Another tutorial for Shared preference
Try this, It may Help you
Add this code in your onitemClicklistener Listview Page
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String TVNameitem = ((TextView) view.findViewById(R.id.tvname)).getText().toString();
String TVPhoneitem = ((TextView) view.findViewById(R.id.tvphone)).getText().toString();
Intent intent1 = new Intent(this,NextActivity.class);
intent1.putExtra("STRING_I_NEED_From_TVNAME", TVNameitem );
intent1.putExtra("STRING_I_NEED_From_TVPHONE",TVPhoneitem );
startActivity(intent1);
}
Add this code in your Nextactivty Oncreate for Getting Values, Then Show in Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find);
Bundle extras = getIntent().getExtras();
String VALUE_1= extras.getString("STRING_I_NEED_From_TVNAME");
String Value_2 =extras.getString("STRING_I_NEED_From_TVPHONE");
TextView Textview1=(TextView)findViewById(R.id.CompanyText);
Textview1.setText(VALUE_1+":"+Value_2);
}
Create getter and setter to share contact details.
public class GetContacts {
private String contactNumber;
private String contactName;
GetContacts(){}// constructor without parameter.
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
}
Now set contact values to the setters in GetContact class
create an instance of GetContact class in your first Activity.
GetContact getContact= new GetContact();
And Set Parameters.
getContact.setContactNumber(phoneNumber);
getContact.setContactName(name);
Now its time to get those values in second activity.
create an instance of GetContact class in your second Activity like you did before.
And Get Parameters, and display into TextView.
textView1.setText(getContact.getContactNumber(phoneNumber));
textView2.setText(getContact.getContactName(name));

App crashes on android 4.0+

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.

Delete view from ListView

i would like to know the best possible way do delete a TextView from ListView,
But i want to do it from Options Menu.
so i click "Delete Country" - it will wait untill i will tap a country than delete the tapped country.
i am new to programming. thanks in advance
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.omAddCountry:
Intent addCountryIntent = new Intent(MainActivity.this, AddCountryActivity.class);
startActivityForResult(addCountryIntent, 11);
break;
case R.id.omDeleteCountry:
break;
the ListView is using SQLite and it gets the first view from DB and the TextViews is added by an Vector from an adapter.
public class CountryAdapter extends BaseAdapter {
private Context mContext;
protected Vector<Country> mVector;
protected SQLiteDatabase mDb;
public void setmContext(Context mContext){
this.mContext = mContext;
}
public CountryAdapter(Context mContext){
this.mContext = mContext;
mVector = new Vector<Country>();
CountryOpenHelper helper = new CountryOpenHelper(mContext);
mDb = helper.getWritableDatabase();
Cursor cursor = mDb.rawQuery("SELECT * FROM COUNTRIES", null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
}
do {
Country country = new Country();
country.setmCountryIndex(cursor.getInt(0));
country.setmCountryName(cursor.getString(2));
country.setmCountryTextSize(cursor.getInt(1));
country.setmCountryColor(cursor.getInt(3));
mVector.add(country);
} while (cursor.moveToNext());
}
public Vector<Country> getmVector() {
return mVector;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mVector.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if(convertView == null){
tv = new TextView(mContext);
}else{
tv = (TextView) convertView;
}
tv.setText(mVector.get(position).getmCountryName());
tv.setTextColor(mVector.get(position).getmCountryColor());
tv.setTextSize(mVector.get(position).getmCountryTextSize());
return tv;
}
public void ChangeColor(int newcolor, String name) {
mDb.execSQL("update COUNTRIES set color = " + newcolor + " where name = '" + name + "' " );
}
public void addCountry(int mId, String myCountry, int myColorNum){
mDb.execSQL("insert into countries values(" + mId + " , ' " + myCountry+"' , "+ myColorNum + ")");
}
}
Make a global boolean:
boolean isDeleting = false;
then in onOptionsItemSelected(), do:
case R.id.omDeleteCountry:
isDeleting = true;
break;
And whereever you implement onListItemClick():
#Override
public void onListItemClick (ListView listView,View view, int pos, long id)
{
if (isDeleting){
yourCustomAdapter.delete(pos)
yourCustomAdapter.notifyDataSetChanged();
isDeleting = false;
}
else {
//do other stuff
}
}
You will have to make a delete() method in your adapter.

Categories

Resources