I need to create an game info list using this json response in android:
{"count":"2","useruid":"100003264774181","games":[{"lastupdate":"2012-01-17 13:55:39","gametype":"R","players":{"2":"100002913406085,Prabir Kumar D,6sq6","1":"100003264774181,Avinash S,twyq"},"turnuid":"100002913406085","score":{"2":"0","1":"18"},"playerscount":2,"dic":"twl","active":"y","canforcewin":"n","showmsg":"n","lastmove":"HIDE,r,18","gameid":"85030616","tilesinbag":"68"},{"lastupdate":"2012-01-17 13:50:55","gametype":"R","players":{"2":"100000145226351,Sayak K,0r9o","1":"100003264774181,Avinash S,kltv"},"turnuid":"100000145226351","score":{"2":"0","1":"26"},"playerscount":2,"dic":"twl","active":"y","canforcewin":"n","showmsg":"n","lastmove":"BOX,r,26","gameid":"85030764","tilesinbag":"68"}]}
my xml is linearlayout>>frame layout>> scrollview>> linear layout-- android:orientation="horizontal">> text view
currently i m using this but got stuck..
JSONObject jresponse=response.getJsonResponseFor(myRequest);
String result=jresponse.toString();
System.out.println(" jresponse is here "+jresponse.toString());
JSONArray jArray = jresponse.getJSONArray("games");
int max=jArray.length();
System.out.println("array length::"+max);
for (int j = 0; j < max; j++)
{
JSONObject obj = jArray.getJSONObject(j);
JSONArray names = obj.names();
for (int k = 0; k < names.length(); k++)
{
String name = names.getString(k);
String value= obj.getString(name);
createtableLayout();
}
}
the createtableLayout() should add the data dynamically to the xml.
Please help me regarding this.
You need not add data dynamically to the xml. You can just create some base layout in XML.
You can get that layout using findviewbyid and then keep adding the data using the java for that layout.
You can find many samples of creating /adding layouts in java.
ok, then add a layout in your xml, and have a reference of this layout as a field in activity,
Create views like:
for Layouts:
LinearLayout ll=new LinearLayout(this);
to set layout param on view or layout use:
ll.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
example to create views,
TextView txt= new TextView(this);
txt.setText(name);
To add view to layout use:
ll.addView(txt);
to add layout to parent layout, use:
parent.addView(ll);
use method like following,
holder=(LinearLayout)findViewById(R.id.GameListHolder);
JSONObject jresponse=response.getJsonResponseFor(myRequest);
String result=jresponse.toString();
System.out.println(" jresponse is here "+jresponse.toString());
JSONArray jArray = jresponse.getJSONArray("games");
int max=jArray.length();
System.out.println("array length::"+max);
for (int j = 0; j < max; j++)
{
JSONObject obj = jArray.getJSONObject(j);
JSONArray names = obj.names();
for (int k = 0; k < names.length(); k++)
{
String name = names.getString(k);
String value= obj.getString(name);
//Fetch values here
createtableLayout(opponentName, lastMove,points, time, sinceLastMove, whose turn);
}
}
public void createtableLayout(String opponentName, String lastMove, String points,
String time, String sinceLastMove, String whoseTurn)
{
LinearLayout ll=new LinearLayout(this);
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
TextView txtOppName=new TextView(this);
txtOppName.setText(txtOppName);
ll.addView(txtOppName);
TextView txtOppName=new TextView(this);
txtOppName.setText(txtOppName);
ll.addView(txtOppName);
......
holder.addView(ll);
}
}
Related
How can I fill views using cycles. For example, I have a three element:
TextView tv_1, tv_2, tv_3
Can I do something like this?
for(int i=1; i<=3; i++){
tv_{i}.setText(i);
}
Just create an List of textViews and run cycles/loop on it.
List<TextView> textViews = new ArrayList<>();
textViews.add(textView1);
textViews.add(textView2);
textViews.add(textView3);
after that just iterate through it :
for(int i=0 ;i <textViews.size(); i++)
{
textViews.get(i).setText("text");
}
Here, try this.
TextView[] tvs = new TextView[3];
tvs[0] = findViewById(R.id.tv1);
tvs[1] = findViewById(R.id.tv2);
tvs[2] = findViewById(R.id.tv3);
for(int i=0; i<3; i++){
tvs[i].setText(i);
}
I want to populate multiple Text Views in layout with JSON data.
I'm getting JSON data but Text View's text is not updated.
Need help!
Here is my code.
JSONObject response = new JSONObject(result1);
JSONArray json_profile_image = response.optJSONArray("profile_image");
for (int i = 0; i < json_profile_image.length(); i++) {
JSONObject jsonObject1 = json_profile_image.getJSONObject(i);
String first_name = jsonObject1.getString("firstname").toString();
String middle_name = jsonObject1.getString("middlename").toString();
String last_name = jsonObject1.getString("lastname").toString();
lbl_firstname.setText(first_name);
lbl_middlename.setText(middle_name);
lbl_lastname.setText(last_name);
}
Got a solution!
I first created an arraylist-
ArrayList<String> dataList = new ArrayList<String>();
then added values from json to it-
dataList.add(first_name);
dataList.add(middle_name);
dataList.add(last_name);
And then updated Text Views -
if(!dataList.isEmpty()){
lbl_firstname.setText(dataList.get(0));
lbl_middlename.setText(dataList.get(1));
lbl_lastname.setText(dataList.get(2));
}
Since I used AsyncTask to get data in json from url, I updated Text Views in
onPostExecute()
Create textview dynamically inside the for loop as below
for (int i = 0; i < json_profile_image.length(); i++) {
JSONObject jsonObject1 = json_profile_image.getJSONObject(i);
String first_name = jsonObject1.getString("firstname").toString();
String middle_name = jsonObject1.getString("middlename").toString();
String last_name = jsonObject1.getString("lastname").toString();
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText(first_name);
yourLinearLayout.addView(tv);
}
create textview for all json objects
I am using post method to get this array and number of columns will increase based on every post.
"floor":
[
{"no_of_bedroom":"1.5","floor_plotsize_start":"692.00","floor_price_start":"4356832.00"},
{"no_of_bedroom":"2.0","floor_plotsize_start":"1000.00","floor_price_start":"6296000.00"},
{"no_of_bedroom":"2.0","floor_plotsize_start":"1029.00","floor_price_start":"6478584.00"},
{"no_of_bedroom":"2.0","floor_plotsize_start":"1132.00","floor_price_start":"7127072.00"},
{"no_of_bedroom":"3.0","floor_plotsize_start":"1390.00","floor_price_start":"8751440.00"},
{"no_of_bedroom":"3.0","floor_plotsize_start":"4901.00","floor_price_start":"40801320.00"}
]
How to display by using dynamic textview in android?
JSONArray jsonarray;
jsonarray = jsonobject.getJSONArray("floor");
{
//How to proceed by using dynamic textview?
}
Thanks in advance
I guess you can create a listview with textview of the item that you would like to display
My suggestion would be using a loop to get per object and place it inside the listview
peseudo code:
for(int i=0; i< jsonarray.size(); i++){
list.add(jsonarray.getJSONObject(i).getString("no_of_bedroom")); //just an example to check the details of no_of_bedroom key and add it inside the
}
//using list adapter HERE to display the item the TextView
It would be good for you to try it out and update us with more information of how you would like to do it.
You can dynamically create the textviews you want,then you can add them to your main layout and display. Below is a small hint for it:
JSONArray jArray = jsonobject.getJSONArray("floor");
for(int i=0; i < jArray.length(); i++)
{
TextView textview = new TextView();
textview.setText(""); //your own text
textview.setTextColor(Color.parseColor("#000000")); //your own color
//And now add this textview to your main layout
yourlayout.addView(textview);
}
try this
JSONArray jArray = jsonobject.getJSONArray("floor");
for(int i=0; i < jArray.length(); i++)
{
TextView textview = new TextView(this);
textview.setText(""); //your own text
layoutname.addView(textview);
}
I am trying to add my query results to a table row inside a table layout. I keep getting java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. When i call:
((ViewGroup)table.getParent()).removeView(table);
I get an null pointer error. Any help on this would be great. Here`s the full code.
runOnUiThread(new Runnable() {
public void run() {
TableLayout table = (TableLayout)findViewById(R.id.resultstable);
int count = response.getPropertyCount();
System.out.println(count);
for(int i = 0; i < count; i++)
{
resultset.add(response.getProperty(i));
}
//TextView tv = new TextView(this);
for(int j = 0; j < resultset.size(); j++)
{
//if(resultset.get(j).toString() == "resFName")
//{
tv.setText(resultset.get(j).toString());
//((ViewGroup)row.getParent()).removeView(row);
row.addView(tv);
//((ViewGroup)table.getParent()).removeView(table);
table.addView(row);
//}
}
}
});
You are adding same TextView object to the row each time. In each iteration, create a new TextView and a TableRow.
for(int j = 0; j < resultset.size(); j++)
{
//if(resultset.get(j).toString() == "resFName")
//{
TextView tv = new TextView(context);
tv.setText(resultset.get(j).toString());
//((ViewGroup)row.getParent()).removeView(row);
TableRow row = new TableRow(context);
row.addView(tv);
//((ViewGroup)table.getParent()).removeView(table);
table.addView(row);
//}
}
You are adding the same view object to the parent. So, you are getting IllegalStateException.
If you seperate child views with "id" attribute, adding will be successful. You can give different ids to the child views via hashcode method.
I have a JSON String returned by my web service as follows:
{"checkrecord"[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}
The above String represents my dataset. I have converted the String to a JSON Object and I now want to put the data in the String into a TableLayout.
I want the table to be like this when displayed on android app:
rollno percentage attended missed
abc2 40 12 34
This is the code I am using as of now :
//json processing code
public void jsonprocessing(String c)
{
try
{
JSONObject jsonobject = new JSONObject(c);
JSONArray array = jsonobject.getJSONArray("checkrecord");
int max = array.length();
for (int j = 0; j < max; j++)
{
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
for (int k = 0; k < names.length(); k++)
{
name = names.getString(k);
value= obj.getString(name);
createtableLayout();
}
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create table layout
public void createtableLayout()
{
Log.d("values",value); //I am able to see the values abc2,40,12 and 34 over here in logcat
TableLayout t= (TableLayout)findViewById(R.id.tablelayout);
TableRow r1=new TableRow(this);
r1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView t1 = new TextView(this);
t1.setText(value);
t1.setTextColor(Color.BLACK);
t1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
r1.addView(t1);
t.addView(r1, new TableLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
}
My TableLayout contains a button and a EditText as the first TableRow. After I click the button I get the JSON String. So I need to insert 2 TableRows dynamically after that as per my requirement.
My xml as of now is as follows:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tablelayout"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#000044">
<TableRow>
<EditText
android:id="#+id/edittext"
android:width="200px" />
<Button
android:id="#+id/button"
android:text="Check Record"/>
</TableRow>
</TableLayout>
So my problem is how to add those 2 extra TableRows so as to populate them with the String values ?
My code isn't working fine. I am not able to get the required output.
Can anyone help me in this?
Thanks
you can use multicolumn listview for your purpose,
Parse the JSON response and get values into different strings and use this blog for your purpose
Multicolumn Listview
You, probably, can define those 2 more rows in your XML and make them initially invisible. Then upon receiving your data put your data in those rows and make them visible.
// Every UI object must have a layout parameter
int widthContent = RelativeLayout.LayoutParams.WRAP_CONTENT;
int heightContent = RelativeLayout.LayoutParams.WRAP_CONTENT;
// Create relative layout
RelativeLayout.LayoutParams rlParamsName = new RelativeLayout.LayoutParams(widthContent,heightContent);
// Create table row layout
int trWidthContent = TableRow.LayoutParams.WRAP_CONTENT;
int trHeightContent = TableRow.LayoutParams.WRAP_CONTENT;
TableRow.LayoutParams trLayout = new TableRow.LayoutParams(trWidthContent, trHeightContent);
// Create a linear layout to add new object as vertical
LinearLayout objLinearLayout = new LinearLayout(context);
objLinearLayout.setOrientation(LinearLayout.VERTICAL);
// Add number of categories to menu
for (int i = 0; i < SpecialCategories.length(); i++) {
try {
// Json for special categories
JSONObject jsonData = SpecialCategories.getJSONObject(i);
// Get name and count of category
String specialCategoryNames = jsonData.getString("label").toString();
String specialCategoryCount = jsonData.getString("coupon_count").toString();
final TableRow tr = new TableRow(this);
tr.setLayoutParams(trLayout);
tr.setId(i);
//tr.setBackgroundColor(0xFFBEBEBE);
// What is the text view for category name
TextView categoryName = new TextView(this);
categoryName.setPadding(8, 8, 8, 8);
categoryName.setTextSize(18);
categoryName.setLayoutParams(trLayout);
categoryName.setText(specialCategoryNames);
categoryName.setId(i);
categoryName.setTypeface(null, Typeface.BOLD);
categoryName.setTextColor(0xFF000000);
// What is count for category
TextView categoryCount = new TextView(this);
categoryCount.setPadding(7, 8, 8, 8);
categoryCount.setLayoutParams(trLayout);
categoryCount.setBackgroundColor(Color.WHITE);
categoryCount.setText("("+specialCategoryCount+")");
// Add disclosure image to row
ImageView objDrawLineImageView = new ImageView(this);
objDrawLineImageView.setPadding(280, 19, 6, 6);
objDrawLineImageView.setImageResource(R.drawable.disclosure);
objDrawLineImageView.setLayoutParams(trLayout);
// Add name of category
tr.addView(categoryName);
// Add count for category
tr.addView(categoryCount);
// Add disclosure back to table row
tr.addView(objDrawLineImageView);
// Add table row into linear layout
objLinearLayout.addView(tr);
//Add Row End Line to Linear layout
ImageView rowEndLine = new ImageView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,2);
params.setMargins(0, 5, 0, 0);
rowEndLine.setLayoutParams(params);
rowEndLine.setBackgroundColor(0xFFBEBEBE);
// Add end line image to linear layout
objLinearLayout.addView(rowEndLine);
// What happen when user click on table row
tr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(Main.this, ""+tr.getId(),Toast.LENGTH_SHORT).show();
Log.e("TAG", " clicked ID: "+tr.getId());
}
});
} catch (Exception e) {
e.printStackTrace();
}// end try
}// end for SpecialCategories.length()
//Add button number two to the activity.
RelativeLayout objRelativeLayout = (RelativeLayout)findViewById(R.id.row_special);
objRelativeLayout.addView(objLinearLayout);