How to get position of view created dynamically in main Linear Layout? - android

I am creating here a dynamic layout. I have one parent layout in which I am adding all the dynamic created views. Now on click of particular view I need position.
According to that position I have to send JsonObject which contain this view in Android. Here I am not able to get exact position of view.
This is my code:
int len = result.length();
View addView;
if (!(len == 0)) {
finalResult.clear();
for (int i = 0; i <= len; i++) {
try {
finalResult.add(result.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
if (i == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
image = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurl1 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl1, image,
Common.optionsSmall);
textview.setText(category1);
} else if (i % 5 == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
images = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurlss = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurlss, images,
Common.optionsSmall);
textview.setText(category1);
} else {
addView = mInflater.inflate(R.layout.sightseeing_secondview, null);
iv = (ImageView) addView.findViewById(R.id.secondimagesightseeing_second);
tv = (TextView) addView.findViewById(R.id.textView2);
llsecond = (LinearLayout) addView.findViewById(R.id.llsecondview);
String category2 = finalResult.get(i).getString("CategoryName");
imageurl2 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl2, iv,
Common.optionsSmall);
tv.setText(category2);
if (result.length() > i + 1) {
i++;
ivview = (ImageView) addView.findViewById(R.id.secondimagesightseeing_third);
text = (TextView) addView.findViewById(R.id.textView3);
llthird = (LinearLayout) addView.findViewById(R.id.llthirdview);
String category3 = finalResult.get(i).getString("CategoryName");
imageurl3 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl3, ivview,
Common.optionsSmall);
text.setText(category3);
}
llayout.addView(addView);
}
position = llayout.indexOfChild(addView);
addView.setTag(position);
addView.setOnClickListener(this);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
position = (Integer) v.getTag();
Toast.makeText(SightseeingToursActivity.this, "Position" + position, Toast.LENGTH_SHORT).show();
try {
Intent in = new Intent(SightseeingToursActivity.this, sightseeing_list.class);
in.putExtra("TourList", result.getJSONObject(position).toString());
startActivity(in);
} catch (Exception e) {
}
}

ViewGroup parent;
int position;
for(int i = 0; i < parent.getChildCount(); ++i) {
int currentViewId = parent.getChildAt(i).getId();
if(currentViewId == wantendViewId) {
position = i;
}
}
try this

Related

RecyclerViewAdapter removed fill content on scroll

i use RecyclerViewAdapter for my json adaper.i make some radiobutton and check box and edittext in RecyclerViewAdapter programically but when i check some radio button or type in edittext and scroll more than 1 screen when i come back all my fill content are removed;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
public MyRecyclerViewAdapter(Context context, ArrayList<HashMap<String, Object>> hash_all) {
}
#Override
public int getItemCount() {
return hash_all.size();
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
hash_all.size();
hash_get = hash_all.get(position);
LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(
LinearLayoutCompat.LayoutParams.MATCH_PARENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 0, 0, 0);
String s = hash_get.get("ModelShowOption").toString();
String toggle = "";
String direc = "";
String type = "";
String model = "";
String rows = "";
String resize = "";
String[] split = s.split("\\|");
String[] split2 = new String[0];
for (int i = 0; i < split.length; i++) {
String s2 = split[i];
split2 = s2.split(":");
if (split2[0].equals("isToggleButton")){
toggle=split2[1];
}else if (split2[0].equals("type")){
type=split2[1];
}else if (split2[0].equals("direction")){
direc=split2[1];
}else if (split2[0].equals("model")){
model=split2[1];
}else if (split2[0].equals("rows")){
rows=split2[1];
}else if (split2[0].equals("resize")){
resize=split2[1];
}
}
String title = hash_get.get("title").toString();
String myValue =hash_get.get("MyValue").toString();
String[] splitValue = myValue.split("\\|");
RadioGroup[] rg;
RadioButton[] rb;
if (toggle.equals("true") && holder.row_list_title.getText().equals("")){
holder.row_list_placeholder.setVisibility(View.GONE);
holder.row_list_buttn.setVisibility(View.GONE);
String multiValue = hash_get.get("MultiValue").toString();
String[] splitMultiValue = multiValue.split(":");
if (splitMultiValue[1].equals("1")){
int p = 0;
rg = new RadioGroup[1];
rb = new RadioButton[splitValue.length];
rg[0] = new RadioGroup(holder.row_list_placeholder.getContext());
rg[0].setOrientation(RadioGroup.VERTICAL);
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
rb[j] = new RadioButton(getApplicationContext());
rg[p].addView(rb[j]);
rb[j].setId(j);
rb[j].setText(splitValue2[0]);
}
holder.linearLayoutCheckBox.addView(rg[p]);
p++;
holder.row_list_title.setText(title);
if (rg[0].getCheckedRadioButtonId() == -1) {
} else {
for (int r = 0; r < splitValue.length; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
}
}
}
}else{
holder.row_list_title.setText(title);
CheckBox[] ch;
final int[] checkd = {0};
List<String> checkvl = new ArrayList<>();
ch = new CheckBox[splitValue.length];
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
ch[j] = new CheckBox(getApplicationContext());
holder.linearLayoutCheckBox.addView(ch[j]);
ch[j].setId(j);
ch[j].setText(splitValue2[0]);
}
for (int r = 0; r < splitValue.length; r++) {
int finalR = r;
int finalR1 = r;
ch[r].setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
if (checkd[0] < Integer.parseInt(splitMultiValue[1])){
//checkvl.add(ch[finalR1].getText().toString());
//hash_all_string.get(position).remove("value");
//hash_all_string.get(position).put("value", String.valueOf(checkvl));
//CheckBox id = findViewById(ch[finalR].getId());
//String CheckBoxText = id.getText().toString();
//Log.e("CheckBoxString", CheckBoxText);
checkd[0] = checkd[0] +1;
}else{
ch[finalR].setChecked(false);
}
} else {
ch[finalR].setChecked(false);
checkd[0] = checkd[0] -1;
//checkvl.remove(ch[finalR1].getText().toString());
//hash_all_string.get(position).remove("value");
//hash_all_string.get(position).put("value", String.valueOf(checkvl));
}
});
}
}
}else{
if (myValue.equals("NULL")){
holder.row_list_title.setText(title);
holder.row_list_placeholder.setVisibility(View.VISIBLE);
holder.row_list_buttn.setVisibility(View.GONE);
holder.row_list_placeholder.setHint(hash_get.get("placeholder").toString());
if (type.equals("Text")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_TEXT);
}else if(type.equals("Int")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER);
}else if(type.equals("Float")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}else {
holder.row_list_placeholder.setVisibility(View.GONE);
holder.row_list_buttn.setVisibility(View.VISIBLE);
holder.row_list_title.setText(title);
int selct = 0;
for (int j = 0; j < hash_all2.size(); j++) {
if (hash_all2.get(j).get("selected").equals("true")) {
selct = selct+1;
}
}
if (selct>0){
holder.row_list_buttn.setBackgroundColor(getResources().getColor(R.color.purple_500));
holder.row_list_buttn.setText("انتخاب شد");
}else{
holder.row_list_buttn.setText("انتخاب کنید");
holder.row_list_buttn.setBackgroundColor(getResources().getColor(R.color.teal_200));
}
String multiValue = hash_get.get("MultiValue").toString();
String[] splitMultiValue = multiValue.split(":");
holder.row_list_buttn.setOnClickListener(v -> {
if (hash_all2.size() == 0) {
for (int j = 0; j < splitValue.length; j++) {
HashMap<String, String> hash_add2 = new HashMap<>();
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
hash_add2.put("Id", String.valueOf(j));
hash_add2.put("name", String.valueOf(splitValue2[0]));
hash_add2.put("value", String.valueOf(splitValue2[1]));
hash_add2.put("selected", "false");
hash_add2.put("max", splitMultiValue[1]);
hash_all2.add(hash_add2);
}
adapt.notifyDataSetChanged();
}
alertDialogSelect(position);
});
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.row_form, parent, false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView row_list_title;
EditText row_list_placeholder;
LinearLayout linearLayoutCheckBox;
Button row_list_buttn;
ViewHolder(View itemView) {
super(itemView);
row_list_title = itemView.findViewById(R.id.row_list_title);
row_list_placeholder = itemView.findViewById(R.id.row_list_placeholder);
linearLayoutCheckBox = itemView.findViewById(R.id.mainrow);
row_list_buttn = itemView.findViewById(R.id.row_list_buttn);
}
}
}
please help.i tryed many code from stack but not working
holder.setIsRecyclable(false);
setHasStableIds(true);
this is not working for me
In RecyclerView when scrolling state of view removed and creating new view by scroll,
you must change your data when radioButton or edittext content changed, and set new data in your model.

what is the reason of java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 error in code?

i have this error in my code:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooshindroid.yastashir/com.nooshindroid.yastashir.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
in dess3 and dess 4 this error has accurred!
idon't know why .but the size of dess3 and dess 4 is 0!
Route class of this code is here:
public class Route extends Activity {
String diff;
Context context;
ArrayList<String> sources, destinations, destinations2,destinations3,destinations4, answer;
public static ArrayList<Models> routeItems;
public Route(Context context) {
this.context = context;
}
public Route(String part) {
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
Bundle bundle = getIntent().getExtras();
diff = bundle.getString("level");
InputStream in_s = this.context.getAssets().open(diff);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
parseXML(parser);
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseXML(XmlPullParser parser) throws XmlPullParserException, IOException
{
int eventType = parser.getEventType();
Models currentRout = null;
sources = new ArrayList<String>();
sources.clear();
destinations = new ArrayList<String>();
destinations.clear();
destinations2 = new ArrayList<String>();
destinations2.clear();
destinations3 = new ArrayList<String>();
destinations3.clear();
destinations4 = new ArrayList<String>();
destinations4.clear();
answer = new ArrayList<String>();
answer.clear();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
routeItems = new ArrayList<Models>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("route")) {
currentRout = new Models();
} else if (currentRout != null) {
if (name.equalsIgnoreCase("source")) {
currentRout.source = parser.nextText();
if ( !sources.contains(currentRout.source))
sources.add(currentRout.source);
} else if (name.equalsIgnoreCase("destination")) {
currentRout.destination = parser.nextText();
try {
//if ( !destinations.contains(currentRout.destination))
destinations.add(currentRout.destination);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination2 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations2.add(currentRout.destination2);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination3 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations3.add(currentRout.destination3);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination4 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations4.add(currentRout.destination4);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("answer")) {
currentRout.answer = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
answer.add(currentRout.answer);
}
catch (Exception ex)
{
}
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("route") && currentRout != null) {
routeItems.add(currentRout);
}
}
eventType = parser.next();
}
}
}
main activiy of my code is as bellow:
public class MainActivity extends Activity {
public int nextque;
ArrayList<String> sourcess;
ArrayList<String> dess;
ArrayList<String> dess2;
ArrayList<String> dess3;
ArrayList<String> dess4;
ArrayList<String> answer;
int randomInt;
Random random;
Button buttons[] = new Button[8];
String j[] = new String[3];
int sumscore1 = 0;
int sumscore2 = 0;
String diff;
ProgressBar mProgressBar, mProgressBar1;
int edtTimerValue;
TextView textViewShowTime;
CountDownTimer countDownTimer;
long totalTimeCountInMilliseconds;
public void nextque() {
if ((nextque) + 1 < sourcess.size()) {
nextque++;
}
}
private void setTimer() {
int time = 0;
time = edtTimerValue;
totalTimeCountInMilliseconds = time * 1000;
mProgressBar1.setMax(time * 1000);
}
public void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 1) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
mProgressBar1.setProgress((int) (leftTimeInMilliseconds));
textViewShowTime.setText(String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
buttons[7].setBackgroundResource(R.drawable.blank_button);
textViewShowTime.setText("10");
textViewShowTime.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar1.setVisibility(View.GONE);
nextStep();
}
}.start();
}
public void nextStep() {
textViewShowTime.setVisibility(View.VISIBLE);
equation1.setVisibility(View.VISIBLE);
equation2.setVisibility(View.VISIBLE);
setTimer();
mProgressBar.setVisibility(View.INVISIBLE);
startTimer();
mProgressBar1.setVisibility(View.VISIBLE);
if(sumscore1==100){
sumscore1=0;
sumscore2=0;
score1.setText(String.valueOf(sumscore1));
score2.setText(String.valueOf(sumscore2));
}
if (sumscore2==100){
sumscore1=0;
sumscore2=0;
score1.setText(String.valueOf(sumscore1));
score2.setText(String.valueOf(sumscore2));
}
random = new Random();
randomInt = random.nextInt(sourcess.size());
equation1.setText(sourcess.get(nextque));
equation2.setText(sourcess.get(nextque));
Random rn = new Random();
int index = rn.nextInt(3) + 0;
Log.e("rand poduct", String.valueOf(index));
nextque();
equation1 = (TextView) findViewById(R.id.equation1);
buttons[index].setText( answer.get(nextque));
dess.size();
int k = 0;
for (int i = 0; i <= 3; i++) {
Log.e("prod", "loop " + i);
if (i != index ) {
if(!(answer.get(nextque).equals(j[k]))){
buttons[i].setText((j[k]));
}
k++;
}
}
equation2 = (TextView) findViewById(R.id.equation2);
Random rt = new Random();
int index2 = rt.nextInt(3) + 0;
int index3 = index2 + 4;
buttons[index3].setText( answer.get(nextque));
int d = 0;
for (int i = 4; i <= 7; i++) {
if (i != index3) {
if(!(answer.get(nextque).equals(j[d]))){
buttons[i].setText((j[d]));
}
d++;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
equal1 = (TextView) findViewById(R.id.equal1);
equal2 = (TextView) findViewById(R.id.equal2);
bord1 = (TextView) findViewById(R.id.bord1);
bord2 = (TextView) findViewById(R.id.bord2);
bakht1 = (TextView) findViewById(R.id.bakht1);
bakht2 = (TextView) findViewById(R.id.bakht2);
refreash = (ImageView) findViewById(R.id.refreash);
textViewShowTime = (TextView) findViewById(R.id.textView_timerview_time);
edtTimerValue = 10;
mProgressBar = (ProgressBar) findViewById(R.id.progressbar_timerview);
mProgressBar1 = (ProgressBar) findViewById(R.id.progressbar1_timerview);
Bundle bundle = getIntent().getExtras();
Typeface font = Typeface.createFromAsset(getAssets(), "BYekan.ttf");
diff = bundle.getString("level");
textViewShowTime.setTypeface(font);
route = new Route(getApplicationContext());
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
InputStream in_s = getApplicationContext().getAssets().open("easys.xml");
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
route.parseXML(parser);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sourcess = new ArrayList<String>();
for (int i = 0; i < route.sources.size(); i++) {
sourcess.add(i, route.sources.get(i));
}
dess = new ArrayList<String>();
for (int i = 0; i < route.destinations.size(); i++) {
dess.add(i, route.destinations.get(i));
}
dess2 = new ArrayList<String>();
for (int i = 0; i < route.destinations2.size(); i++) {
dess2.add(i, route.destinations2.get(i));
}
dess3 = new ArrayList<String>();
for (int i = 0; i < route.destinations3.size(); i++) {
dess3.add(i, route.destinations3.get(i));
}
dess4 = new ArrayList<String>();
for (int i = 0; i < route.destinations4.size(); i++) {
dess4.add(i, route.destinations4.get(i));
}
answer = new ArrayList<String>();
for (int i = 0; i < route.answer.size(); i++) {
answer.add(i, route.answer.get(i));
}
nextStep();
}
}
can anyone help me to solve it?thank alot for your attention.
The array size of array j is 3. But when you are using it inside the loop, you are iterating it more than its size.. Try increasing the size of the arrays and check.
Along with the error you get the line number too of the error, post it if possible.

How to get Id of ChildView Items of ExpandableListView in Android

I'm using ExpandapbeListView its work perfect all expand and collapse but I just want to update only particular child item here when I click on plus value should be update in EditText and I don't want to use notifyDatasetChanged() Just want to update only particular field and also i should able to update EditText directly. It can have multiple child item.
Ex: Colgate may have multiple child Item like 100gm,200gm,300gm
So when I click on Plus It should able to get Id of EditText and Update Quantity
#Override
public View getChildView(int productPos, int weightPos, boolean b, View plusMinusView, ViewGroup viewGroup) {
if (plusMinusView == null) {
csHolder = new ChildHolder();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
plusMinusView = inflater.inflate(R.layout.orders_products_plus_minus_design, null);
}
csHolder.minQty = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitMinQtyTxt);
csHolder.totalPriceTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitTotalPriceTxt);
csHolder.weightTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitWeightTxt);
csHolder.unitPrice = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitUnitPriceTxt);
csHolder.totalTaxTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitTotalTaxTxt);
csHolder.netPriceTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitNetPriceTxt);
csHolder.orderQtyEdit = (CustomEditText) plusMinusView.findViewById(R.id.orderProducts_orderQtyTxt);
csHolder.plusTxt = (RelativeLayout) plusMinusView.findViewById(R.id.orderProducts_plusTxtLay);
csHolder.minusTxt = (RelativeLayout) plusMinusView.findViewById(R.id.orderProducts_minusTxtLay);
plusMinusView.setTag(productPos + "_" + weightPos);
String tag = "weight_" + productPos + "_" + weightPos;
csHolder.orderQtyEdit.setTag(tag);
csHolder.plusTxt.setTag(tag);
csHolder.minusTxt.setTag(tag);
//csHolder.plusTxt.setOnClickListener(weightClick);
//csHolder.minusTxt.setOnClickListener(weightClick);
final View finalPlusMinusView = plusMinusView;
csHolder.plusTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
csHolder.orderQtyEdit.setText("5");
}
});
if(!csStatus.equalsIgnoreCase("DRAFT")) {
csHolder.plusTxt.setVisibility(View.GONE);
csHolder.minusTxt.setVisibility(View.GONE);
csHolder.orderQtyEdit.setEnabled(false);
}
else
{
csHolder.plusTxt.setVisibility(View.VISIBLE);
csHolder.minusTxt.setVisibility(View.VISIBLE);
csHolder.orderQtyEdit.setEnabled(true);
}
try
{
csHolder.orderQtyEdit.addTextChangedListener(new MyTextWatcher(csHolder.orderQtyEdit));
JSONObject weighObj = csMainArr.getJSONObject(productPos).getJSONArray("weights").getJSONObject(weightPos);
if(weighObj.has("unit"))
{
csHolder.weightTxt.setText(weighObj.getString("unit"));
}
if (weighObj.has("order_qty") == false)
weighObj.put("order_qty", "0");
if (weighObj.has("sell_price") == false)
weighObj.put("sell_price", "0");
if (weighObj.has("order_qty") == false)
{
csHolder.totalPriceTxt.setText("0.00");
csHolder.totalTaxTxt.setText("0.00");
csHolder.netPriceTxt.setText("0.00");
}
else {
int qty = 0;
double sellPrice = 0.00;
float tax = 0f;
double totalPrice = 0.00;
double totalTax = 0.00;
double netPrice = 0.00;
if(csStatus.equals("DRAFT")) {
qty = Integer.parseInt(weighObj.getString("order_qty"));
sellPrice = weighObj.getDouble("sell_price");
}
else
{
qty = Integer.parseInt(weighObj.has("qty") ? weighObj.getString("qty"):"0");
sellPrice = weighObj.getDouble("unit_price");
}
tax = Float.parseFloat(csMainArr.getJSONObject(productPos).has("tax") ? csMainArr.getJSONObject(productPos).getString("tax") : "0");
totalPrice = qty*sellPrice;
totalTax = (totalPrice*tax)/100;
netPrice = totalPrice + totalTax;
csHolder.totalPriceTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",totalPrice));
csHolder.totalTaxTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",totalTax));
csHolder.netPriceTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",netPrice));
}
csHolder.orderQtyEdit.isValueChangeMySelf = true;
if(csStatus.equals("DRAFT"))
csHolder.orderQtyEdit.setText(weighObj.getString("order_qty"));
else
csHolder.orderQtyEdit.setText(weighObj.has("qty")?weighObj.getString("qty"):"0");
/*if(weightPos == iClickedItem) {
csHolder.orderQtyEdit.requestFocus();
}
else {
csHolder.orderQtyEdit.clearFocus();
}*/
if(csStatus.equals("DRAFT"))
csHolder.unitPrice.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",weighObj.has("sell_price")?weighObj.getDouble("sell_price") : 0.00));
else
csHolder.unitPrice.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",weighObj.has("unit_price")?weighObj.getDouble("unit_price") : 0.00));
csHolder.minQty.setText(weighObj.has("min_order_qty")?weighObj.getString("min_order_qty"):"0");
//View line = (View) plusMinusView.findViewById(R.id.orderProducts_submitDividerLine);
//if(isLast)
// line.setVisibility(View.GONE);
}
catch(Exception e)
{
}
return plusMinusView;
}

Set the textview in a dynamic tableview

I have a layout for a fragment which contains a textview inside a tableview, and I want to set its text whenever a new row is added.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_fragment,container,false);
doctorNameTextView = (TextView) v.findViewById(R.id.doctorNameTextView);
tableLayout = (TableLayout) v.findViewById(R.id.tableLayout1);
tableLayout.removeAllViews();
showDoctorList();
return v;
}
public void showDoctorList() {
String result = "Match Found";
context = this.getActivity();
MyDBHandler dbHandler = new MyDBHandler(context, null, null, 1);
ArrayList<ArrayList<String>> docArray = new ArrayList<ArrayList<String>>();
DoctorDataModel doctor = null;
try {
doctor = dbHandler.showDoctors();
} catch (SQLException e) {
e.printStackTrace();
}
if (doctor != null) {
docArray = doctor.getDocArray();
for(int i = 0; i < docArray.size(); i++) {
TableRow row = new TableRow(getActivity());
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
for(int j = 1; j < docArray.get(i).size(); j++) {
if(j == 1) {
result = "Dr. " + docArray.get(i).get(j) + " ";
} else {
result = docArray.get(i).get(j) + " ";
}
doctorNameTextView.setText(result);
}
tableLayout.addView(row);
}
}
}
So How do I set the textview inside the dynamic tableview?

Change two textViews inside a listview

Let's say, I have two textviews, TextView A and B.
when I click on A, I need to change both textviews;
When I click on B, I need it to do something else.
I used the setTag(key,A); and setTag(key,B); The textView A changed correctly but the textView B is null. And when I click on B it works.
Here is my code :
public class CustomeAdapterHowComment extends ArrayAdapter<ItemsHowComment> {
Context context;
ItemsHowComment items;
List<LikersComment> likeItems;
List<ItemsHowComment> Items1;
Bitmap bitmap;
String imageUser = "";
String filePath_Image = "/Pictures/jehad/joj/";
String user_id = "1510";
String secret_id = "789654120";
View v;
String onclick = " ";
int x;
String table = "10";
String target = "";
String type = "";
DataBaseHandler dbobj;
public static String server_List_of_Comments = "https://www.ashabe.comt";
public static String server_Comment_like = "https://www.ashabe.com/";
public static String server_Comment_like_remove = "https://www.ashabe.com/";
public static String server_Comment_Delte = "https://www.ashabe.com/";
public static String server_Comment_likers = "https://www.ashabe.com/";
String response;
public CustomeAdapterHowComment(Context context, int textViewResourceId,
List<ItemsHowComment> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("View ", "View>>>>>>>>");
commentholder h = null;
v = convertView;
items = getItem(position);
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
v = vi.inflate(R.layout.how_comment_list, null);
h = new commentholder();
h.img = (ImageView) v.findViewById(R.id.CommentImg);
h.name = (TextView) v.findViewById(R.id.CommentName);
h.commentBody = (TextView) v.findViewById(R.id.CommentBody);
h.like = (TextView) v.findViewById(R.id.CommentLike);
h.numoflike = (TextView) v.findViewById(R.id.CommentNumOfLike);
v.setTag(h);
} else {
h = (commentholder) v.getTag();
}
imageUser = items.getUserId() + items.getRand();
boolean flag_ImagePath = Methods.checkIfImage_DirExists(filePath_Image
+ imageUser);
if (flag_ImagePath == true) {
Log.v("flag_ImagePath", String.valueOf(flag_ImagePath));
bitmap = Methods.displayBitmapImage(imageUser);
h.img.setImageBitmap(bitmap);
}
h.commentBody.setText(items.getCommentBody());
h.name.setText(items.getName());
if (items.getiLike().equals("0")) {
h.like.setText("Like");
}
if (items.getiLike().equals("1")) {
h.like.setText("Unlike");
}
if (items.getNumOfLike().equals("0")) {
h.numoflike.setText("0");
} else {
h.numoflike.setText(items.getNumOfLike());
}
h.name.setOnClickListener(listener);
h.name.setTag(R.id.CommentName, h.name);
h.name.setTag(position);
h.numoflike.setOnClickListener(listener);
h.numoflike.setTag(R.id.CommentNumOfLike, h.numoflike);
h.numoflike.setTag(position);
h.like.setOnClickListener(listener);
h.like.setTag(R.id.CommentLike, h.like);
h.like.setTag(position);
h.img.setOnClickListener(listener);
h.img.setTag(R.id.CommentImg, h.img);
h.img.setTag(position);
return v;
}
private OnClickListener listener = new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View view) {
final int id = view.getId();
type = " ";
CommentEvents t = new CommentEvents();
t.execute();
switch (id) {
case R.id.CommentImg:
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + Items1.get(x).getName());
Toast.makeText(getContext(), Items1.get(x).getName(),
Toast.LENGTH_SHORT).show();
break;
case R.id.CommentName:
// ///profile
try {
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
TextView tv = (TextView) view.getTag(R.id.CommentName);
Log.v("value", x + Items1.get(x).getName());
Toast.makeText(getContext(), Items1.get(x).getName(),
Toast.LENGTH_SHORT).show();
// String user = Items1.get(x).getUserId();
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
break;
case R.id.CommentLike:
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + "");
TextView like = (TextView) view.getTag(R.id.CommentLike);
target = Items1.get(x).getCommentId().toString();
type = "like";
CommentEvents s = new CommentEvents();
s.execute(user_id, secret_id, table, target);
if (Items1.get(x).getiLike().equals("0")) {
like.setText("Unlike");
onclick = "true";
} else if (Items1.get(x).getiLike().equals("1")) {
like.setText("Like");
onclick = "true";
}
case R.id.CommentNumOfLike:
// ////howlike
if (onclick.equals("true")) {
x = (Integer) view.getTag();
TextView numofLike = (TextView) view
.getTag(R.id.CommentNumOfLike);
if (numofLike != null) {
if (Items1.get(x).getiLike().equals("0")) {
Log.e("getNumOfLike____unlike", Items1.get(x)
.getNumOfLike());
int num = Integer.parseInt(Items1.get(x)
.getNumOfLike().toString());
num = num + 1;
Log.e("numberunlike", num + "");
numofLike.setText(num + "");
} else if (Items1.get(x).getiLike().equals("1")) {
Log.e("getNumOfLike_______like", Items1.get(x)
.getNumOfLike());
int num = Integer.parseInt(Items1.get(x)
.getNumOfLike().toString());
num = num - 1;
Log.e("numberlike", num + "");
numofLike.setText(num + "");
}
onclick=" "; }
} else {
try {
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + "");
target = Items1.get(x).getCommentId().toString();
type = "numoflike";
CommentEvents r = new CommentEvents();
r.execute(user_id, secret_id, table, target);
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
}
}
}
};
Use
View view = v.getParent();
and then try to initialize views with view in onClick
You can set Tag
h.name.setOnClickListener(listener);
h.name.setTag(h.numoflike); // use setTag only once
h.numoflike.setOnClickListener(listener);
h.numoflike.setTag(h.name); // use setTag only once
Then in on click
public void onClick(View v) {
switch(v.getId())
{
case R.id.CommentName :
TextView tv1 = (Button) v.getTag();
TextView tv2 = (TextView) v;
tv1.setText("clicked");
tv2.setText("clicked");
break;
case R.id.CommentNumOfLike :
//do something
break;
}
}
Or in onClick Initialize yours views
View view = v.getParent();
TextView tv = view.findVIewById(R.id.CommentName);
TextView tv1 = view.findVIewById(R.id.CommentNumOfLike);
tv.setText("clicked");
tv1.setText("clicked");

Categories

Resources