Answer the question
In order to leave comments, you need to log in
How to make setText in adapter?
There is a DialogFragment, in which, by means of an adapter, information from the database is displayed. I make a counter for the displayed information. Those. received a number from the base, changed the number with the help of + / - and saved it to the base. Everything is fine: output, change, save. The problem is displaying the number change when you press + or -. Those. something is wrong with setText, but I don't see what. I would appreciate any tips and ideas.
Dialog:
public class DialogGrading extends DialogFragment {
Cursor c = null;
private ArrayList<OneCoin_nom> arr_all_descriptions = new ArrayList<>();
private MyBaseAdapter_grading myBaseAdapter;
public static final String KEY_ID = "_id";
ListView listView;
String coinId;
private static final String TAG = "-=-=-=-";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
View v = inflater.inflate(R.layout.dialog_grading, container, false);
myBaseAdapter = new MyBaseAdapter_grading(arr_all_descriptions, getActivity());
return v;
}
@Override
public void onResume() {
super.onResume();
// подключаюсь к БД
final DatabaseHelper myDbHelper = new DatabaseHelper(getActivity());
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
// таблица БД (соответственно языку локализации)
final String TABLE_FULL = getResources().getString(R.string.db_table_name);
final String TABLE_GRADING = getResources().getString(R.string.db_table_grading);
// получаем id элемента
coinId = getArguments().getString("coin_id");
// получаем из БД только одну строку (по id элемента)
c = myDbHelper.myDataBase.rawQuery("SELECT * FROM " + TABLE_FULL + " NATURAL JOIN " + TABLE_GRADING + " WHERE " + KEY_ID + " = " + coinId + " Limit 1", null);
if (c.moveToFirst()) {
do {
// передаем из БД в адаптер
OneCoin_nom one_coin = new OneCoin_nom();
one_coin.setCoinID(c.getString(0)); // ID
one_coin.setGradingPRF(c.getString(25));
arr_all_descriptions.add(one_coin);
} while (c.moveToNext());
}
// инициализация View
listView = (ListView) getView().findViewById(R.id.grading_listview);
listView.setAdapter(myBaseAdapter);
}
// исключаем дублирование item list при нажатии back из другого activity
@Override
public void onStop() {
super.onStop();
arr_all_descriptions.clear();
}
@Override
public void onDestroy(){
super.onDestroy();
// закрываем подключение
c.close();
}
// перезапуск активности после закрытия диалога (для отображения произошедших изменений)
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
getActivity().recreate();
Log.d(TAG, "DialogGrading: onDismiss");
}
}
class MyBaseAdapter_grading extends BaseAdapter implements OnClickListener {
private ArrayList<OneCoin_nom> arr_nominals;
private Context ctx;
private LayoutInflater layoutInflater;
private static final String TAG = "-=-=-=- ";
private View my_view;
private TextView grading_PRF;
private TextView grading_BU;
MyBaseAdapter_grading(ArrayList<OneCoin_nom> arr_nominals, Context ctx) {
this.arr_nominals = arr_nominals;
this.ctx = ctx;
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return arr_nominals.size();
}
@Override
public Object getItem(int position) { return arr_nominals.get(position); }
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
my_view = convertView;
if (my_view == null){
my_view = layoutInflater.inflate(R.layout.list_item_grading, parent, false);
}
OneCoin_nom coin = get_one_coin_object(position);
// ID элемента
TextView coin_id = (TextView) my_view.findViewById(R.id.coin_id);
coin_id.setText(coin.getCoinID());
// значение PRF
grading_PRF = (TextView) my_view.findViewById(R.id.tv_prf);
grading_PRF.setText(coin.getGradingPRF());
my_view.findViewById(R.id.btn_prf_minus).setOnClickListener(this);
my_view.findViewById(R.id.btn_prf_plus).setOnClickListener(this);
return my_view;
}
private OneCoin_nom get_one_coin_object(int position){
return arr_nominals.get(position);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_prf_minus: {
CharSequence tz = qty_PRF.getText(); // объект "надпись", получаем содержание объекта
if (qty_PRF != null) {
int zm = Integer.valueOf(tz.toString()); // превращаем в число
if (zm > 0) { zm--; } // уменьшаем на 1 (минимальное значение = 0)
if (zm == 0) { Toast.makeText(ctx, R.string.grading_min, Toast.LENGTH_SHORT).show(); }
//превращаем в срочное значение и возвращаем к объекту "надпись"
qty_PRF.setText(String.valueOf(zm));
Log.d(TAG, "PRF = " + tz + " - 1 = " + zm);
}
}
break;
case R.id.btn_prf_plus: {
CharSequence tz = qty_PRF.getText(); // объект "надпись", получаем содержание объекта
if (qty_PRF != null) {
int zp = Integer.valueOf(tz.toString()); // превращаем в число
if (zp < 99) { zp++; } // увеличиваем на 1 (максимальный значение = 99)
if (zp > 98) { Toast.makeText(ctx, R.string.grading_max, Toast.LENGTH_SHORT).show(); }
// превращаем в срочное значение и возвращаем к объекту "надпись"
qty_PRF.setText(String.valueOf(zp));
Log.d(TAG, "PRF = " + tz + " + 1 = " + zp);
}
}
break;
}
}
}
Answer the question
In order to leave comments, you need to log in
I decided this:
add R.id.btn_prf_minus to case:
Intent intent = new Intent("counter-update");
intent.putExtra("PRF_p", zm);
LocalBroadcastManager.getInstance(ctx).sendBroadcast(intent);
Intent intent = new Intent("counter-update");
intent.putExtra("PRF_m", zp);
LocalBroadcastManager.getInstance(ctx).sendBroadcast(intent);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TextView qty_PRF = (TextView) listView.findViewById(R.id.tv_prf);
int new_PRF_p = intent.getIntExtra("PRF_p", 0);
int new_PRF_m = intent.getIntExtra("PRF_m", 0);
if (new_PRF_p != 0) { qty_PRF.setText(String.valueOf(new_PRF_p)); }
if (new_PRF_m != 0) { qty_PRF.setText(String.valueOf(new_PRF_m)); }
}
}, new IntentFilter("counter-update"));
If you are sure that the number changes and setText 100% is executed, but for some reason the value does not change, then you should pay attention to the initialization of the object, it is possible that your TextView does not refer to the element you are looking at at all.
I propose to make a Clear project.
Perhaps you once created the same object and soon deleted it, but it remained in the R file.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question