I have made an android activity,In that multiple LinearLayouts are inflated on a "plus" button,Now in each Layout i am having 2 edittext and a textView,I want to do multiplication of that edittexts and display to textView,its working fine,But i am so much confused when multiple linearLayouts are binded,because i want all the textview values's sum at the end,I have tried as below,but getting wrong values.
code
add.setOnClickListener(new OnClickListener()){
#Override
onClick(){
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.raw_descs, null);
ImageView buttonRemove = (ImageView) addView.findViewById(R.id.iv_del);
et_item_id = (EditText) addView.findViewById(R.id.et_item_id);
et_desc = (EditText) addView.findViewById(R.id.et_desc);
et_qty = (EditText) addView.findViewById(R.id.et_qty);
et_unit_prize = (EditText) addView.findViewById(R.id.et_unit_prize);
et_amt = (EditText) addView.findViewById(R.id.et_amt);
et_qty.addTextChangedListener(textwatcher);
et_unit_prize.addTextChangedListener(textwatcher);
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
((LinearLayout) addView.getParent()).removeView(addView);
// calculate();
if (cnt >= 0) {
cnt = cnt - 1;
}
}
});
cnt = cnt + 1;
listitems.setTag(cnt);
listitems.addView(addView);
}
}
private void calculateInvoice() {
double QuantyInt = 1;
double PriceInt = 0;
double discountInt = 0;
double shipInt = 0;
for (int i = 0; i < listitems.getChildCount(); i++) {
et_qty = (EditText) ((RelativeLayout) listitems.getChildAt(i)).getChildAt(4);
et_amt = (EditText) ((RelativeLayout) listitems.getChildAt(i)).getChildAt(8);
et_unit_prize = (EditText) ((RelativeLayout) listitems.getChildAt(i)).getChildAt(6);
if (et_qty != null) {
QuantyInt = Double.parseDouble(!et_qty.getText().toString().equals("") ? et_qty.getText().toString() : "0");
}
if (et_unit_prize != null) {
PriceInt = Double.parseDouble(!et_unit_prize.getText().toString().equals("") ? et_unit_prize.getText().toString() : "0");
}
subtotal = (QuantyInt * PriceInt);
}
double textResult = subtotal;
System.out.println("::::::::::::MY TOATAL PRICE::::::::::::::::>>>>>>>>>>>>>>>>" + subtotal);
et_amt.setText("$" + textResult + "");
double finaltotal = 0;
for (int i = 0; i < subtotl.size(); i++) {
System.out.println(":::::::::::::Subtotal values+++++++++++:::::::::::>>>>>>>>>>>>>>" + subtotl.get(i));
finaltotal = finaltotal + Double.parseDouble(subtotl.get(i));
}
System.out.println(":::::::::::::Subtotal:::::::::::>>>>>>>>>>>>>>" + finaltotal);
tv_pre.setText("$" + finaltotal + "");
if (et_dis != null) {
discountInt = Double.parseDouble(!et_dis.getText().toString().equals("") ? et_dis.getText().toString() : "0");
}
discount = ((finaltotal * discountInt) / 100);
double txtdiscount = discount;
tv_dis.setText("$" + txtdiscount + "");
double totl1 = finaltotal - discount;
tv_total.setText("$" + totl1 + "");
if (et_ship != null) {
shipInt = Double.parseDouble(!et_ship.getText().toString().equals("") ? et_ship.getText().toString() : "0");
}
tv_ship.setText("$" + et_ship.getText().toString());
double fnltotl = (shipInt + totl1);
tv_total.setText("$" + fnltotl + "");
}
TextWatcher textwatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
calculateInvoice();
}
};
you don't need to get the String in editText which you registered a TextWatcher for that again . just pass that CharSequence from onTextChanged() to calculateInvoice(arg0) and do your calculation based on arg0.
Related
I'm trying to create an app that shows some questions and EditText fields in front of the each of the question for an answer with CountDownTimer, the problem I have is I'm trying to stop the running CountDownTimer on the last entered answer and save those seconds next to user's name but not sure how? I know questionTimer.cancel() would stop the timer but it has to be done on the last entered answer in last EditText.
This is the MainActivity.java file:
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
This is the AdapterListView.java file:
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}
I have manged to sort this out by setting an int variable against Position and calling this in MainActivity class inside the running Timer. Please see the code below.
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
if (adapter.getEndQuiz() == 5) {
questionTimer.cancel();
}
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
Adapter
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
private int endQuiz = 0;
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
if(position == 0) setEndQuiz(1);
else if(position == 1) setEndQuiz(2);
else if(position == 2) setEndQuiz(3);
else if(position == 3) setEndQuiz(4);
else if(position == 4) setEndQuiz(5);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}
i have button,on button click it create editText with value, value of edit text is depending on count of total edit texts.for example edittext1 = 100, when user create two edit text then the value will be like this edittext1 = 50,edittext2 = 50 and so on.( value = 100/ total no of edittext) which i set equally to each edit text.now the problem is when user want to change/update any value from edittext, i want to update value of each edittext according to user's newly entered value.
i want to call textwatcher when value changed by only user,in my case when user click on button it will call.
thank you.
here is my code
public class StageForm extends BaseActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stage_form);
spinnerProjectStage = (Spinner) findViewById(R.id.spinnerAddProjectStage);
spinnerProjectList = (Spinner) findViewById(R.id.spinnerProjectList);
stageLinearLayout = (LinearLayout) findViewById(R.id.stageProjectList);
btnAddMoreStage = (Button) findViewById(R.id.btnAddMoreStage);
btnAddMoreStage.setOnClickListener(this);
getProjectStage();
}
public void onClick(View v) {
if (v.getId() == R.id.btnAddMoreStage) {
public void addMoreFields () {
try {
k++;
flag = k;
final LinearLayout.LayoutParams lparams;
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout[flag] = new LinearLayout(StageForm.this);
layout[flag].setLayoutParams(lparams);
layout[flag].setId(flag);
txtStageName[flag] = new EditText(StageForm.this);
txtStageName[flag].setLayoutParams(lparams);
txtStageName[flag].setHint("stage " + k + "");
txtStageName[flag].setId(flag);
txtStagePercent[flag] = new EditText(StageForm.this);
txtStagePercent[flag].setLayoutParams(lparams);
txtStagePercent[flag].setHint("percent");
txtStagePercent[flag].setId(flag);
txtStagePercent[flag].addTextChangedListener(stagePercentChangeListener);
if (flag == 0) {
txtStagePercent[flag].setText(String.valueOf(totalPercent));
} else {
countEditText = flag + 1;
calculatePercentage(countEditText, flag);
}
} catch (Exception e) {
e.printStackTrace();
}
layout[flag].addView(txtStageName[flag]);
layout[flag].addView(txtStagePercent[flag]);
stageLinearLayout.addView(layout[flag]);
}
}
}
private void calculatePercentage(int countEditText, int flag) {
k = flag;
if (flag == 0) {
// countEditText = flag;
lastTextBox = countEditText;
} else {
// countEditText = flag;
lastTextBox = countEditText - 1;
}
result = totalPercent / countEditText;
convertFloatResult = Math.round(result);
remainingPercent = totalPercent - (convertFloatResult * countEditText);
lastTextValue = convertFloatResult + remainingPercent;
try {
if (remainingPercent == 0) {
for (int j = 0; j <= lastTextBox; j++) {
txtStagePercent[j].setText(String.valueOf(convertFloatResult));
}
txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue));
} else {
for (int j = 0; j < lastTextBox; j++) {
txtStagePercent[j].setText(String.valueOf(convertFloatResult));
}
txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private TextWatcher stagePercentChangeListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (flag == 0) {
} else {
String getbeforValue = String.valueOf(s);
beforeTextChanged = Integer.parseInt(getbeforValue);
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String getchangedValue = String.valueOf(s);
afterTextChanged = Integer.parseInt(getchangedValue);
}
#Override
public void afterTextChanged(Editable s) {
totalPercent = totalPercent - afterTextChanged;
countEditText = countEditText - 1;
calculatePercentage(countEditText, flag);
}
};
}
I am not able to get edittext value from dynamic listview. When I am scrolling listview, entered values in edit text is going invisible
Below is My Activity file -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_servic_homepage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
url = getResources().getString(R.string.webservice);
aq = new AQuery(ServicHomepage.this);
cd = new ConnectionDetector(ServicHomepage.this);
findviewbyId();
progressdialog();
if (cd.isConnectingToInternet()) {
getintentData();
} else {
Toast.makeText(ServicHomepage.this, "CheckIternet connection", Toast.LENGTH_SHORT).show();
}
}
private void progressdialog() {
pd = new ProgressDialog(ServicHomepage.this);
pd.setMessage("Loading...");
}
public void findviewbyId() {
recyclerview = (ListView) findViewById(R.id.service_recycler_view);
update_descrptn = (TextView) findViewById(R.id.update_descrptn);
uploadimages = (TextView) findViewById(R.id.uploadimages);
}
public void getintentData() {
SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
catid = prefs.getString(Constants.CATID, "");
subcatid = prefs.getString(Constants.SUBCATID, "");
user_id = prefs.getString(Constants.USERID, "");
isappointment = prefs.getString(Constants.IS_APPOINTMENT, "");
clicklistener();
}
public void clicklistener() {
uploadimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GalleryAlbumActivity.class);
startActivity(i);
}
});
update_descrptn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ServicHomepage.this, "" + serv_adapter.getItem(POSITION), Toast.LENGTH_SHORT).show();
for (int i = 0; i < serv_adapter.getCount(); i++) {
View view = serv_adapter.getView(i,null,null);
EditText edittext = (EditText)view.findViewById(R.id.et_amount);
EditText et_description = (EditText)view.findViewById(R.id.et_description);
String str = edittext.getText().toString();
String str1 = et_description.getText().toString();
Toast.makeText(ServicHomepage.this, str + "==" + str1, Toast.LENGTH_SHORT).show();
}
updateList();
}
});
}
private void updateList() {
String substring = null, msgString = "";
String MAIN_CART = null;
MAIN_CART = "{\"service\":[%s]}";
String temstring = "";
for (int i = 0; i < arrayList.size(); i++) {
substring = "{\"title\":\"" + arrayList.get(i).getTitle() + "\",\"subcatid\":\"" + arrayList.get(i).getSubcatid()
+ "\",\"amount\":\"" + "" + "\",\"description\":\"" + "" + "\"}" + ",";
temstring = temstring + substring;
}
temstring = temstring.substring(0, temstring.length() - 1);
msgString = msgString + String.format(MAIN_CART, temstring);
Log.e("msgString=============", msgString);
}
This is the method where all the items are adding in the list
public String parseanimcat(String object) {
try {
JSONObject json = new JSONObject(object);
JSONObject jsonobj = json.getJSONObject("data");
status1 = jsonobj.getString("status");
message = jsonobj.getString("message");
arrayList = new ArrayList<>();
JSONArray jarray = jsonobj.getJSONArray("dataFound");
for (int i = 0; i <= jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String category = jobj.getString("category");
String subsubcat_id = jobj.getString("subsubcat_id");
Toast.makeText(ServicHomepage.this, category + "==" + subsubcat_id, Toast.LENGTH_SHORT).show();
model = new Data_Model();
model.setTitle(category);
model.setSubcatid(subsubcat_id);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
This is my adapter class-
private class service_list_adapter extends ArrayAdapter<Data_Model>{
private ArrayList<Data_Model> array_list;
Context context;
String[] etValArr;
ViewHolder holder;
String[] totalValue;
Data_Model model;
HashMap<String, String> hm = new HashMap<>();
ArrayList<HashMap<String, String>> list = new ArrayList<>();
public service_list_adapter(Context context,int resourceId,ArrayList<Data_Model> arrayList) {
super(context,resourceId,arrayList);
this.context = context;
this.array_list = arrayList;
etValArr = new String[array_list.size()];
totalValue = new String[array_list.size()];
}
private class ViewHolder {
public TextView serv_title;
public EditText serv_descrptn, serv_amount;
}
public View getView(int position, View convertView, ViewGroup parent) {
model = array_list.get(position);
POSITION = position;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.serv_cat_rowitem, null);
holder = new ViewHolder();
holder.serv_title = (TextView) convertView.findViewById(R.id.serv_txt);
holder.serv_descrptn = (EditText) convertView.findViewById(R.id.et_description);
holder.serv_amount = (EditText) convertView.findViewById(R.id.et_amount);
convertView.setTag(holder);
holder.serv_title.setTag(position);
holder.serv_descrptn.setTag(position);
holder.serv_amount.setTag(position);
} else
holder = (ViewHolder) convertView.getTag();
holder.serv_title.setText(model.getTitle());
holder.serv_descrptn.setText(model.getServdescription());
holder.serv_amount.setText(model.getServamount());
holder.serv_amount.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 s) {
model.setServamount(s.toString());
}
});
holder.serv_descrptn.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 s) {
model.setServdescription(s.toString());
}
});
return convertView;
}
}
be more specific exactly which editText value you want.
you can implement onScrollListner on list and save the value of the editText on that event and later use it
here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.
I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}