Problems creating a table view in Android - java

I am trying to program a variable table to display data from a database in Android. I am now so far that I can display 2 different lines but the program does not create any more lines and I simply do not find the error.
main Activity:
package com.example.tabellentest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String[] textArray ={" Null "," Eins ", " Zwei ", " Drei ", " Vier ", " Fünf "," SechsHundertZweiUndDreizig ", " Sechs "};
String[] textArray1 ={" 12Null "," 12Eins ", " 12Zwei ", " 12Drei ", " 12Vier ", " 12Fünf "," 12SechsHundertZweiUndDreizig ", " Sechs "};
private TableLayout firstTable;
private TableLayout secondTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandTextView();
this.firstTable = (TableLayout) findViewById(R.id.tableLayout1);
this.secondTable = (TableLayout) findViewById(R.id.tableLayout2);
ExpandTableRow();
}
public TextView CreateTextView(String text, int index){
TextView textView1 = new TextView(getApplicationContext());
textView1.setText(text);
return textView1;
}
public void ExpandTextView (){
LinearLayout linearLayout = findViewById(R.id.linearLayout1);
for( int i = 0; i < textArray.length; i++ )
{
linearLayout.addView(CreateTextView(textArray[i], i));
TextView textView = new TextView(this);
//textView.setText(textArray[i]);
//textView.setId(i);
linearLayout.addView(textView);
}
}
public void ExpandTableRow(){
for (int ab = 2; ab < 8; ab++){
LinearLayout linearLayout2 = findViewById(R.id.linearLayout2);
for( int i = 0; i < textArray1.length; i++ ) {
linearLayout2.addView(CreateTextView(textArray1[i], i));
}
Context context = getApplicationContext();
TableRow row = new TableRow(context);
secondTable.addView(row);
for( int i = 0; i < textArray1.length; i++ ) {
linearLayout2.addView(CreateTextView(textArray1[i], i));
}
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<HorizontalScrollView
android:id="#+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="64dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"/>
</TableRow>
</TableLayout>
</ScrollView>
</HorizontalScrollView>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TableLayout
android:id="#+id/tableLayout2"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
</TableRow>
</TableLayout>
</HorizontalScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
I'm hoping that anybody can give me a tip to find the problem.

Related

Unable to add more than one item in a listview

I am working on a tasks app, for which I created a list view that shows list items consitsting of task names, their priority etc. The data given to the list view is from an sqlite database. I, however, am unable to add more than one item to the list. I have no idea why. I have created a method to do so, but it doesn't seem to work. I don't know if the error is due to the database or my method itself. Even debugging didn't help. Please note that I am using a list adapter since I am using a custom listview.
Code for Activity where list is shown :
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class TaskSummary extends AppCompatActivity {
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
String subtname;
String pri;
String time;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
subtname = getIntent().getStringExtra("subtaskname");
pri = getIntent().getStringExtra("pri");
time = getIntent().getStringExtra("time");
// Using adapter for listview :
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
double working_hours = getIntent().getIntExtra("working_hours", 1);
double working_minutes = getIntent().getIntExtra("working_minutes", 0);
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
}
}
Code for Adapter Class :
package com.example.taskmasterv3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskDetailAdapter extends ArrayAdapter<SubtaskPartTwo> {
private final Context context;
private ArrayList<SubtaskPartTwo> values;
public boolean deleted;
public SubtaskDetailAdapter(Context context, ArrayList<SubtaskPartTwo> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.task_summary_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvlolitaskname);
ImageView ivPri = convertView.findViewById(R.id.ivloliPri);
ImageView ivTime = convertView.findViewById(R.id.ivloliTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).getPri() == "h")
{
ivPri.setImageResource(R.drawable.priority_high);
}
if (values.get(position).getPri() == "m")
{
ivPri.setImageResource(R.drawable.priority_med);
}
if (values.get(position).getPri() == "l")
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).getTime() == "more")
{
ivPri.setImageResource(R.drawable.time_symbol_more);
}
if (values.get(position).getPri() == "med")
{
ivPri.setImageResource(R.drawable.time_symbol_med);
}
if (values.get(position).getPri() == "less")
{
ivPri.setImageResource(R.drawable.time_symbol_less);
}
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(SubtaskPartTwo newSubTask){
ArrayList<SubtaskPartTwo> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
XML code for listview activity :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".TaskSummary">
<!-- hello -->
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/okay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/lvTaskList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Total Working Time (Including Breaks)"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/break_duration_mins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<!-- hello -->
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvWorktimeWithoutBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Work Time Before Each Break"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/hmm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreakAfterEvery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/roboto"
android:text="Break Duration"
android:textColor="#B8AEAE"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/lvTaskList"
app:layout_constraintEnd_toStartOf="#+id/lvTaskList"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="30 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="16dp"
android:text="Start" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
EDIT : Database Code
package com.example.taskmasterv3;
public class TaskInfo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
dbHelper = new DBHelper(this);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
// THE DATABASE PART
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = dbHelper.getdata();
while(res != null && res.moveToNext()){
subtname = res.getString(0);
pri = res.getString(1);
time = res.getString(2);
}
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("subtaskname", subtname);
intent.putExtra("pri", pri);
intent.putExtra("time", time);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("prihigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
boolean delete = getIntent().getBooleanExtra("deleted", false);
if (delete){
}
}
}
}
}
The problem is that you're creating a new ArrayList while the adapter is left using the old one. That's why notifyDataSetChanged() doesn't work because the adapter's backing list has not changed.
To fix this, update the values list directly
public void addANewSubTask(SubtaskPartTwo newSubTask) {
this.values.add(newSubTask);
notifyDataSetChanged();
}
or, add() through the adapter itself.
public void addANewSubTask(SubtaskPartTwo newSubTask) {
add(newSubTask);
notifyDataSetChanged();
}
Even if I add one item, it shows 2 (both the same)
It seems you're adding the new element twice:
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
Just add via adapter only as it notifies as well. Check other places too for such duplicates.

choosing from an integer arraylist

Working in Android studio and as part of a bigger app. I will have an ArrayList of Integers and want to send this to a new instance/screen where each integer in the list displays a string description from which the user can pick whatever entry they want. Once they click it, I want the new instance to send back the integer corresponding to the position in the array of their choice so that I can use it for the next operation.
I made this program as a stand-alone just to get this operation down, but it fails to work (ListChooser has stopped working on load)
my MainActivity.java:
package com.example.kenn.listchooser;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.hardware.camera2.TotalCaptureResult;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;
public class MainActivity extends ListActivity {
private static final String TOTAL_COUNT = "total_count";
public ArrayList<Integer> listValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listValues= new ArrayList<Integer>();
listValues.add(1);
listValues.add(2);
listValues.add(4);
listValues.add(5);
}
public int randomMe(View view) {
Intent randomIntent = new Intent(this, Chooser.class);
randomIntent.putExtra(TOTAL_COUNT, listValues);
startActivity(randomIntent);
int pick=getIntent().getIntExtra (TOTAL_COUNT, 2);
return pick;
}
public void action(View view) {
TextView showCountTextView = (TextView) findViewById(R.id.textViewA);
showCountTextView.setText(Integer.toString(this.randomMe(view)));
} }
my Chooser.java:
package com.example.kenn.listchooser;
import ...
public class Chooser extends ListActivity{
private String TOTAL_COUNT = "total_count";
private TextView text;
private ArrayList<Integer> listHere;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooser);
List<Integer> def = new ArrayList<Integer>();
listHere=getIntent().getIntegerArrayListExtra(TOTAL_COUNT);
text = (TextView) findViewById(R.id.mainText);
// initiate the listadapter
ArrayAdapter<Integer> myAdapter = new ArrayAdapter <Integer>(this,
R.layout.row_layout, R.id.listText, listHere);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
String selectedItem = (String) getListView().getItemAtPosition(position);
Intent randomIntent = new Intent(this, com.example.kenn.listchooser.MainActivity.class);
randomIntent.putExtra(TOTAL_COUNT, selectedItem);
} }
my activity main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context=".MainActivity">
<Button
android:id="#+id/random_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="24dp"
android:layout_marginTop="8dp"
android:background="#color/colorPrimaryDark"
android:onClick="action"
android:text="Choose"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="#+id/textViewA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:text="Alert Dialog"
android:textSize="35dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
my chooser.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mainText"
android:text="My list" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:id="#android:id/list"
android:background="#aaaaaa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:id="#android:id/empty"
android:text="There is no data"
android:textStyle="bold" />
</RelativeLayout>
my row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:orientation="vertical" >
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#ff00ff" />
</LinearLayout>

Dynamically Remove EditText Field in LinearLayout

My problem is that once my editText fields are created, I don't know how to remove them one by one with the other button in my app. I don't really understand the android:id element as it relates to setID() in my java code. I guess my main question is, how do I figure out how to target dynamically created editText views with their id's if I don't know their id's. Here is my code, any help is really appreciated:
Java:
package com.zdowning.decisionmaker;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ScrollView;
import android.widget.Toast;
import java.lang.*;
import static com.zdowning.decisionmaker.R.layout.activity_main;
public class MainActivity extends AppCompatActivity {
public int numberOfLines = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer();
}
});
final Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_Line();
}
});
final Button remove_button = (Button) findViewById(R.id.remove_button);
remove_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Remove_Line();
}
});
}
public void Add_Line() {
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setId(numberOfLines++);
et.setText("Enter Answer #" + numberOfLines++);
ll.addView(et);
numberOfLines++;
Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();
}
public void Remove_Line() {
}
public void getAnswer() {
String[] options = new String[numberOfLines];
EditText text = (EditText)findViewById(R.id.editText2);
options[0] = text.getText().toString();
text = (EditText)findViewById(R.id.editText3);
options[1] = text.getText().toString();
text = (EditText)findViewById(R.id.editText4);
options[2] = text.getText().toString();
int number = (int)(Math.random() * 3);
String answer = options[number];
TextView answerBox = (TextView)findViewById(R.id.textView7);
answerBox.setText(answer);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d4cfcd">
tools:context="com.zdowning.decisionmaker.MainActivity">
<LinearLayout
android:id="#+id/linearLayoutMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Your Question Here"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"/>
<LinearLayout
android:id="#+id/linearLayoutDecisions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Answer #2" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Answer #1" />
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Answer #3" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="#+id/add_button"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="+"
android:textColor="#android:color/background_light"
android:textSize="18sp"/>
<View
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="#+id/remove_button"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="-"
android:textColor="#android:color/background_light"
android:textSize="18sp"
android:layout_margin="10dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="DECIDE!"
android:textColor="#android:color/background_light"
android:textSize="18sp"
android:layout_centerInParent="true" />
</RelativeLayout>
<TextView
android:id="#+id/textView7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_margin="20dp"
android:textColor="#android:color/black"
android:textSize="36sp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
There is no relationship between android:id and your setID.
Check this answer to unsderstand more about that.
Anyway, one approach to achieve to remove a generated line could be based on the children index of your LinearLayout like this:
private LinearLayout mEditTextContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mEditTextContainer = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
...
}
public void addLine() {
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setText("Enter Answer #" + (mEditTextContainer.getChildCount()+1));
mEditTextContainer.addView(et);
Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();
}
public void removeLine() {
mEditTextContainer.removeViewAt(mEditTextContainer.getChildCount()-1);
}

Read View's children while initializing View

This View is supposed to make a Button for each LinearLayout inside itself, and put that LinearLayout inside a ScrollView. I think the problem is that the LinearLayouts don't exist yet, since they are created AFTER initializing this view. Therefore getChildCound() returns zero. You could work around this by hard coding the number of Buttons or getting it from a XML attribute, but you can't put the LinearLayouts in the ScrollViews, when there are no LinearLayouts. Is there a way to work around this?
code:
package mika.actual;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import java.util.ArrayList;
public class AccordionWidget extends LinearLayout{
public AccordionWidget(Context c, AttributeSet attrs) {
super(c, attrs);
final Context context = c;
final int count = this.getChildCount();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
String[] btns = getResources().getStringArray(R.array.buttons);
ArrayList<LinearLayout> lls = new ArrayList <> (count);
for(int i = 0; i < count; i++){
View child = this.getChildAt(i);
if (child instanceof LinearLayout) {
lls.add((LinearLayout)child);
}
}
for(int i = 0; i < lls.size(); i++){
if(btns[i] == null){
Log.e("error: ", "Please add more Button lables to the strings.xml file.");
}
final Button btn = new Button(context);
final LinearLayout ll = lls.get(i);
final ScrollView sv = new ScrollView(context);
final int col_pressed = a.getColor(R.styleable.accordion_backgroundColorPressed, Color.BLACK);
final int col_unpressed = a.getColor(R.styleable.accordion_backgroundColorUnpressed, Color.YELLOW); //Black and yellow, black and yellow...
LayoutParams btnparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
LayoutParams swparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
LayoutParams llparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
btn.setText(btns[i]);
btn.setBackgroundColor(col_pressed);
llparams.weight = 1f;
btn.setLayoutParams(btnparams);
ll.setLayoutParams(llparams);
sv.setLayoutParams(swparams);
ll.setOrientation(LinearLayout.VERTICAL);
sv.setVisibility(View.GONE);
this.addView(sv);
this.addView(btn);
sv.addView(ll);
btn.setOnClickListener(new OnClickListener() {
private boolean btnstate = false;
#Override
public void onClick(View v) {
if (btnstate) {
btn.setBackgroundColor(col_pressed);
sv.setVisibility(View.VISIBLE);
btnstate = true;
} else {
btn.setBackgroundColor(col_unpressed);
sv.setVisibility(View.GONE);
btnstate = false;
}
}
});
}
a.recycle();
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<mika.actual.AccordionWidget
xmlns:accordion="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
accordion:text_color="#color/text_color"
accordion:backgroundColorPressed="#color/button_pressed"
accordion:backgroundColorUnpressed="#color/button_not_pressed"
android:id="#+id/swaggy"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
</mika.actual.AccordionWidget>
The idea is that you need to put your logic into onLayout
Something like this:
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final Context context = c;
final int count = this.getChildCount();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
String[] btns = getResources().getStringArray(R.array.buttons);
ArrayList<LinearLayout> lls = new ArrayList <> (count);
for(int i = 0; i < count; i++){
View child = this.getChildAt(i);
if (child instanceof LinearLayout) {
lls.add((LinearLayout)child);
}
}
.......
See this
Make sure that you call child.layout() for each child inside this method.
You can create custom LinearLayout inside ScrollView:
<ScrollView>
<LinearLayout android:id="#+id/parent"/>
</ScrollView>
Then Create java class for your layout and inflate it.
See this

android TableLayout adding rows dynamically adds only the last row

after reading tens of threads on StackOverflow.
I'm trying to add dynamically rows to a table-layout.
The problem is, the only one row is added dynamically, and it is spanning on all of the page.
This is my code:
package com.example.trashproject;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
public class MainActivity extends FragmentActivity{
private static final int ROWS =2;
private static final int COLS = 10;
private static final String TAG = null;
private TableLayout mTable;
private View[][] mCircles;
private boolean[][] mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeTable();
}
private void makeTable() {
mTable = (TableLayout) findViewById(R.id.table);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams();
rowParams.width = LayoutParams.WRAP_CONTENT;
rowParams.height = LayoutParams.WRAP_CONTENT;
mCircles = new View[ROWS][COLS];
TableRow row;
for (int i = 0; i < ROWS; i++) {
row = new TableRow(this);
row.setLayoutParams(rowParams);
for (int j = 0; j < COLS; j++) {
mCircles[i][j] = new View(this);
mCircles[i][j].setBackgroundResource(R.drawable.small_circle);
row.addView(mCircles[i][j]);
}
mTable.addView(row);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT"/>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT"/>
</TableRow>
</TableLayout>
</LinearLayout>
calendar_month_grid.xml:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="1dp"
/>
small_circle.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size android:width="15dp"
android:height="1dp"/>
<solid android:color="#android:color/holo_green_light"/>
</shape>
Your help appreciated...
I think it is the "View" that is giving you a problem. Try replacing it with an ImageView (try it) and I think it will work. If you really want View (not sure why) then set the min height and min width to something like 10dp.
It happened to me once that empty View with wrap content spans the whole page. It is pushing the rest of your rows out of the screen

Categories

Resources