I've been searching on this around here but I cant seem to find the right source/answer for this.
I want to pull data from my SQLite DB and display it in the layout (with TextViews), according to the number of elements I have in the DB.
How do I add TextViews to the layout "on the fly"?
hardcoding textviews is very simple but I have no idea how to it dynamically.
thanks for any help!
here is my class:
package android.GUI;
public class Shifts extends Activity implements OnClickListener {
String dbTime;
DBAdapter DB = new DBAdapter(this);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shifts);
LinearLayout layout = (LinearLayout) findViewById(R.id.shifts);
TextView text = new TextView(this);
DB.open();
Cursor c = DB.getAllShifts();
if (c.moveToFirst()) {
do {
} while (c.moveToNext());
layout.addView(text);
text.setText(showDB(c));
}
DB.close();
}
public String showDB(Cursor c) {
dbTime = c.getString(1) + "\n" + c.getString(2);
return dbTime;
}
You have used
DBAdapter DB = new DBAdapter(this);
The line before Activity is initiated. So this keyword is causing is null pointer exception.Please write this line on the method onCreate() before db.open();
Adding dynamically:
TextView tv = new TextView(this);
tv.setText("TaskID");
TextView tv1 = new TextView(this);
task = new EditText(this);
task.setMaxWidth(100);
task.setMinHeight(100);
tv1.setText("Task");
id = new EditText(this);
id.setMaxHeight(10);
TextView tv2 = new TextView(this);
name = new EditText(this);
name.setMaxHeight(1);
tv2.setText("Name");
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.VERTICAL);
l.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setContentView(l);
l.addView(tv);
l.addView(id);
l.addView(tv1);
l.addView(task);
l.addView(tv2);
You can use ListView and SimpleCursorAdapter, which automatically creates views for your DB records. http://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/
Or if you still want to manage it by yourself you can use following:
// In onCreate method.
// E.g. your topmost view is LinearLayour with id 'layout'.
LinearLayout layout = findViewById(R.id.layout);
TextView text = new TextView(this);
text.setText("Hello, I'm dynamically added text view");
layout.addView(text).
What you are looking for is a ListView. To populate data from the db into the list, use a SimpleCursorAdapter
Related
I have looked through other Posts as much as I can, and though this may be a simple problem, for the life of me I can't figure out how to make this work. I have a Database of Customers, including their names, address, etc.
I would Like to be able to select one of the customers from my custom ListView, and View all of their Database information in A separate Activity. Currently, I cant make it give me anything past the first record.
Any advice would be very helpful if you can see what I am doing wrong.
I am fairly new to Java so Please take it easy on me :P My best guess right now is that I need to create a new cursor but I'm a bit lost.
Code attached below.
Database Viewer.java
public class DatabaseViewer extends AppCompatActivity{
TextView DisplayName;
TextView DisplayID;
TextView DisplayMarks;
TextView DisplayAddress;
DatabaseHelper mydb = new DatabaseHelper(this);
ListView customerlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_viewer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
customerlist = (ListView) findViewById(R.id.ListViewCustomers);
populateDatabase();
customerlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
DisplayID = (TextView) findViewById(R.id.TVCUSTOMERNAME);
DisplayMarks = (TextView) findViewById(R.id.TVADDRESS);
DisplayName = (TextView) findViewById(R.id.TVID);
DisplayAddress = (TextView) findViewById(R.id.TVMARKS);
// NEED TO MAKE A CURSOR THAT GETS ALL ROWS NOT COLUMNS LIKE BELOW.
int c1 = mydb.getallrows().getPosition();
// 35 ROWS 4 COLUMNS.
String item = String.valueOf(parent.getItemAtPosition(i));
Intent clientViewIntent = new Intent(DatabaseViewer.this, ClientViewer.class);
clientViewIntent.putExtra("Client ID", c1);
startActivity(clientViewIntent);
}
});
}
private void populateDatabase(){
Cursor c = mydb.getallrows();
customerlist = (ListView) findViewById(R.id.ListViewCustomers);
String[] fromfieldnames = new String[] {DatabaseHelper.COL_1, DatabaseHelper.COL_2, DatabaseHelper.COL_3, DatabaseHelper.COL_4};
int[] tofieldnames = new int[] {R.id.TVCUSTOMERNAME, R.id.TVADDRESS, R.id.TVMARKS, R.id.TVID};
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.custom_db_viewer_row, c, fromfieldnames, tofieldnames, 0);
customerlist.setAdapter(adapter);
}
public void OnClientLongPress(){
// Function to Open up Client Information in a new activity.
// Step 1, Use data from Client to pull up Full Client Records.
// Step 2, Send Data in Intent Extras.
Intent clientVIewIntent = new Intent(DatabaseViewer.this, ClientViewer.class);
clientVIewIntent.putExtra("Client ID", customerlist.getSelectedItemId());
startActivity(clientVIewIntent);
}
ClientViewer.java
public class ClientViewer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_viewer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.inflateMenu(R.menu.menu_invoice_creator);
Bundle NameIntentData = getIntent().getExtras();
if (NameIntentData==null){
return;
}
int IntentDataID = NameIntentData.getInt("Client ID");
String IntentDataName = NameIntentData.getString("Client Name");
String IntentDataAddress = NameIntentData.getString("Client Address");
final TextView IDBar = (TextView) findViewById(R.id.ClientViewerIDTV);
final TextView Namebar = (TextView) findViewById(R.id.ClientViewerNameTV);
final TextView AddressBar = (TextView) findViewById(R.id.ClientViewerAddressTV);
Namebar.setText(Integer.toString(IntentDataID));
IDBar.setText(IntentDataName);
AddressBar.setText(IntentDataAddress);
}
}
Thanks so much for your time and effort guys. Really cant wait to hear back from you.
TextView textview =((TextView)view.findViewById(R.id.tvInVisitorName)).getText().toString();
Use this on onClick and get your text view data like this.
Get the ID of client onClick which is same and unique as stored in DB
Then, pass it to another activity
Pass id parameter and get all the data based on that ID and display..don't pass all the data via intent just pass one key and get all data and display
Hope this will help you
Thanks!!!
SOLVED, Largely in thanks to Anamica!
The code
String a = Long.toString(l);
Intent clientViewIntent = new Intent(DatabaseViewer.this,
ClientViewer.class);
clientViewIntent.putExtra("Client ID", a);
startActivity(clientViewIntent);
Got me where I needed to be.(Shows the Id of Item) Thanks again Guys!
I have created EditText textView Buttons using for loops in MainActivity.Java not in activity_main.Xml.
I want to do arithmetic calculations on the inputted numbe rthrough EditText.
Here is my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int MY_BUTTON = 9000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
final LinearLayout my_root = (LinearLayout)findViewById(id.Root);
for(int i =1;i<=5;i++){
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams ParamLayout =
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
ParamLayout.gravity=Gravity.CENTER;
layout.setLayoutParams(ParamLayout);
TextView tvi = new TextView(MainActivity.this);
tvi.setText("Sub " + String.valueOf(i));
tvi.setId(i);
tvi.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tvi.setTextSize(24);
tvi.setPadding(0,0,5,3);
tvi.setMinWidth(300);
tvi.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD),Typeface.ITALIC);
layout.addView(tvi,0);
EditText etCrediti = new EditText(this);
etCrediti.setHint("Credit ");
etCrediti.setMinWidth(300);
etCrediti.setId(50+i);
etCrediti.setMinLines(1);
etCrediti.setMaxLines(1);
layout.addView(etCrediti);
EditText etPointsi = new EditText(this);
etPointsi.setText(" ");
etPointsi.setMinWidth(300);
etPointsi.setId(100+i);
etPointsi.setMinLines(1);
etPointsi.setMaxLines(1);
layout.addView(etPointsi);
my_root.addView(layout);
}
Button btn = new Button(this);
btn.setText("Submit");
btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// b.setId(MY_BUTTON);
//btn.setOnClickListener(this);
btn.setGravity(Gravity.CENTER);
btn.setTextSize(24);
btn.setWidth(300);
btn.setId(MY_BUTTON);
btn.setOnClickListener(this);
my_root.addView(btn);
}
I guess what you wanted to do is a calculator...
You must have for this two editTexts and a button.
You should also have another TextView for the result.
You need to set the button on click to the function that calculate.
In your on create set b1 and b2 to the views editText.
b1= (EditText)findViewById(R.id.editText1);
Then to get the text value:
int n1= Integer.pharseInt(b1.getText.toString());
Then just do the calc and set the result for the TextView text.
findViewById (R.id.textView1).setText(result);
I also add a link for tutorial below:
https://www.google.co.il/amp/www.androidauthority.com/build-a-calculator-app-721910/amp/
From my experience with EditText in Android, I had to convert the number-string to different type that can be calculated with by Java.
When you expect a 'double' you can use the following Java code-snippet:
EditText myNumericTextfield = ...
...
// fill value of myNumericTextfield
...
double valueOfMyNumericTextfield = 0.0;
try {
valueOfMyNumericTextfield = Double.parseDouble(myNumericTextfield.toString());
} catch (NumberFormatException e) {
System.err.println(e);
throw new Exception(e);
}
...
You can also convert the string myNumericTextfield to an int, or long.
In my main.xml I have a LinearLayout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linearMain"
>
</LinearLayout>
Then, inside my Main.java I am retrieving values from the DB (name and price of an item). Then, I dynamically created my form using the below code:
Cursor cursor = mydb.getAllJuice();
lm = (LinearLayout) findViewById(R.id.linearMain);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
while (cursor.moveToNext()) {
int cid = cursor.getInt(0);
String id = Integer.toString(cid);
String name = cursor.getString(1);
String price = cursor.getString(2);
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(name+" ");
ll.addView(product);
// Create TextView
TextView pricetxt = new TextView(this);
pricetxt.setText(" "+price);
ll.addView(pricetxt);
// Create TextView
TextView currency = new TextView(this);
currency.setText(" LL ");
ll.addView(currency);
// Create TextView
TextView qtylabel = new TextView(this);
qtylabel.setText("QTY ");
ll.addView(qtylabel);
EditText qty = new EditText(this);
qty.setMinLines(1);
qty.setMaxLines(3);
ll.addView(qty);
lm.addView(ll);
}
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
final Button btn = new Button(this);
// Give button an ID
int j = 122;
btn.setId(j+1);
btn.setText("Add To Cart");
// set the layoutParams on the button
btn.setLayoutParams(params);
//Add button to LinearLayout
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
The user will be able to enter the number of items and consequently onClick of the button a TextView will be manipulated.
To fill this textview I will need to loop on all the items that were created to check the price and check how the number that the user entered. I tried using the below code, however I am not able to access the specific item that I want as I have in each row 2 TextView and 1 editText:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// code will be here
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
total = 0 ;
View v1 = null;
for(int i=0; i<lm.getChildCount(); i++) {
v1 = lm.getChildAt(i);
}
}
});
How can I access the different element in the v1?
You can use tag parameter of your Views (TextView, EditText etc.): setTag(Object) . Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure. Check Android documentation for more details.
P.S. Instead to use your approach, you can use RecyclerView (or older ListView) with ViewHolder. This already mentioned in comments.
Answer to your question:
The problem is that your "product", "pricetxt", "btn" variables are local variables and gets garbage collected after your current loop iteration is over.
Well you can implement view holder pattern in your project.
Create a class named ViewHolder
class ViewHolder{
LinearLayout ll;
TextView product;
TextView pricetxt ;
TextView currency ;
TextView qtylabel ;
EditText qty ;}
public ViewHolder(LinearLayout ll TextView product TextView pricetxt TextView currency TextView qtylabel EditText qty)
{
this.l1= l1;
this.product=product;
this.pricetxt=pricetxt;
this.currency = currency;
this.qtylabel = qtylevel;
this.qty = qty;
}
This class can hold all your data by passing all these parameters (qty, pricetxt, etc).
Now you have to maintain a List for this ViewHolder Object at the top. You can do this as-
List myList<ViewHolder> = new ArrayList<ViewHolder>();
At the end of every iteration, create and add the ViewHolder object;
You can do this as follows
ViewHolder currentView = new ViewHolder(l1.product,pricetxt,currency,qtylabel,qty);
myList.add(currentView);
myList.add(currentView);
You can access any ViewHolder object maintained inside the list at position "index" as
myList.get(index);
Or the EditText "qty" as
myList.get(index).qty;
In this way you can access your created EditTexts and TextView even after the loop iteration is over.
My Suggestion:- No one does it in this way. As suggested some guys over here you should you android implement recommended RecyclerView which is much more efficient than the current implementation. In cases you can even you ListView.
I have some problems passing and displaying values from the MainActivityClass to another MyActivityClass. So I learned here how to pass values from one class to another. Here's the method of MainActivity class which contains the intent to the other activtiy:
Intent intent = new Intent(this, AddAptActivity.class);
Bundle extras = new Bundle();
EditText editText = (EditText) findViewById(R.id.edit_address);
String message = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.edit_name);
String message2 = editText2.getText().toString();
extras.putString(EXTRA_MESSAGE, message);
extras.putString(EXTRA_MESSAGE1, message2);
intent.putExtras(extras);
startActivity(intent);
and then in MyActivityClass receiving the values:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String message = extras.getString(MainActivity.EXTRA_MESSAGE);
String message2 = extras.getString(MainActivity.EXTRA_MESSAGE2);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
TextView textView2 = new TextView(this);
textView2.setTextSize(40);
textView2.setText(message2);
setContentView(textView, textView2);
}
but the setContentView() method doesn't want to accept more than one value. How can I display the other value in another textview and then display it???
I think I don't understand how to display values with setContentView... Please help me, as I am new in Android programming (just finished the 1st tutorial one week ago).
You can use a ViewGroup such as a LinearLayout or RelativeLayout then add TextViews to the same and then setContenView(linearlayout);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
TextView textView2 = new TextView(this);
ll.addView(textView);
ll.addView(textView2);
setContenView(ll);
setContentView() takes one Layout, either a View or a layout resource ID. You can pass in a LinearLayout, RelativeLayout, etc. to setContentView() which can contain any number of views. Probably a better approach would be to build a layout XML file that contains your view higherarchy then set it using setContentView(R.layout.someLayout);
see more info here:
http://developer.android.com/guide/topics/ui/declaring-layout.html
You can only add a view to your setContentView(...). Best create a new View that contains both TextView and then setContentView to this new View.
RelativeLayout layout= new RelativeLayout(this);
layout.addView(textView1);
layout.addView(textView1);
setContentView(layout);
Several things wrong here so let's start from the beginning...
but the setContentView() method doesn't want to accept more than one value. There is a method of it which takes a second param but that is for layout params.
Nope, if you look at the docs that's all it takes and you can't force it to take more (without rewriting the activity class).
I think I don't understand how to display values with setContentView.
I don't think so either but you will.
You just set a layout (typically) with this method. You are creating Views dynamically which is ok but you don't need to. If you do then you need to add them to your inflated layout (the one you set in setContentView()). You can just add them to your layout (someLayout.xml) then get a reference to them
So it may look something like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* call this first and it will save you some grief
*/
where someLayoutFile is the xml file without the .xml extension
setContentView(R.layout.someLayoutFile);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String message = extras.getString(MainActivity.EXTRA_MESSAGE);
String message2 = extras.getString(MainActivity.EXTRA_MESSAGE2);
TextView textView = (TextView) findViewById(R.id.someID); // where someId is the id you give a TextVIew in your xml file
textView.setTextSize(40);
textView.setText(message);
// create another TextView in your xml and do the same with that using the appropriate layout
See this page in the docs for more information
I am having issues in TableLayout, width issues. I tried searching a lot, but all I get is solution using xml. I am doing it programmatically. Here is what I am doing
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableLayout table = new TableLayout(this);
table.setStretchAllColumns(true);
table.setShrinkAllColumns(true);
TableRow tableTitle = new TableRow(this);
tableTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TableRow name = new TableRow(this);
TableRow password = new TableRow(this);
TableRow button = new TableRow(this);
TextView empty = new TextView(this);
TextView title = new TextView(this);
title.setText("Hello table layout");
title.setGravity(Gravity.CENTER_HORIZONTAL);
TextView txtUname = new TextView(this);
txtUname.setText("Username");
TextView txtPass = new TextView(this);
txtPass.setText("Password");
EditText uname = new EditText(this);
EditText pass = new EditText(this);
Button login = new Button(this);
login.setText("Login");
name.addView(txtUname);
name.addView(uname);
password.addView(txtPass);
password.addView(pass);
button.addView(empty);
button.addView(login);
table.addView(name);
table.addView(password);
table.addView(button);
table.setColumnShrinkable(0, true);
setContentView(table);
}
I want to shrink first column. What should I add in this code?
Anyone help!
You should consider moving your to layout xml file. This would make your life way easier.
To make only first column shrinkable replace setShrinkAllColumns(true)
with setColumnShrinkable(0, true).