friends i want to create a app which have create text view from the JSON array
in example
"name":"Lenovo","price":"5000","description":"2 gb ram","type":"mobile"
it will be change it know the values and create a text field with this titles name ,type,price
Try this..
Create a layout with LinearLayout
<LinearLayout
android:orientation="vertical"
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
Then iterate your json
LinearLayout linearLayout= (LinearLayout)findViewById(R.id.linear);
linearLayout.removeAllViews();
Iterator<String> iter = new JSONObject("JSON STRING").keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
TextView textView= new TextView(this);
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 48));
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setText(key+" : "+value.toString());
linearLayout.addView(textView);
} catch (JSONException e) {
// Something went wrong!
}
}
You need to consume your json somehow, use framework like gson or class like JSONObject (find on web if you need to).
Assume you have data to put in TextView so next you need to create your TextView in your activity:
TextView textView = new TextView(this); //it need context
textView.setText(yourJSONObject.getText());
Last part is to put TextView to your layout, (in this case linearLayout).
yourLinearLayout.addView(addView(textVIew))
Related
I have a function who gets a list of products from a webpage, and I want to add a row in a tableLayout for each element of the list.
public void getProductsOfCategory() throws IOException{
new Thread(){
public void run(){
//background code...
try {
Bundle extras = getIntent().getExtras();
String categoryName = extras.getString("categoryName");
HttpGet httpget = new HttpGet("http://romal.hopto.org/foodadvisor/users/getProductsOfCategory.json?category="+categoryName);
HttpResponse httpresp = httpClient.execute(httpget);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
httpresp.getEntity().writeTo(baos);
final String content = new String(baos.toByteArray());
CategoryActivity.this.runOnUiThread(new Runnable(){
public void run(){
//foreground code (UI)
//update user interface, for example, showing messages
try {
JSONObject jObject = new JSONObject(content);
JSONArray productsList = jObject.getJSONArray("response");
for(int i=0; i<productsList.length();i++){
JSONObject product = productsList.getJSONObject(i);
JSONObject productData = product.getJSONObject("Product");
String productDescription = productData.getString("description");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
In my layout xml file I have defined the table layout like this:
<TableLayout
android:id="#+id/tableOfProducts"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/productDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:paddingBottom="7dp"
android:paddingLeft="14dp"
android:paddingRight="14dp"
android:paddingTop="7dp"
android:textSize="20dp" />
</TableLayout>
I imagine I have to add some extra code in the for loop, adding a new row and a new textview for each element, and setting the content of the text view with the string that has the description of the product.
How can I do this?
Check this out, this is the general way of creating table rows dynamically. Modify it accordingly
XML file
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_table"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</TableLayout>
JAVA PART
TableLayout t1;
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
Create table row header to hold the column headings
TableRow tr_head = new TableRow(this);
tr_head.setId(10);
tr_head.setBackgroundColor(Color.GRAY); // part1
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
I'm adding two data sections to the table row
TextView label_hello = new TextView(this);
label_hello.setId(20);
label_hello.setText("HELLO");
label_hello.setTextColor(Color.WHITE); // part2
label_hello.setPadding(5, 5, 5, 5);
tr_head.addView(label_hello);// add the column to the table row here
TextView label_android = new TextView(this); // part3
label_android.setId(21);// define id that must be unique
label_android.setText("ANDROID..!!"); // set the text for the header
label_android.setTextColor(Color.WHITE); // set the color
label_android.setPadding(5, 5, 5, 5); // set the padding (if required)
tr_head.addView(label_android); // add the column to the table row here
After adding the columns to the table row its time to add the table row the the main table layout that we fetched at the start
tl.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, //part4
LayoutParams.MATCH_CONTENT));
EDIT : YOU CAN DO THE FOLLOWING IN YOUR CODE
TextView[] textArray = new TextView[productsList.length()];
TableRow[] tr_head = new TableRow[productsList.length()];
for(int i=0; i<productsList.length();i++){
JSONObject product = productsList.getJSONObject(i);
JSONObject productData = product.getJSONObject("Product");
String productDescription = productData.getString("description");
//Create the tablerows
tr_head[i] = new TableRow(this);
tr_head[i].setId(i+1);
tr_head[i].setBackgroundColor(Color.GRAY);
tr_head[i].setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically
textArray[i] = new TextView(this);
textArray[i].setId(i+111);
textArray[i].setText(productDescription);
textArray[i].setTextColor(Color.WHITE);
textArray[i].setPadding(5, 5, 5, 5);
tr_head[i].addView(textArray[i]);
// Add each table row to table layout
tl.addView(tr_head[i], new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
} // end of for loop
Creating the TextView and TableRow array are not necessary. You can just include part1, part2, part3 (if you need more than 1 field) and part4 inside your for loop.
Look, i think you have to modify your xml to adding rows to your tableview:
First, the inflater:
LayoutInflater inflater = mContext.getLayoutInflater();
or in this way:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Here you can set up the layoutparameters from your tableview and the rowview.
//Maybe you don't have to modify nothing from the parameters of your tableview so
//you can dismiss it.
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
//Here were we take the tablelayout from your xml
TableLayout tableLayout = (TableLayout)inflater.inflate(R.layout.tableOfProducts, null);
//Like a told you before, maybe you don't need set the parameters of the tablelayout
//so you can comment next line.
tableLayout.setLayoutParams(this.tableParams);
TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(this.tableParams);
//Here you have to create and modify the new textview.
TextView textView = new TextView(context);
textView.setLayoutParams(this.rowParams);
tableRow.addView(textView);
tableLayout.addView(tableRow);
If you need more help, tell me, if it is helpful, rating me!!! ;) Un saludo Gallega! O como se dice en gallego: una aperta!
for this, you have to create one xml file for row, then you have to modify your layout.xml file like
<ScrollView>
<LinearLayout orientation=vertical id="+id/rowHolder">
</LinearLayout
</scrollview>
Then in for loop, inflate the row layout and add it runtime to rowHolder object.
I'm new myself to Android, and after years with Python/Gtk, I'm lost if I can't think in terms of Model/View/Presenter.
one useful approach I managed to apply, it puts me back into that optics, and even if it's not relative to a Table, I'm quite sure it can be extended to that (I guess this page would be a good start, for me too).
start by declaring the two objects in your fragment (or activity):
List<String> stringList; // think of it as the model.
ArrayAdapter<String> listAdapter; // and this would be the presenter
define the model in the fragment constructor:
stringList = new ArrayList<>();
next, when the onCreateView of my fragment is invoked, I do this (edit correspondingly if you're using Activity, not Fragment):
View rootView = inflater.inflate(R.layout.fragment_taxonomy, container, false);
ListView mainListView = rootView.findViewById(R.id.taxonomy_results);
// Create ArrayAdapter using the string list. think of it as the presenter.
// see how it's being handled a model and a view.
listAdapter = new ArrayAdapter<>(
rootView.getContext(), R.layout.textrow, stringList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
textrow.xml is an extra layout which is being reused every time I add an element to the stringList model.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
in the rest of the code, I only "talk" to listAdapter, and I only need its two add and clear methods, to add elements, or for clearing the list.
There are many ways to do this. First, for minimizing your code, create an XML file that initializes the TableRow and its attribute (TextView should be also included). Then, in your target XML file that is linked to the activity, you have to create only the TableLayout.
In the main, create LayoutInflater that will link the items to gather. Then, create as much as you can of the number of TableRow. In the end, each TableRow that has a unique variable should be linked using addView() to the TableLayout that you have created in the XML.
For more, see here. https://github.com/AreejTurky/Dynamic-TableRow-Generation
I am making a word game in which each a user has multiple guesses, each one made up of multiple TextViews. So far my code reads:
TextView[] guess1 = new TextView[numTextViews];
guess1[0] = (TextView) findViewById(R.id.Guess1_1);
guess1[1] = (TextView) findViewById(R.id.Guess1_2);
guess1[2] = (TextView) findViewById(R.id.Guess1_3);
guess1[3] = (TextView) findViewById(R.id.Guess1_4);
guess1[4] = (TextView) findViewById(R.id.Guess1_5);
with the xml looking like:
<TextView
android:id="#+id/Guess1_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="#string/guessChar" />...
which repeats with android:id= changing.
I am going to be repeating myself if I type out TextView[] guess2 and all its elements.
What is a better way to go about this?
Would it be better to create all the TextViews programmatically as they are so similar?
This is how you can iterate through your views without the use of ids in repetitive code:
LinearLayout ll = (LinearLayout) findViewById(R.id.layout_containing_textviews);
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i).getClass() == TextView.class) {
guess1[i] = (TextView)ll.getChildAt(i);
}
}
Make sure to tweak this in case you have non-TextView views since the i index will not be consecutive in that case. You can use another counter just for the TextViews.
Now if your layout has only TextViews, you don't even need an array. You can use that layout as a container/array the way it's used in the snipped above.
Do you know what is the amount of guesses for each text view?
I would suggest you to use reflection
Class clazz = R.id.class; // get the R class
Field f = clazz.getField("Guess1_" + "1");
int id = f.getInt(null); // pass in null, since field is a static field.
TextView currcell = (TextView) findViewById(id);
in this case it will bring the Guess1_1
for you case:
for (int i =0; i < numTextViews; i++)
{
Class clazz = R.id.class;
Field f = clazz.getField("Guess1_" + Integer.toString(i+1));
int id = f.getInt(null);
guess[i] = (TextView)findViewById(id);
}
but this only bring you the first array of Guess1 you need to convert it to generic code..
so some problems can be occur.. so read it with the xml as you have right now would be the easiest way..
Edit:
If the all textView have the same attributes you can also create it programmatically
LinearLayout view = new LinearLayout(this); // create new linear layout
view.setOrientation(LinearLayout.HORIZONTAL); // optional.. so the
// view will be horizontaly
view.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)); // set the layout
// height and width
for (int i = 0; i < numOf ; i ++)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
guess[i] = new TextView();
guess[i].setLayoutParams(lp);
guess[i].setID(i+1);
}
You could either create the textViews programmatically (and use inflate if you wish to use some xml too), or you could use the getIdentifier method , for example:
private static final String ID_FORMAT="Guess1_%d";
...
for(int i=0;i<10;++i)
{
String id=String.format(FORMAT,i);
TextView tv = (TextView) findViewById(getResources().getIdentifier(id, "id", getPackageName()));
//...
}
same goes if you wish to do a loop within a loop.
If the layout has a lot of views, I would suggest using an adapterView (listView,gridView,...) instead, and avoid creation of so many views (either programmatically or by xml).
I want to add a LinearLayout wrapped around a TextView and Button programmatically. I want it to take a String array and then using the length of the string array, add that many TextViews each with their own button.
So first:
String [] s = { .... the values ....}
int sL = s.length;
TextView t1 = new TextView (this);
// then somehow create t2, t3... etc. matching the length of the String array.
Is this the best way to do this or is there another way to do this? For some context, it's a quiz app and I've created a list of categories inside resources as values and I'm trying to programmatically get my app to create as many TextViews as there are categories then set each TextView to each category then get each button to take the user to that category of questions.
You are starting it right, just do a for loop and add textviews to your linearlayout.
// You linearlayout in which you want your textview
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
String [] s = { .... the values ....}
int sL = s.length;
TextView textView = null;
// For later use if you'd like
ArrayList<TextView> tViews = new ArrayList<TextView>();
for (int i = 0; i < sL; i++)
{
textView = new TextView(this);
textView.setText(s[i]);
linearLayout.addView(textView);
tViews.add(textView);
}
There is nothing wrong with this way of doing it. If you want to use these textview later on (set text for them or something) store them in an Array of some kind. Edited code
You can do the following:
for(int i=0;i<s.length;i++){
TextView t=new TextView(this);
t.setText(s[i]);
yourLinearLayout.addView(t);
}
But I really think that using a ListView would be better for performance ;)
Hello I set values in ArrayList Now how can I store that values in different textviews.
For Example:
ArrayList<String> mylist =new ArrayList<String>();
for(int i=0;i<mylist.size();i++)
{
//Here mylist contains 10 values and I have 10 different textviews. Now How can i add values 1 to 10 in different textview. set value to First textview 1,second textview to 2 etc.
}
Please Help me to find this.
This is the way::
TextView []tv=new TextView[10];
tv[0]=(TextView)findViewById(R.id.____);
tv[1]=(TextView)findViewById(R.id.____);
tv[2]=(TextView)findViewById(R.id.____);
tv[3]=(TextView)findViewById(R.id.____);
tv[4]=(TextView)findViewById(R.id.____);
tv[5]=(TextView)findViewById(R.id.____);
tv[6]=(TextView)findViewById(R.id.____);
tv[7]=(TextView)findViewById(R.id.____);
tv[8]=(TextView)findViewById(R.id.____);
tv[9]=(TextView)findViewById(R.id.____);
for(int i=0;i<mylist.size();i++)
{
tv[i].setText(mylist.get(i));
}
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
ArrayList<String> mylist = new ArrayList<String>();
mylist.add("1");
mylist.add("2");
mylist.add("3");
mylist.add("4");
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < mylist.size(); i++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(lparams);
tv.setText(mylist.get(i));
layout.addView(tv);
}
And XML File
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
If u have the same no of text views and the data then create a array of views then use for loop as:
ArrayList<String> mylist =new ArrayList<String>();
mylist.add("1st");
mylist.add("2nd");
mylist.add("3rd");
mylist.add("4th");
// mylist.add("5th");
one=(TextView)findViewById(R.id.textView1);
two=(TextView)findViewById(R.id.textView2);
three=(TextView)findViewById(R.id.textView3);
four=(TextView)findViewById(R.id.textView4);
ArrayList<TextView>text=new ArrayList<TextView>(Arrays.asList(one,two,three,four));
for(int i=0;i<mylist.size();i++)
{
text.get(i).setText(mylist.get(i));
//Here mylist contains 10 values and I have 10 different textviews. Now How can i add values 1 to 10 in different textview. set value to First textview 1,second textview to 2 etc.
}
Then you dont need of for loop. just set text to Your text views manually
as
ArrayList<String> mylist =new ArrayList<String>();
TextView txt1 = (TextView)findviewbyId(R.id.txt1);
txt1.setText(mylist.get(0);
....//upto 10 textViews
TextView txt10 = (TextView)findviewbyId(R.id.txt10);
txt10.setText(mylist.get(9);
You could try something like this:
for(int i=0;i<mylist.size();i++)
{
TextView tv = findViewById(getResources().getIdentifier("textView"+i, "id",getPackageName()));
tv.setText(mylist.get(i));
}
I'm not sure that is you want to do. I used the getIdentifier method to retrieve your textViews.
Else, you can inflate your textViews in a loop:
for(int i=0;i<mylist.size();i++)
{
TextView tv = (TextView)LayoutInflater.from(context).inflate(R.layout.myTextView, null);
tv.setText(mylist.get(i));
}
Hope this will help you
You dont need loop here
you need to call textView.setText(mylist.get(0)); ... u need to call this for 10 times with increasing value in get method.. and with diff text view instances.
Edit :as par your comment: here suppose you have created
TextView [] tv; // you need to initialized array here with textviews
ArrayList<String> mylist =new ArrayList<String>();
for(int i=0;i<mylist.size();i++)
{
tv[i].setText(mylist.get(i));
}
for(int i=0;i<mylist.size();i++)
{
tv[i].setText(mylist.get(i));
}
Hai Friends,
I am parsing the url to display the contents in it, my requirement i have to display the each content in separate textviews.
For Instance:
Let us assume the contents in that url are FootBall, Carom , chess, VolleyBall and so on . I want to display FootBall as a individual textview similarly others. so i cannot declare the textviews in xml what i usually do.
(<TextView android:text=" " android:layout_width="wrap_content"
android:gravity="center_horizontal" android:paddingLeft="7dp" android:layout_height="wrap_content"
/>).
so i planned to create textview via java code
This is my parsing code which parse the url contents and store the result in a string array namely san_tagname; depending upon the length of this variable i want to create number of textviews.
List<Message_category> l_obj_tagname = new ArrayList<Message_category>();
l_obj_tagname = obj_parse1.parse_tagname();
System.out.println("l_obj_tagname"+l_obj_tagname.size());
String[] san = new String[l_obj_tagname.size()];
Iterator<Message_category> it_id1 = l_obj_tagname.iterator();
i=-1;
while (it_id1.hasNext()) {
i++;
san[i] = it_id1.next().toString();
System.out.println("Id="+san[i].toString());
san_tagname[i]=san[i];
//vm.setTitle(it.next().toString());
}
for(int z=0;z<san_tagname.length;z++)
{
//how to create textview here ...............
}
I am really struggling on this, pls help me regarding on this friends.................
Thanks In Advance
Tilsan The Fighter...
TextView tv = new TextView(context);
tv.setText(myText);
parent.addView(tv, {LayoutParams for parent container type})
Here is the answer,
Parse the Contents from web
//manipulation to parse id
List<Message_category> l_obj_id = new ArrayList<Message_category>();
l_obj_id = obj_parse1.parse_id();
VAL1 = new String[l_obj_id.size()];
Iterator<Message_category> it_id = l_obj_id.iterator();
while (it_id.hasNext()) {
i++;
VAL1[i] = it_id.next().toString();
System.out.println("Id="+VAL1[i].toString());
//vm.setTitle(it.next().toString());
}
//manipulation to parse tagname
List<Message_category> l_obj_tagname = new ArrayList<Message_category>();
obj_parse1.parse_tagname();
obj_parse1.storedata();
san_tagname= new String[obj_parse1.santagname.length];
for(int k=0;k<obj_parse1.santagname.length;k++)
{
san_tagname[k]=ParsingHandler.temptag[k];
if(san_tagname[k].contains("%20"))
{
san_tagname[k]=san_tagname[k].replace("%20"," ");
System.out.println("San_tagName1"+san_tagname[k]+"S"+k);
}
else
{
System.out.println("San_tagName2"+san_tagname[k]+"S"+k);
}
}
gal_lay = (LinearLayout) findViewById(R.id.rl_1);
navagtion_bar= (LinearLayout) findViewById(R.id.san_tag);
hv = (HorizontalScrollView)findViewById(R.id.gv);
// This is the Code i needed finally i stirkes with the help of hackbod
**for(int z=0;z<san_tagname.length;z++)
{
TextView san_text[]= new TextView[san_tagname.length];
san_text[z]= (TextView) new TextView(this);
san_text[z].setText(" "+san_tagname[z]+" ");
san_text[z].setTextSize(15);
navagtion_bar.addView(san_text[z]);
}**