TableRow is returning empty value in TableLayout? - java

I have an Activity which does not have any layout file. Here there is a TableLayout which has 5 input rows. I want to get those edittext value from the rows. I have tried a lot but still unable to get the data from the rows.
Here is my activity.java file.Is there any other way to get the data from edittext? I have tried this.Duplicate Question but my app crashes with showing the error "TableRow can not be cast into EditText".
public class MainActivity extends AppCompatActivity {
ScrollView sv;
TableLayout myTableLayout;
String userName,
firstName,
city,
zipCode,
age;
UserListAdapter adapter;
RecyclerView recyclerView;
List <User> userList;
TableRow inputRow;
String temp = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TurnToTech", "Project Name - Dynamic table view");
sv = new ScrollView(this);
userList = new ArrayList <>();
myTableLayout = new TableLayout(this);
drawScreen();
recyclerView = new RecyclerView(this);
}
public void drawScreen() {
// this might be a redraw, so we clean the view's container
myTableLayout.removeAllViews();
sv.removeAllViews();
// special rows
TableRow buttonRow = new TableRow(this);
TableRow titleRow = new TableRow(this);
//Alerts
final AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Saveing");
alertDialog.setMessage("Saved..");
final AlertDialog alertDialog1;
alertDialog1 = new AlertDialog.Builder(this).create();
alertDialog1.setTitle("Cancel");
alertDialog1.setMessage("Rejected");
// margins
buttonRow.setPadding(20, 10, 20, 10);
titleRow.setPadding(20, 10, 20, 10);
// the title
TextView title = new TextView(this);
title.setText("Data input form");
title.setTextSize(14);
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER_HORIZONTAL);
titleRow.addView(title);
titleRow.setGravity(Gravity.CENTER);
// the title tablelayout
TableLayout titleTableLayout = new TableLayout(this);
titleTableLayout.addView(titleRow);
// we add the title layout to the main one
myTableLayout.addView(titleTableLayout);
/// the 5 input rows
inputRow(myTableLayout, "Name", 30, 10000); //returning ""
inputRow(myTableLayout, "First Name", 30, 10001); //returning ""
inputRow(myTableLayout, "Age", 3, 10002); //returning ""
inputRow(myTableLayout, "City", 20, 10003); //returning ""
inputRow(myTableLayout, "Zip Code", 6, 10004); //returning ""
// the buttons table layout
// purpose : right align for both buttons
TableLayout buttonsLayout = new TableLayout(this);
buttonRow.setPadding(20, 50, 40, 0);
// the accept and cancel buttons
Button btAccept = new Button(this);
btAccept.setText("Save");
btAccept.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
//TODO here I want to get all the row value that I filled from the table and store the value inside the user object.
User user = new User(userName, firstName, age, city, zipCode);
userList.add(user);
adapter = new UserListAdapter(userList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
Button btCancel = new Button(this);
btCancel.setText("Cancel");
btCancel.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
alertDialog1.show();
}
});
buttonRow.addView(btAccept);
buttonRow.addView(btCancel);
buttonRow.setGravity(Gravity.RIGHT);
buttonsLayout.addView(buttonRow);
myTableLayout.addView(buttonsLayout);
sv.addView(myTableLayout);
setContentView(sv);
}
public void inputRow(TableLayout tl, String label, int inputSize, int inputID) {
inputRow = new TableRow(this);
TextView tv = new TextView(this);
EditText edit = new EditText(this);
// some margin
inputRow.setPadding(20, 10, 20, 0);
tv.setText(label);
edit.setMaxWidth(inputSize * 7);
edit.setMinimumWidth(inputSize * 7);
edit.setId(inputID);
edit.setGravity(Gravity.RIGHT);
inputRow.addView(tv);
inputRow.addView(edit);
tl.addView(inputRow);
}
}
I mentioned a todo inside the onClick event.

Inside of onClick() for btAccept, you'll need to call something like this for each EditText:
#SuppressLint("ResourceType") EditText nameEditText = findViewById(10000);
String nameEntered = nameEditText.getText().toString();
.
.
.
One you've done this for all your EditTexts, you can store them in a User object.

Related

Getting a view's index in a LinearLayout

So I have a LinearLayout set up in my XML file, and I dynamically add a bunch of CardViews to it through code upon startup of my activity. How can I make it so that when I click on any of the CardViews, I am able to obtain its position?
I tried setting up on an onClickListener for the LinearLayout, as well as an OnClickLIstener for each individual card, but couldn't find a way to obtain the index of the card that was clicked.
I'd really like to know where to put the onClickListener, and how to obtain the position that was clicked so that I can start a new activity based on what was clicked.
Here is my code:
private LinearLayout sLinearLayout;
private CardView[] cardViews;
private Workout[] workouts;
private ViewGroup.LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saved_workouts);
Intent intent = getIntent();
Parcelable[] parcelableArrayExtra = intent.getParcelableArrayExtra(MainActivity.EXTRA_WORKOUTS);
workouts = new Workout[parcelableArrayExtra.length];
System.arraycopy(parcelableArrayExtra, 0, workouts, 0, parcelableArrayExtra.length);
sLinearLayout = findViewById(R.id.viewList);
// Set the CardView layoutParams
params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
populateCardViews();
populateLayout();
}
//TODO: this method will populate the linear layout, filling the list.
private void populateLayout() {
for (CardView cardView : cardViews) {
sLinearLayout.addView(cardView);
}
}
//TODO: this method will fill up the CardViews array with an array of workouts.
private void populateCardViews() {
cardViews = new CardView[workouts.length];
for(int i = 0; i < workouts.length; i++) {
CardView card = new CardView(this);
card.setClickable(true);
card.setLayoutParams(params);
// Set CardView corner radius
card.setRadius(9);
// Set cardView content padding
card.setContentPadding(15, 15, 15, 15);
// Set a background color for CardView
card.setCardBackgroundColor(Color.BLUE);
// Set the CardView maximum elevation
card.setMaxCardElevation(50);
// Set CardView elevation
card.setCardElevation(25);
// Initialize a new TextView to put in CardView
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText("Workout WorkTime: " + workouts[i].getWorkTime());
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
tv.setTextColor(Color.WHITE);
card.setTag(workouts[i].getWorkTime());
card.addView(tv);
cardViews[i] = card;
}
}
I think you can setOnClickListener for each individual card. The index of clicked card is i
for (int i = 0; i < workouts.length; i++) {
...
final int finalI = i;
card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("TAG", "You click at card: " + finalI);
}
});
}
I not good to add so much layout programmatically. You can use a recycler view and an adapter to show a list of items. You can read this: https://developer.android.com/guide/topics/ui/layout/recyclerview
By the way, in your case: when you create a Cardview, just add onClickListener to it and the index of your Cardview is the index of it in Cardview list.
CardView cardView = new CardView(this);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click here
}
});
See if this works.
cardview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index = linearLayout.indexOfChild(v);
}
});

Check if various checkboxes that have being created programmatically are checked when you click a button in android

My question is:
How I can check if the checkboxes are checked and how can I get its id or text in a onclick event?
I have done it whit RadioGroup, but RadioGroup only let me check 1 RadioButton, and in this case I need to check more than one, but if Im wrong and there is a way to do it with RadioGroup it should work for me.
Thanks for the help
Here is the code where I create the checkboxes programmatically:
protected void onCreate(Bundle savedInstanceState) {
LinearLayout lg = (LinearLayout) findViewById(R.id.lg);
Button botonenv = (Button) findViewById(R.id.botonenv);
try{
myJson = new JSONObject(data);
JSONArray Solutions = myJson.getJSONArray("solutions");
for (int i = 0; i < Solutions.length(); i++) {
JSONObject JSonSol = Solutions.getJSONObject(i);
final String idSt = JSonSol.getString("id");
final String name = JSonSol.getString("name");
String resp = name.toUpperCase();
CheckBox cb1 = new CheckBox(this);
cb1.setText(resp);
LinearLayout.LayoutParams llg = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llg.setMargins(0, 30, 0, 0);
cb1.setTextSize(15);
cb1.setTextColor(Color.parseColor("#FF000000"));
lg.addView(cb1);
int id =Integer.parseInt(idSt);
cb1.setId(id);
}
}catch(JSONException e){
e.printStackTrace();
}
botonenv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//HERE I MUST NOW WHAT CHECKBOXES ARE CHECKED AND THEIR IDS
..............
}
});
}
Add their references to list , then you can reuse those reference again in any where outside after creation .
like
List<CheckBox> checkBoxes = new ArrayList<>();
add checkbox to your list wherever your create a new one checkBoxes.add(cb1);
inside your onClick you can check all of them .

Changing the onClickListener of an Imagebutton dynamically without ever leaving the activity

I have an ImageButton with an onClickListener. That sets the "favorite" column of an entry in my database to "1" or "0" and changes the image of the button. What is the best way to refresh the view or activity, so the onClickListener changes dynamically.
If I failed to make myself clear:
Click 1: Update favorite column to 1, change image to ic_star_black_48dp
Click 2: Update favorite column to 0, change image to ic_star_border_black_48dp
Click 3: Update favorite column to 1, change image to ic_star_black_48dp
Click 4: Update favorite column to 0, change image to ic_star_border_black_48dp
All of this without ever leaving the activity.
star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cn.getFavorite() == 0) {
star.setImageResource(R.mipmap.ic_star_black_48dp);
db_verladestellen.updatePlace(new Location(cn.getID(), cn.getPlace_id(), cn.getName(), cn.getLongitude(), cn.getLatitude(), cn.getTor(), 1));
}
else{
star.setImageResource(R.mipmap.ic_star_border_black_48dp);
db_verladestellen.updatePlace(new Location(cn.getID(), cn.getPlace_id(), cn.getName(), cn.getLongitude(), cn.getLatitude(), cn.getTor(), 0));
}
}
});
EDIT:
Since you asked, this is the whole class. Below it is the method getAllDBPlaces().
public class UI_Verladestellen extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verladestellen);
//Initialisation of the database
final DB_Verladestellen db_verladestellen = new DB_Verladestellen(this);
//Saves all entries from the database in a List
List<Location> placeList = db_verladestellen.getAllDBPlaces();
//Generates a button for each entry in the list
for (final Location cn : placeList) {
//Linear Layout for the buttons
final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste);
final LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//Favorites-Button
final ImageButton star = new ImageButton(this);
star.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (cn.getFavorite() == 0) {star.setImageResource(R.mipmap.ic_star_border_black_48dp);}
else {star.setImageResource(R.mipmap.ic_star_black_48dp);}
star.setId(cn.getID());
row.addView(star);
star.setPadding(50,50,50,50);
star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cn.getFavorite() == 0) {
star.setImageResource(R.mipmap.ic_star_black_48dp);
db_verladestellen.updatePlace(new Location(cn.getID(), cn.getPlace_id(), cn.getName(), cn.getLongitude(), cn.getLatitude(), cn.getTor(), 1));
}
else{
star.setImageResource(R.mipmap.ic_star_border_black_48dp);
db_verladestellen.updatePlace(new Location(cn.getID(), cn.getPlace_id(), cn.getName(), cn.getLongitude(), cn.getLatitude(), cn.getTor(), 0));
}
}
});
//Location-Button
Button place = new Button(this);
place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
place.setText(cn.getName());
place.setId(cn.getID());
row.addView(place);
row.setId(cn.getID());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams();
params.weight = 1.0f;
place.setLayoutParams(params);
place.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMap(cn.getID());
}
});
layout.addView(row);
}
}
//Methode zum öffnen der Map in MainActivity. Übermittelt die ID des Buttons, von dem die Methode aufgerufen wird.
//Diese ID ist identisch mit der ID des Ortes in der Datenbank, den der Button repräsentiert.
public void openMap(int view) {
Intent intent = new Intent(UI_Verladestellen.this, UI_MainActivity.class);
intent.putExtra("findLocation", view);
startActivity(intent);
}
}
getALLDBPlaces:
public List<Location> getAllDBPlaces() {
List<Location> placeList = new ArrayList<Location>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DB_VERLADESTELLEN_Eintrag;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Location location = new Location();
location.setID(Integer.parseInt(cursor.getString(0)));
location.setPlace_id(cursor.getString(1));
location.setName(cursor.getString(2));
location.setLongitude(cursor.getString(3));
location.setLatitude(cursor.getString(4));
location.setTor(cursor.getString(5));
location.setFavorite(cursor.getInt(6));
// Adding contact to list
placeList.add(location);
} while (cursor.moveToNext());
}
// return contact list
return placeList;
}
Well after you edited your question, my answer will be different.
First of all, you should check for Adapter implementation.
It will be easier to handle your scenario and be way more effective.
But then you should try to implement it yourself and come agian if you face any issues.

Android how to hide the table lyout

In my android application a love compatibility test is doing.. where first the details of boys and then details of girls are entered in the same page..one after another. and separate save button for saving boy details and girl details and these data is saved in separate databases. and there is a recall button also there for both boys and girls. When this recall button is pressed the database will opened and from that user can select the name to be checked. When he press the corresponding data has to be entered into the corresponding edittexts. In my case I don't know how to close this tablerow. that mean the database opened.then only the data will go to the corresponding edittext box.
I am giving my code below
MainActivity
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Cursor c = dbb.rawQuery("SELECT * from Data3", null);
int count = c.getCount();
c.moveToFirst();
TableLayout tableLayout = new TableLayout(getApplicationContext());
tableLayout.setVerticalScrollBarEnabled(true);
TableRow tableRow;
TextView textView1, textView2,textView3, textView4, textView5, textView6, textView7, textView8 ;
tableRow = new TableRow(getApplicationContext());
textView1 = new TextView(getApplicationContext());
textView1.setText("First Name");
textView1.setTextColor(Color.BLACK);
textView1.setTypeface(null, Typeface.BOLD);
textView1.setPadding(20, 20, 20, 20);
tableRow.addView(textView1);
textView2 = new TextView(getApplicationContext());
textView2.setText("Last Name");
textView2.setTextColor(Color.RED);
textView2.setTypeface(null, Typeface.BOLD);
textView2.setPadding(10, 10, 10, 10);
tableRow.addView(textView2);
tableLayout.addView(tableRow);
for(Integer j=0; j<count; j++)
{
tableRow = new TableRow(getApplicationContext());
textView3= new TextView(getApplicationContext());
textView3.setText(c.getString(c.getColumnIndex("ffirstname")));
textView3.setClickable(true);
ett1=textView3.getText().toString();
textView4 = new TextView(getApplicationContext());
textView4.setText(c.getString(c.getColumnIndex("fmiddlename")));
textView4.setClickable(true);
ett2=textView4.getText().toString();
textView5 = new TextView(getApplicationContext());
textView5.setText(c.getString(c.getColumnIndex("flastname")));
textView5.setClickable(true);
ett3=textView5.getText().toString();
textView6 = new TextView(getApplicationContext());
textView6.setText(c.getString(c.getColumnIndex("fdayofbirth")));
textView6.setClickable(true);
ett4=textView6.getText().toString();
textView7 = new TextView(getApplicationContext());
textView7.setText(c.getString(c.getColumnIndex("fmonthofbirth")));
textView7.setClickable(true);
ett5=textView7.getText().toString();
textView8 = new TextView(getApplicationContext());
textView8.setText(c.getString(c.getColumnIndex("fyearofbirth")));
textView8.setClickable(true);
ett6=textView8.getText().toString();
textView3.setPadding(10, 10, 10,10);
textView5.setPadding(10, 10, 10, 10);
tableRow.addView(textView3);
tableRow.addView(textView5);
tableLayout.addView(tableRow);
c.moveToNext();
final List<String> list = new ArrayList<String>();
list.add(textView3.getText().toString());
list.add(textView4.getText().toString());
list.add(textView5.getText().toString());
list.add(textView6.getText().toString());
list.add(textView7.getText().toString());
list.add(textView8.getText().toString());
textView3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
c.close();
setContentView(tableLayout);
dbb.close();
}
});
Declare the table layout out side button click and to make it GONE/INVISIBLE do Like this
tablelayout.setVisibility(View.INVISIBLE);//white space will be available
Or
tablelayout.setVisibility(View.GONE);//No white space

How to set onClickListener for the textviews generated dynamically?

Can anyone please guide me on how to setOnClickListener for the TextViews that are generated dynamically.
I have few buttons in my app.Now when a particular button is clicked than some specific text elements are retrieved from the database based on the the number of elements returned corresponding TextViews are generated in order to display the retrieved text elements.
Now the problem that i'm having is that i don't know how to set onClickListner for the dynamically generated TextViews.Following is the piece of code where i'm creating my TextViews.Please guide me on what should i do.thank you
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
catagory = "General";
IndependentDB genData = IndependentDB.getInstance();
genData.open(this);
ArrayList<TextHolder> genList = new ArrayList<TextHolder>();
genList = genData.getAllTextFromGenT();
genData.close();
x = genList.size();
String xstr = new StringBuilder().append(x).toString();
System.out.println(xstr);
mainText = new TextView[x];
textLayout = new LinearLayout[x];
llseperator = new LinearLayout[x];
textLayoutContainer
.setBackgroundResource(R.color.dark_navy_blue);
if (!genList.isEmpty()) {
for (int i = 0; i < x; i++) {
TextHolder firstOne = genList.get(i);
String text = firstOne.getText();
mainText[i] = new TextView(this);
mainText[i].setId(i);
mainText[i].setText("Text");
mainText[i].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mainText[i].setTextSize(25);
mainText[i].setGravity(Gravity.CENTER);
mainText[i].setText(text);
mainText[i].setTextColor(0xFFFFFFFF);
mainText[i].setClickable(true);
mainText[i].setOnClickListener(this);
llseperator[i] = new LinearLayout(this);
llseperator[i].setId(i);
llseperator[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
llseperator[i].setGravity(Gravity.CENTER);
llseperator[i]
.setBackgroundResource(R.drawable.tv_seperator);
textLayout[i] = new LinearLayout(this);
textLayout[i].setId(i);
textLayout[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
textLayout[i].setGravity(Gravity.CENTER);
textLayout[i].addView(mainText[i]);
textLayoutContainer.addView(textLayout[i]);
textLayoutContainer.addView(llseperator[i]);
}// End of for
}// End of If
break;}
You already have onClick() method in Activity class (implemented View.setOnClickListener) so I suggest you to create a new class which implements View.setOnClickListener interface to handle click of TextView.
Try,
class TextClick implements View.setOnClickListener {
#Override
public void onClick(View view) {
TextView tx=(TextView) view;
...
}
}
and set click listener,
TextClick click=new TextClick();
for (int i = 0; i < x; i++) {
TextHolder firstOne = genList.get(i);
String text = firstOne.getText();
mainText[i] = new TextView(this);
mainText[i].setOnClickListener(click);
...
}
It's the same setting on click listeners regardless of if the view was dynamically generated.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dosomething();
}
});
For example. you have a List tvs to store your TextView Objects created by the db result. What you should do is like this:
for(int i =0;i<tvs.count;i++){
tvs.get(i).setOnClickListener(new OnClickListener(){
...
})
}

Categories

Resources