Search code examples
androidlistviewretrofitretrofit2switchcompat

SwitchCompat in ListView to make network call


I have SwitchCompat inside a listView item , I want this SwitchCompat State to be sent to my remote database every time i change it ON/OFF for the specific item, I tried to put this network call in the adapter but i got the Exception: NetworkOnMainThreadException

any help?

I am using Retrofit for the network call

My Adapter

Adapter.java

public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ExpensesHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ExpensesHolder();
        ...
        row.setTag(holder);

    } else {
        holder = (ExpensesHolder) row.getTag();
    }
    holder.switchExpenses.setTag(position);
    ...
    if (flag.equals("unselected")) {
        holder.switchExpenses.setChecked(false);

    } else {
        holder.switchExpenses.setChecked(true);

    }
    if (TextUtils.isEmpty(expName)) {
        // want to make network call here
        }




    return row;

}

Solution

  • Probably you're calling call.execute(), to avoid NetworkOnMainThreadException use call.enqueue(listener)