I am getting a json response in which i am getting jsonObject and jsonArray. I successfully set values for jsonObject but for JsonArray i have two values for each as que ans ans. for example:
"question": [
{
"ans": "test",
"que": "What is your name"
},
{
"ans": "25-30",
"que": "Age"
}
]
this is jsonarray in jsonObject. Now i want to set que and ans in textbox. Note that number of questions are not fixed, they can be 12 or more or less depends on API.
My question is how to set this questions in layout inflater or anything like that?
thanks in advance :)
You will need to use inflation like this: Keep one item.xml which will hold 2 TextViews (or EditText as per your need.)
item.xml:
<RelativeLayout
android:id="#+id/item_row"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/que"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/ans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
Now in your code:
You would need to inflate that item.xml in a loop for as many items you get in your JSONArray. So firstly parse JSONArray and get a ArrayList of Question, Answer pair:
ArrayList<String[]> myArr = new ArrayList<String[]>();
for (int i=0; i < myJSONArray.length(); i++) {
JSONObject j = myJSONArray.getJSONObject(i);
String[] t = {j.getString("que"),j.getString("ans")};
myArr.add[t];
}
Pass this to your activity.
Now you would need to iterate through the ArrayList and inflate your layout, populate TextViews with values in map, and add the inflated view in parent layout:
RelativeLayout container = (RelativeLayout)findViewById(R.id.mylayout); //this will be your container layout
for (int i = 0; i < secQAArr.size(); i++){
View item = getLayoutInflater().inflate(R.layout.item, null);
TextView tQue = (TextView) findViewById(R.id.que);
que.seText(secQAArr.get(i)[0]);
TextView tAns = (TextView) findViewById(R.id.ans);
que.seText(secQAArr.get(i)[1]);
container.addView(item);
}
Hope it helps.
Try this way,hope this will help you to solve your problem.
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/lnrQuestionContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
question.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txtAnswer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
private LinearLayout lnrQuestionContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrQuestionContainer =(LinearLayout) findViewById(R.id.lnrQuestionContainer);
try{
JSONObject jsonObject = new JSONObject("{\"question\":[{\"ans\":\"test\",\"que\":\"What is your name\"},{\"ans\":\"25-30\",\"que\":\"Age\"}]}");
JSONArray questionJsonArray = jsonObject.getJSONArray("question");
for(int i=0;i<questionJsonArray.length();i++){
View view = LayoutInflater.from(this).inflate(R.layout.question,null);
TextView txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
TextView txtAnswer = (TextView) view.findViewById(R.id.txtAnswer);
txtQuestion.setText("Question "+(i+1)+" : "+questionJsonArray.getJSONObject(i).getString("que"));
txtAnswer.setText("Answer "+(i+1)+" : "+questionJsonArray.getJSONObject(i).getString("ans"));
lnrQuestionContainer.addView(view);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
Related
I have a piece of code where I am generating a checklist according to what is in an array. The ScrollView is a parent layout to allow the list to be scrolled when it is long and there is a LinearLayout inside the ScrollView to allow the checkbox to be created dynamically.
My XML code is:
<ScrollView
android:id="#+id/ss_checklist_form"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:id="#+id/ll_checklist_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
My Java code is:
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonO = jsonArray.getJSONObject(i);
assetID = jsonO.getString("AssetID");
assetName = jsonO.getString("AssetName");
// Create the checkbox dynamically with the asset name and ID of the response
CheckBox checkbox = new CheckBox(this);
checkbox.setId(Integer.parseInt(assetID));
checkbox.setTextSize(30);
checkbox.setScaleX(checkboxScale);
checkbox.setScaleY(checkboxScale);
checkbox.setTextColor(Color.parseColor("#606060"));
checkbox.setText(assetName);
final String index = assetID;
checkbox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
submitAsset(index);
}
});
checkList_layout.addView(checkbox);
}
buttonFinish.setVisibility(View.VISIBLE);
buttonGenerate.setVisibility(View.GONE);
ringProgressDialog.dismiss();
}
Everything is working as it should. However, the error comes out when the created checkbox is being added into the layout. This piece of code was tested before and it was working. I've looked on other threads, some stating that I have to run the code on a UI thread instead and some suggest to input a layoutparams which did not work.
I have created dynamic EditText boxes and spinner on Add button, but I don't know how to retrieve data from them. The whole code is available on this website.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parentLinearLayout = (LinearLayout) findViewById(R.id.parent_linear_layout);
mText=(EditText) findViewById(R.id.number_edit_text);
}
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
parentLinearLayout.getChildAt(counter);
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
Try this, You can simply create loop and get all data which have added dynamically, like this :
Change your layout activity_main.xml because in demo they were doing wrong code for layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/parent_linear_layout"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"/>
<Spinner
android:id="#+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:entries="#array/types"
android:gravity="right" />
<Button
android:id="#+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete"/>
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/add_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onAddField"
android:textColor="#FFF"
android:text="Add Field"
android:paddingLeft="5dp"/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/result"/>
</LinearLayout>
Code for getting all values of edit Text :
int count = parentLinearLayout.getChildCount();
for(int i=0; i<count; i++) {
LinearLayout linearLayout = (LinearLayout)parentLinearLayout.getChildAt(i);
EditText editText = (EditText)linearLayout.getChildAt(0);
String result = editText.getText().toString();
//You can result get data from edit text.
}
For Spinner Value :
int count = parentLinearLayout.getChildCount();
for(int i=0; i<count; i++) {
LinearLayout linearLayout = (LinearLayout)parentLinearLayout.getChildAt(i);
Spinner spinnerField = (Spinner)linearLayout.getChildAt(1);
String result = spinnerField.getSelectedItem().toString();
//You can result get data from spinner value.
}
mText=(EditText) view.findViewById(R.id.number_edit_text);
Put this in onAddField method.
When you want to get the text from the ediText you need to call
mText.getText().toString()
I want to display a list of items containing 2 textview in one of my fragment. Something really simple since I'm learning how to use listviews.
Here is my code:
public class CommandeFragment extends Fragment{
private BarMenu myMenu;
View myView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.commande_layout,container, false);
myMenu = (BarMenu) getArguments().getSerializable(MENU_KEY);
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i = 0; i < myMenu.drinks.size(); i++){
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("Name",myMenu.drinks.get(i).drinkName);
hm.put("Price",myMenu.drinks.get(i).drinkPrice.toString());
aList.add(hm);
}
String[] from = {"drinkName","drinkPrice"};
int[] to = {R.id.textView3,R.id.textView4};
SimpleAdapter adapter = new SimpleAdapter(myView.getContext(), aList, R.layout.listview_commande_layout, from, to);
ListView listView = (ListView) myView.findViewById(R.id.listView);
listView.setAdapter(adapter);
return myView;
}
}
When I run this, I got a list of textviews placed correctly but the problem is that the text inside is empty. I've try multiple advice about the xml files online but I'm pretty sure it's fine.
Here it is in case:
listview_commande_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_weight="1" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
commande_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:text="Bar Menu Layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp"
android:id="#+id/textView2" />
</RelativeLayout>
The column names you pass to your adapter don't match the column names in your HashMap ("Name" vs. "drinkName"). If you update these to match, it should work.
for(int i = 0; i < myMenu.drinks.size(); i++){
HashMap<String,String> hm = new HashMap<String, String>();
hm.put("Name",myMenu.drinks.get(i).drinkName);
hm.put("Price",myMenu.drinks.get(i).drinkPrice.toString());
aList.add(hm);
}
String[] from = {"Name","Price"}; //changed from {"drinkName","drinkPrice"}
I'm using a spinner and have populated the dropdown menu with all of the choices. The problem I have is that when the dropdown menu appears, it blocks what is currently selected.
Here's a picture to demonstrate and my code:
if(field.getType().equalsIgnoreCase("select"))
{
CSSelect select = (CSSelect) field;
LinearLayout ll = new LinearLayout(this);
final Spinner s = new Spinner(this);
TextView t = new TextView(this);
t.setText("▼");
t.setTextSize(12);
t.setBackgroundResource(R.drawable.spinnerbg);
t.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s.performClick();
}
});
LinearLayout.LayoutParams slp = new LinearLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT);
s.setLayoutParams(slp);
ll.addView(s);
ll.addView(t);
s.setBackgroundResource(R.drawable.spinnerbg);
List<String> list = new ArrayList<String>();
JSONArray choices = select.getChoices();
for(int j = 0; j < choices.length(); j++)
{
JSONObject jObj = choices.getJSONObject(j);
String st = jObj.getString("text");
list.add(st);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
s.setAdapter(dataAdapter);
rscroll.addView(ll, lp);
}
Spinner dropdown item xml:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textSize="12dp"
android:textColor="#000000"/>
Spinner item xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#000000"
/>
How do I go from A, above, to B? What code do I use to move the dropdown menu below?
Just add the following property to Spinner in XML:
android:overlapAnchor="false"
Have spinner mode set from dialog to dropdown:
<Spinner
android:id="#+id/tv_power_settings_type_spinner"
style="#android:style/Widget.Spinner"
android:spinnerMode="dropdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:popupBackground="#color/black"/>
To do it with code:
new Spinner(this, Spinner.MODE_DROPDOWN)
I am new to android/java and trying to learn by typing code from tutorials. I'm trying to see if I can make a FAQs android module.
Could someone show me how to display only the list of questions and when you click on a question, correspond question and answer display on the next activity?
It's currently displaying both question and answer for the both activities.
Hope my question makes sense. please kindly ask and I will explain as best as I can.
Thank you very much!
faq_list.xml
<item>
<id>1</id>
<question>Whats my phone number?</question>
<answer>my phone number here</answer>
</item>
<item>
<id>2</id>
<question>Whats my fax number?</question>
<answer>my fax number here</answer>
</item>
<item>
<id>3</id>
<question>What is my mailing address?</question>
<answer>my address here</answer>
</item>
faqs_questions.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- qnestion -->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="14sp"
android:layout_marginBottom="10dip"
android:layout_marginTop="10dip"
android:layout_weight="1"
android:paddingLeft="5sp" />
<!-- answer -->
<TextView
android:id="#+id/answer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="14sp"
android:layout_marginBottom="10dip"
android:layout_marginTop="10dip"
android:layout_weight="2"
android:paddingLeft="5sp">
</TextView>
</LinearLayout>
faqs_answers.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/question_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textStyle="bold"
android:textColor="#000"
android:paddingLeft="5sp"
/>
<TextView android:id="#+id/answer_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textColor="#000"
android:paddingLeft="5sp"
/>
</LinearLayout>
FaqsQuestionsActivity.java
public class FaqsQuestionsActivity extends ListActivity {
static final String URL = "http://myweb.com/faq_list.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_QUESTION = "question";
static final String KEY_ANSWER = "answer";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faqs_questions);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_QUESTION, parser.getValue(e, KEY_QUESTION ));
map.put(KEY_ANSWER, parser.getValue(e, KEY_ANSWER));
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.faqs_question_list,
new String[] { KEY_QUESTION, KEY_ANSWER }, new int[] {R.id.question, R.id.answer});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String question = ((TextView) view.findViewById(R.id.question)).getText().toString();
String answer = ((TextView) view.findViewById(R.id.answer)).getText().toString();
Intent in = new Intent(getApplicationContext(), FaqsAnswersActivity.class);
in.putExtra(KEY_QUESTION, question);
in.putExtra(KEY_ANSWER, answer);
startActivity(in);
}
});
}
}
FaqsAnswersActivity.java
public class FaqsAnswersActivity extends Activity {
// XML node keys
static final String KEY_QUESTION = "question";
static final String KEY_ANSWER = "answer";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faqs_answers);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String question = in.getStringExtra(KEY_QUESTION);
String answer = in.getStringExtra(KEY_ANSWER);
// Displaying all values on the screen
TextView lblQuestion = (TextView) findViewById(R.id.question_label);
TextView lblAnswer = (TextView) findViewById(R.id.answer_label);
lblQuestion.setText(question);
lblAnswer.setText(answer);
}
}
It looks to me like the previous answer may give you a problem since you are pulling values from your TextView to put in the Intent for the next Activity.
Instead, I suggest that you change the visibility of your answer TextView in "questions.xml" like this:
<TextView
android:id="#+id/answer"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="14sp"
android:layout_marginBottom="10dip"
android:layout_marginTop="10dip"
android:layout_weight="2"
android:paddingLeft="5sp">
</TextView>
Also, since the view is not visible, you could remove the layout properties that are now irrelevant. I believe all you should need is id and visibility.
<TextView
android:id="#+id/answer"
android:visibility="gone">
</TextView>
The simple list adapter builds the list based on the xml files, just remove the reference to the answer from the listview and it should work
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.faqs_question_list,
new String[] { KEY_QUESTION }, new int[] {R.id.question});
and remove the answer textview from the faq_questions.xml