So I am dynamically adding rows to table which consist of some data (httpresponse) and buttons (like delete). How can I add onClickListener for delete button so it knows which row I want to delete?
This is part of my code, if you need more let me know:
try {
HttpResponse httpResponse = httpclient.execute(request);
String result = EntityUtils.toString(httpResponse.getEntity());
if (!result.isEmpty()) {
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObjekt = ja.getJSONObject(i);
Racuni novi = new Racuni();
novi.setCode(jsonObjekt.getString("Code"));
novi.setDate(jsonObjekt.getString("Date"));
novi.setTotal(jsonObjekt.getString("Total"));
niz.add(i, novi);
}
for (int i = 0; i < niz.size(); i++) {
TableRow redak = new TableRow(getApplicationContext());
final TextView code = new TextView(getApplicationContext());
code.setText(niz.get(i).getCode());
code.setPadding(0, 0, 5, 0);
TextView date = new TextView(getApplicationContext());
date.setText(niz.get(i).getDate());
date.setPadding(0, 0, 5, 0);
TextView total = new TextView(getApplicationContext());
total.setText(niz.get(i).getTotal());
total.setPadding(0, 0, 5, 0);
final Button print = new Button(getApplicationContext());
print.setText("P");
final Button delete = new Button(getApplicationContext());
delete.setText("D");
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//so this is what i would like it to do, but with the proper id
int id = Integer.parseInt(code.getText().toString());
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://staging-api.e-poslovanje.hr/ReceiptCash/Delete" + "?id=" + id);
request.addHeader("Authorization", "Basic " + base64EncodedCredentials);
try {
httpclient.execute(request);
Toast.makeText(getApplicationContext(), "You have deleted receipt " + code.getText().toString(), 5000).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
redak.addView(code);
redak.addView(date);
redak.addView(total);
redak.addView(delete);
redak.addView(print);
list.addView(redak);
}
You can use Tag to hold the Id.
On the delete button , set the Id as tag
tag. delete.setTag(code.getText().toString())
and on onClick() you can retrieve the id like..
int = delete.getTag();
Create a "Row" class with Buttons and Textview. Instead of creating each button in the for loop just create a row
class Row{
Button delete
Button print
Textview date
public Row(){
delete.setOnClickListener(.....);
}
}
and than in mainActivity
for (int i = 0; i < niz.size(); i++) {
Row row=new Row();
}
Related
private void parseProductOptionData(JSONObject response){
try {
boolean success = response.getBoolean("success");
if(success){
rlProductOption.setVisibility(View.GONE);
//Get All the Categories
JSONArray data = response.getJSONArray("data");
if(data.length()!=0){
rlProductOptionQuantityTxt.setVisibility(View.VISIBLE);
for(int i= 0;i<data.length();i++){
//First Get Type
JSONObject optionQuantity = data.getJSONObject(i);
Log.d(TAG, "onResponse: option quantity"+optionQuantity);
//Create a Layout
llMainLayout = new LinearLayout(getActivity());
llMainLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
llMainLayout.setBackgroundResource(R.drawable.border_details);
llMainLayout.setOrientation(LinearLayout.VERTICAL);
llMainLayout.setPadding(10,0,10,5);
llProductOptionsSheet.addView(llMainLayout);
tvOptionTitleText= new TextView(getActivity());
tvOptionTitleText.setId(Integer.valueOf("1"+i));
tvOptionTitleText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
tvOptionTitleText.setTypeface(Typeface.SERIF);
llMainLayout.addView(tvOptionTitleText);
tvOptionTitleText.setText(optionQuantity.getString("title"));
if(optionQuantity.getString("min_selection").equals("1") && optionQuantity.getString("max_selection").equals("1")){
RadioGroup maxAndMin = new RadioGroup(getActivity());
maxAndMin.setOrientation(LinearLayout.VERTICAL);
maxAndMin.clearCheck();
//maxAndMin.setId(Integer.valueOf("1"));
maxAndMin.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Option length1 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
RadioButton rdbtn = new RadioButton(getActivity());
//rdbtn.setId(i);
//if (btnCount==0)
rdbtn.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
maxAndMin.addView(rdbtn);
}
llMainLayout.addView(maxAndMin);
}else if(optionQuantity.getString("min_selection").equals("0") && optionQuantity.getString("max_selection").equals("1")){
RadioGroup maxAndMin = new RadioGroup(getActivity());
maxAndMin.setOrientation(LinearLayout.VERTICAL);
maxAndMin.clearCheck();
//maxAndMin.setId(Integer.valueOf("1"));
maxAndMin.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Option length1 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
RadioButton rdbtn = new RadioButton(getActivity());
//rdbtn.setId(i);
rdbtn.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
maxAndMin.addView(rdbtn);
}
llMainLayout.addView(maxAndMin);
}else{
Log.d(TAG, "Option length2 "+optionQuantity.getJSONArray("options").length());
for (int btnCount =0;btnCount<optionQuantity.getJSONArray("options").length();btnCount++){
Log.d(TAG, "Option data fetch "+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name"));
CheckBox cbMaxOption = new CheckBox(getActivity());
cbMaxOption.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
cbMaxOption.setText(optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("name")+" ("+optionQuantity.getJSONArray("options").getJSONObject(btnCount).getString("price")+")");
llMainLayout.addView(cbMaxOption);
}
}
}
}else{
Log.d(TAG, "No product option ");
rlProductOptionQuantityTxt.setVisibility(View.VISIBLE);
}
btnAddToCart = new Button(getActivity());
btnAddToCart.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
btnAddToCart.setBackgroundColor(getResources().getColor(R.color.color_btn_login));
btnAddToCart.setText(getActivity().getResources().getString(R.string.add_to_cart));
btnAddToCart.setTypeface(Typeface.SERIF);
btnAddToCart.setTextColor(Color.WHITE);
llProductOptionsSheet.addView(btnAddToCart);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvOptionTitleText.setError("please fill all the text");
}
});
}else{
rlProductOption.setVisibility(View.GONE);
Toast.makeText(getActivity(),response.getString("message"),Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Sorry try Later!!!",Toast.LENGTH_SHORT).show();
rlProductOption.setVisibility(View.GONE);
}
}
This is my code in which i have add radio button and checkbox according to json data.So when i click on a button "btnAddToCart" then i want to know all the selected checkbox and radio button.beacuse i have to store all the selected data in my session.
Declare a global variable like:
int rlProductOptionQuantityTxt =0;// for default case
Use Switch case,
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.yourRadioButton:
rlProductOptionQuantityTxt =1;
}
}
and then you can directly use the value of your global variable.
SetGet.setProductOptionQuantityTxt(rlProductOptionQuantityTxt );
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
How can I refresh the LinearLayout called "contNoticias" after doing a click in a button?
Here is my code:
contNoticias = (LinearLayout)findViewById(R.id.contNoticias);
int arrayNoticias = 1;
for (int i = 0; i < arrayNoticias; i++) {
//agregar views
RelativeLayout relativeLayout = new RelativeLayout(antro.this);
relativeLayout.setPadding(0, 0, 0, 0);
relativeLayout.setId(+1);
contNoticias.addView(relativeLayout);
relativeLayout.setBackgroundResource(R.drawable.textviews_menu);
//Separar variables
try {
httpHandler handler = new httpHandler();
String response = handler.post(url + "MyDayFiles/muro.php");
JSONArray array = new JSONArray(response);
for (int u = 0; u < array.length(); u++) {
JSONObject jsonObject = array.getJSONObject(u);
tituloN += jsonObject.getString("nombre") + "/";
tituloN = tituloN.replace("null", "");
titulosN = tituloN.split("/");
noticiaN += jsonObject.getString("noticia") + "/";
noticiaN = noticiaN.replace("null", "");
noticiasN = noticiaN.split("/");
imagenN += jsonObject.getString("foto") + "/";
imagenN = imagenN.replace("null", "");
imagenesN = imagenN.split("/");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//imagen
ImageView imagenNoticia = new ImageView(antro.this);
imagenNoticia.setId(+2);
RelativeLayout.LayoutParams imagenNoticiaParams = new RelativeLayout.LayoutParams(250, 250);
imagenNoticiaParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
imagenNoticiaParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
imagenNoticiaParams.addRule(RelativeLayout.ALIGN_PARENT_START);
imagenNoticia.setLayoutParams(imagenNoticiaParams);
imagenNoticia.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.with(this).load(url + "MyDayFiles/imgnoticias/" + imagenesN[i]).into(imagenNoticia);
//imagen
//titulo
TextView tituloNoticia = new TextView(antro.this);
tituloNoticia.setId(+3);
RelativeLayout.LayoutParams tituloNoticiaParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tituloNoticiaParams.addRule(RelativeLayout.RIGHT_OF, imagenNoticia.getId());
tituloNoticia.setLayoutParams(tituloNoticiaParams);
tituloNoticia.setTextColor(Color.DKGRAY);
tituloNoticia.setTextSize(12);
tituloNoticia.setPadding(20, 0, 0, 0);
tituloNoticia.setText(titulosN[i]);
//titulo
//noticia
TextView textoNoticia = new TextView(antro.this);
textoNoticia.setId(+4);
RelativeLayout.LayoutParams textoNoticiaParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textoNoticiaParams.addRule(RelativeLayout.BELOW, tituloNoticia.getId());
textoNoticiaParams.addRule(RelativeLayout.RIGHT_OF, imagenNoticia.getId());
textoNoticia.setLayoutParams(textoNoticiaParams);
textoNoticia.setTextColor(Color.GRAY);
textoNoticia.setTextSize(12);
textoNoticia.setPadding(20, 0, 0, 0);
textoNoticia.setText(noticiasN[i]);
//noticia
//agregar views
relativeLayout.addView(imagenNoticia);
relativeLayout.addView(tituloNoticia);
relativeLayout.addView(textoNoticia);
}
The thing is I want to refresh the views inside my LinearLayout when the user clicks a button "Post" so the new post can be displayed at the screen at the moment the user clicks the button
I have 3 row in table, where every row has 3 checkbox. I want to check appropriate CheckBox according to its id.
I have to check following ids CheckBox.
tempArray =[1-2-3,3-2,null];
i am already splitting these data and putting in string array(setopts).more see my code.
Null for no check any CheckBox with this row.
I am doing this code in my project.
Vector<CheckBox> chkBoxList = new Vector<CheckBox>();
Vector<TextView> txtViewList = new Vector<TextView>();
// mat_elemItemSetChk.get(0).size() OF VALUE IS 3
for (int n = 0; n < mat_elemItemSetChk.get(0).size(); n++) {
LinearLayout llayout = new LinearLayout(getContext());
ll.setOrientation(android.widget.LinearLayout.VERTICAL);
cb = new CheckBox(getContext());
tv = new TextView(getContext());
for (int r = 0; r < tempArray.size() ; r++) {
isContains=tempArray.get(r).contains(individualValueSeparator);
if(isContains){
setOpts = tempArray.get(r).split("\\-");
for (int k = 0; k < setOpts.length; k++)
{
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) iv.getId()) == Integer.parseInt(setOpts[k]))
{
mat_elemItemSetChk.get(n).get(Integer.parseInt(setOpts[k])-1);
cb.setChecked(true);
}
}
}else{
if(tempArray.get(r).toString().equalsIgnoreCase("null")||tempArray.get(r).toString()!=null){
String temp;
String px[]= null;
temp = tempArray.get(r).toString();
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) IV.getId()) == Integer.parseInt(temp))
{
mat_elemItemSetChk.get(0).get(Integer.parseInt(temp) - 1);
cb.setChecked(true);
}
}else{
cb.setChecked(false);
}
}
}
tv.setText(mat_elemItemSetChk.get(0).get(n) .toString());
llayout.addView(cb);
llayout.addView(tv);
chkBoxList.add(cb);
txtViewList.add(tv);
ll.addView(llayout);
// this.addView(tableLayout);
}
Thank you in advance.
make an array selchkboxlist and store the selected checkbox id in it and check condition like selchkboxlist.isEmpty() if true then then show error msg other wise go ahed...
selchkboxlist=new ArrayList<String>();
cbs = new CheckBox[8];
// generate dynamic item check box code
for(int k = 0; k<8; k++)
{
cbs[k] = new CheckBox(getApplicationContext());
#SuppressWarnings("deprecation")
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(cbs[k], params);
int j =k+1;
cbs[k].setText("ITEM" + j);
cbs[k].setTextColor(Color.parseColor("#000000"));
cbs[k].setId(k+1);
cbs[k].setPadding(70, 20, 10, 10);
// check box on click listener for add in to produduct array with quntity
cbs[k].setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
String chk = null;
if (((CheckBox) v).isChecked()) {
chk = Integer.toString(v.getId());
selchkboxlist.add(chk);
} else {
selchkboxlist.remove(chk);
}
}
});
}
// button on click listener code
b.setOnClickListener(new OnClickListener() {
#SuppressLint("SdCardPath")
public void onClick(View v) {
if (! selchkboxlist.isEmpty()) {
shoe erroe msg here
}else{
go ahed
}
}
});
I am trying to display a list of items I am getting from a mysql database on a webserver. Here is my create for the page.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getlist);
showBusyDialog();
new GetData()
.execute(picdetails);
}
Here is my GetData class. The problem here is with the lines that are adding items to the listview. I am passing a JSON array as a text result.
public class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... pic) {
// You might be tempted to display the busy dialog here, but you
// CAN'T update the UI from this method!
return loadImageFromNetwork(pic[0]);
}
#Override
protected void onPostExecute(String result) {
// Our long-running process is done, and we can safely access the UI thread
int ct_id;
String item_make;
String item_model;
String item_price;
String item_desc;
String item_location;
String item_image;
dismissBusyDialog();
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout1);
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("id");
item_make=json_data.getString("make");
item_model=json_data.getString("model");
item_price = json_data.getString("price");
item_desc = json_data.getString("cardesc");
item_location = json_data.getString("location");
item_image = json_data.getString("image");
String image_URL = "http://www.myurl.com/images/" + car_image;
TableRow tr = new TableRow(null);
tr.setId(ct_id);
tr.setClickable(true);
tr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
String sdet_id;
int det_id;
// v.setBackgroundColor(Color.GRAY);
det_id = v.getId();
sdet_id = String.valueOf(det_id);
final Intent i = new Intent();
i.setClassName("demo.example.com", "demo.example.com.viewdetails");
i.putExtra("Det_id", sdet_id);
startActivity(i);
// v.setBackgroundColor(Color.TRANSPARENT);
// TODO Auto-generated method stub
}
});
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin=20;
int topMargin=10;
int rightMargin=15;
int bottomMargin=20;
tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(tableRowParams);
/* Create a Button to be the row-content. */
ImageView myimage = new ImageView(R.layout.getlist);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
myimage.setImageBitmap(bm);
tr.addView(myimage);
TextView tmake=new TextView(R.layout.getlist);
// tmake.setText(item_make);
tmake.setText(Html.fromHtml("<H1>" + " " + item_location + "</H1>" + "<br /> ;" + item_desc
));
tr.addView(tmake);
TextView tmodel=new TextView(R.layout.getlist);
tmodel.setText(Html.fromHtml("<b><H1>" + " " + "€" + item_price + "</b></H1></br></br>" ));
tr.addView(tmodel);
/* Add row to TableLayout. */
// tr.setPadding(50, 0, 0, 0);
tl.addView(tr);
View v = new View(R.layout.getlist);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
v.setBackgroundColor(Color.rgb(51, 51, 51));
tl.addView(v);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Category Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
The problem appears to be with creating new items to add to the view, lines like this
View v = new View(R.layout.getlist);
Is my overall structure ok or do I need to do this another way?
1.Usually we show the busy dialog in the onPreExecute of the
asyncTask.
2.You need to inflater your views thanks to an inflater.
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.view, null);
Hope this will help you.
Hi i have created an array of dates and i'm wanting to add a header view for each of these dates i'm then gonna run another for loop that will add other views underneath each header. at the moment i'm just wanting to add the header views but currently nothing is showing on screen. so my question is How can i programmatically add views within a for loop?
heres my code
public void FillData() throws JSONException{
ListView list = getListView();
list.scrollTo(0, 0);
list.setVerticalFadingEdgeEnabled(false);
list.setTextFilterEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View header = inflater.inflate( R.layout.homeheader, list, false);
fixturesView = LayoutInflater.from(getBaseContext()).inflate(R.layout.fixturescell,
null);
//Log.v("MyFix", "fixturesArray = " + fixturesArray);
if(fixturesArray.length() < 1){
TextView emptytext = (TextView) fixturesView.findViewById(R.id.TextView02);
emptytext.setText("No Upcoming Fixtures Available");
}else{
try{
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject matchDateDict = fixturesArray.getJSONObject(t);
String matchDate = matchDateDict.getString("matchdate");
if(matchDatesArray.length() != 0){
int lm = t - 1;
JSONObject lastDateDict = fixturesArray.getJSONObject(lm);
String lastMatchDate = lastDateDict.getString("matchdate");
Log.v("MyFix", "lastMatchDate " + lastMatchDate);
if(matchDate.equals(lastMatchDate)){
Log.v("MyFix", "2 are the same");
} else {
Log.v("MyFix", "add new matchdate to array");
matchDatesArray.put(matchDate);
}
} else {
Log.v("MyFix", "add new matchdate to array (first time only)");
matchDatesArray.put(matchDate);
}
}
Log.v("MyFix", "matchDatesArray = " + matchDatesArray);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateHeader = LayoutInflater.from(getBaseContext()).inflate(R.layout.redcell,
null);
adapter = new MergeAdapter();
for(int t = 0; t < matchDatesArray.length(); t++){
JSONObject mdheaderdict = matchDatesArray.getJSONObject(t);
String matchheader = mdheaderdict.getString("matchdate");
TextView matchdayheader = (TextView) DateHeader.findViewById(R.id.redheadertext);
matchdayheader.setText(matchheader);
adapter.addView(DateHeader);
}
}
setListAdapter(adapter);
}
}
i think this is what you are searching for
http://code.google.com/p/android-amazing-listview/
ListView with section headers and auto-loading of next pages (i.e. "Loading..." on the last item)