Updating Multiple TextView in layout with data from json respose - android

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

Related

Parse JSON in Android And Display It In String like array

I am A beginner at the android studio. I want to parse a JSON object and I want to display it like this.
String mNames[] = {"name1", "name2", "name3"};
How Can I do this.
You can use JSONObject and JSONArray as displayed in the following example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
String[] blah = arrays.toArray(jsons);
(Taken from How to parse a JSON and turn its values into an Array?)
Also, just for your information, this process has nothing to do with Android Studio itself, rather with Java and JSON ^^

How Can I Get The Value Of The Components That I Created Programmatically?

I fetch my data from my web server using JSON string (see below)
{"identification":[{"question":"Who created the C programming language?","answers":"Dennis Ritchie","subject":"1","points":"1","question-id":"1"},{"question":"What company created Visual Basic?","answers":"Microsoft","subject":"1","points":"1","question-id":"2"}],"multiplechoice":[{"question":"Which of the following programming languages are not Object Oriented?","answers":"C","choices":["Java","Visual Basic"],"subject":"1","points":"1","question-id":"3"},{"question":"The person who is responsible for the creation of Facebook?","answers":"Mark Zuckerberg","choices":["Steve Jobs","Bill Gates","Larry Page"],"subject":"1","points":"1","question-id":"4"}]}
Using that data I created a dynamic components for e.g. some question have 3 choices hence 3 radio buttons some have 5 choices which is 5 radio buttons etc.
Now the main problem is I really don't have any idea on how to get the reference of the components that I created programmatically, I know how use findViewById when using XML but this time there are no XML file used except for the parent layouts.
I'm planning on retrieving and parsing all the value of the components that I created back into JSON string. (which I have an idea on how to do and not the main problem of this question)
The code below is the one who is responsible for dynamically creating components:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jObject = new JSONObject(jsonObj.toString().trim());
Iterator<?> keys = jObject.keys();
Log.d("TEST: ", "WORKING> " + "ENABLED");
JSONArray temp_json_arr = null;
JSONObject temp_json_obj = null;
String temp_string = "";
int question_number = 1;
LinearLayout ll = (LinearLayout)findViewById(R.id.test_layout);
while( keys.hasNext() ){
String key = (String)keys.next();
Log.d("TEST: ", "KEYS> " + key);
// Getting JSON Array node
temp_json_arr = jsonObj.getJSONArray(key);
// looping through All Questions
for (int i = 0; i < temp_json_arr.length(); i++) {
Log.d("TEST: ", "EXECUTE> before if condition");
JSONObject q = temp_json_arr.getJSONObject(i);
if( key.equals("identification") ) {
Log.d("TEST: ", "EXECUTE> START");
int element_ctr = 0;
TextView[] question_textview = new TextView[10];
TextView[] label_textview = new TextView[10];
EditText[] answer_edittext = new EditText[10];
TextView[] seperator_textview = new TextView[10];
//question node
question_textview[element_ctr] = new TextView(getApplicationContext());
question_textview[element_ctr].setText(question_number+". "+q.getString("question"));
question_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
//question_textview[element_ctr].
ll.addView(question_textview[element_ctr]);
//label node
label_textview[element_ctr] = new TextView(getApplicationContext());
label_textview[element_ctr].setText("Answer:");
label_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(label_textview[element_ctr]);
//answer node
answer_edittext[element_ctr] = new EditText(getApplicationContext());
answer_edittext[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(answer_edittext[element_ctr]);
if(i!=temp_json_arr.length()-1) {
//seperator
seperator_textview[element_ctr] = new TextView(getApplicationContext());
seperator_textview[element_ctr].setText("--------------------------------------------------");
ll.addView(seperator_textview[element_ctr]);
Log.d("TEST: ", "EXECUTE> END");
}
}
if( key.equals("multiplechoice") ) {
Log.d("TEST: ", "EXECUTE> START");
int element_ctr = 0;
TextView[] question_textview = new TextView[10];
TextView[] label_textview = new TextView[10];
RadioButton[] answer_radiobutton = new RadioButton[10];
TextView[] seperator_textview = new TextView[10];
//question node
question_textview[element_ctr] = new TextView(getApplicationContext());
question_textview[element_ctr].setText(question_number+". "+q.getString("question"));
question_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(question_textview[element_ctr]);
//label node
label_textview[element_ctr] = new TextView(getApplicationContext());
label_textview[element_ctr].setText("Answer:");
label_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(label_textview[element_ctr]);
//choices node
JSONArray temp_json_arr2 = null;
temp_json_arr2 = q.getJSONArray("choices");
temp_string = q.getString("answers");
temp_json_arr2.put(temp_string);
Random rnd = new Random();
for (int k = temp_json_arr2.length() - 1; k >= 0; k--)
{
int j = rnd.nextInt(k + 1);
// Simple swap
Object object = temp_json_arr2.get(j);
temp_json_arr2.put(j, temp_json_arr2.get(k));
temp_json_arr2.put(k, object);
}
Log.d("TEST: ", "TRAP> START");
int group_ctr = 0;
RadioButton[] choices_radiobutton = new RadioButton[10];
RadioGroup[] choices_radiogroup = new RadioGroup[10]; //create the RadioGroup
choices_radiogroup[group_ctr] = new RadioGroup(getApplicationContext());
choices_radiogroup[group_ctr].setOrientation(RadioGroup.VERTICAL);
Log.d("TEST: ", "TRAP> END");
for (int t = 0; t < temp_json_arr2.length(); t++) {
choices_radiobutton[t] = new RadioButton(getApplicationContext());
choices_radiobutton[t].setText(temp_json_arr2.getString(t));
choices_radiobutton[t].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
choices_radiogroup[group_ctr].addView(choices_radiobutton[t]); //the RadioButtons are added to the radioGroup instead of the layout
}
ll.addView(choices_radiogroup[group_ctr]);//you add the whole RadioGroup to the layout
group_ctr++;
if(i!=temp_json_arr.length()-1) {
//seperator
seperator_textview[element_ctr] = new TextView(getApplicationContext());
seperator_textview[element_ctr].setText("--------------------------------------------------");
ll.addView(seperator_textview[element_ctr]);
Log.d("TEST: ", "EXECUTE> END");
}
}
if( key.equals("truefalse") ) {
//Log.d("TEST: ", "hi iam true or false");
}
question_number++;
}//end for
}//end while
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm sorry for codes, I just started creating android app and I'm still trying to get a hang with basic stuffs before jumping into complicated code structures, I just want to solve the problem I'm having right now before proceeding with other things.
One simple solution would be to set ID for the Views/components when you create them in the code.
Use this method.
someView.setId(int);
The int must be positive. (Any number)
Once you set the ID, you can refer it in the code elsewhere.
Example
TextView1.setId(10);
TextView tv = (TextView)findViewById(10);
Though it may seems complicated at the start may help you improve on further requirement.
It is better to create a DataStructure (custom class) to de-serialize this json to Object (refer GSON library) then bind it to the UI. And then if UI is updated assign the updated values to Object and send back to server (refer Retrofit library for easy REST operations)

Android text is in reversed order

As a result of the two for-loops below I should get the word an Album name, but I get this name in reverse order. For example if I expect "LINK", I get "KNIL"... Where am I going wrong?
Here is the code:
jsonobj = new JSONObject(param);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String album = c.getString(TAG_ALBUM);
TextView tv = (TextView) findViewById(R.id.imgtest);
//tv.setText(album);
if(!(album == "null")){
String var[] = album.split("|");
for(int a=0;a<var.length;a++){
String t = var[a].intern();
String al = ((TextView) findViewById(R.id.imgtest)).getText().toString();
String b = t+al;
tv.setText(b);
}
}else{
break;
}
}
This line is adding the newest letter t to the beginning of your existing String al:
String b = t+al;
However rather than simply switching this line around (b = al + t), I recommend a faster method:
String album = c.getString(TAG_ALBUM).replaceAll("|", "");
TextView tv = (TextView) findViewById(R.id.imgtest);
tv.setText(album);
I looks like you only wanted to remove the "|" character from your album String, so just use String.replaceAll().
If you need album split into an array, then when you rebuild the String don't waste your time calling findViewById() on a view that you already have. In fact you already have the String, so there is no need to use getText() either:
String var[] = album.split("|");
StringBuilder builder = new StringBuilder();
for(int a=0;a<var.length;a++)
builder.append(a);
// use builder.toString() when you want the cleaned album name.
To add the latest letter t to the end of the current string al:
b = al + t

create android layout using json response

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);
}
}

Android - cannot populate a TableView with JSONArray data

i'm tryng to populate a TableLayout witth data that i get from a MySql database, i get the data from a php script that execute the query and return a JSONArray.
The query seem to work and i get a correct JSONArray, but i get a NullPointerExeption while running this code:
JSONArray jArray = new JSONArray(result);
TableLayout tl = (TableLayout) findViewById(R.layout.list);
TableRow tr = new TableRow(this);
TextView title = new TextView(this);
TextView author = new TextView(this);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
title.setText(json_data.getString("title").toString());
author.setText(json_data.getString("author").toString());
tr.addView(title);
tr.addView(author);
tl.addView(tr);
tr.removeAllViews();
}
"result" contain a valid JSONArray, probably something go wrong in the for cycle, but i don't understand where is the error!
Thanks for your help!

Categories

Resources