How to display content correctly from XML Parsing? - java

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

Related

Is there a way to save tablerows into Firebase? Realtime or Firestore?

I made this mobile app that can add table rows after pressing a button. Each row contains an Edittext, four dropdown menus (spinners), and a button that deletes a row. Each row is like a duplicate after I press the button "add". Now, my only problem is how to save that specific content into firebase's real-time database or could firestore. Do you guys have recommendations of how to do this, any resources, or is this question is broad? I can specify some things you're confused.
I can save an edit text that holds the title for the document, and it successfully works, except the table rows because it holds multiple data types. I just heard that firebase can only hold primitive datatypes.
This is the code that is relevant to the problem, so I won't have to paste all 357 lines of code.
private android.support.v7.widget.Toolbar maintoolbar, editToolBar;
private FirebaseAuth mAuth;
private FloatingActionButton fab;
private RelativeLayout layoutMain;
private RelativeLayout layoutButtons;
private RelativeLayout layoutContent;
private boolean isOpen = false;
private Button addnewRowButton, saveItButton;
private EditText titleofDoc;
private Context context = null;
private ProgressBar pb;
private DatabaseReference dr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
dr = FirebaseDatabase.getInstance().getReference().child("Notes").child(mAuth.getCurrentUser().getUid());
maintoolbar = findViewById(R.id.mainToolBar);
setSupportActionBar(maintoolbar);
getSupportActionBar().setTitle("Files");
layoutMain = findViewById(R.id.mainLays);
layoutButtons = findViewById(R.id.layoutButtons);
layoutContent = findViewById(R.id.layoutContent);
addnewRowButton = findViewById(R.id.AddRow);
saveItButton = findViewById(R.id.SaveThis);
titleofDoc = findViewById(R.id.TitleofDoc);
editToolBar = findViewById(R.id.main_edit_toolbar);
pb = findViewById(R.id.progressBar2);
saveItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = titleofDoc.getText().toString().trim();
if (!TextUtils.isEmpty(title)) {
pb.setVisibility(View.VISIBLE);
createNew(title);
pb.setVisibility(View.INVISIBLE);
} else {
Snackbar.make(v, "Fill Empty Fields", Snackbar.LENGTH_SHORT).show();
pb.setVisibility(View.INVISIBLE);
}
}
});
addnewRowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addNewRow();
}
});
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewMenu();
}
});
}
This is the method that makes the table rows.
private void addNewRow() {
final TableLayout tl = findViewById(R.id.tbllays);
String[] teamRoles = {"Director", "Marketing", "Team", "All"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, teamRoles);
context = getApplicationContext();
//adds new row
final TableRow tbr = new TableRow(context);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
tbr.setLayoutParams(layoutParams);
//add edittext to name the task
EditText editText = new EditText(context);
editText.setHint("Add Task");
tbr.addView(editText, 0);
//add spinner to assign teams
Spinner toDo = new Spinner(context);
toDo.setAdapter(adapter);
tbr.addView(toDo, 1);
//add spinner to assign teams
Spinner InProgress = new Spinner(context);
InProgress.setAdapter(adapter);
tbr.addView(InProgress, 2);
//add spinner to assign teams
Spinner Test = new Spinner(context);
Test.setAdapter(adapter);
tbr.addView(Test, 3);
//add spinner to assign teams
Spinner Done = new Spinner(context);
Done.setAdapter(adapter);
tbr.addView(Done, 4);
// Add a button in the second column
Button button = new Button(context);
button.setText("X");
tbr.addView(button, 5);
button.setBackgroundColor(Color.rgb(159, 168, 218));
// Get delete table row button.
Button deleteRowButton = (Button) button;
deleteRowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tbr.removeAllViews();
}
});
tl.addView(tbr);
}
This is the method that can only save the title instead of the content (the table rows in this case).
private void createNew(String title) {
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newThingRef = dr.push();
final Map thingMap = new HashMap();
thingMap.put("title", title);
thingMap.put("timestamp", ServerValue.TIMESTAMP);
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
newThingRef.setValue(thingMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Note added", Toast.LENGTH_SHORT).show();
Intent MainIntent = new Intent(MainActivity.this, MainActivity.class);
startActivity(MainIntent);
} else {
String error = task.getException().getMessage();
Toast.makeText(MainActivity.this, "ERROR: " + error, Toast.LENGTH_LONG).show();
}
}
});
}
});
mainThread.start();
} else {...}
}
This is the xml file (the part where the editor is held)
<RelativeLayout
android:id="#+id/layoutContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/mainToolBar"
>
<RelativeLayout
android:id="#+id/layoutButtons"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:gravity="center"
android:visibility="gone">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainEditor">
<LinearLayout
android:id="#+id/LinLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="370dp">
<android.support.v7.widget.Toolbar
android:id="#+id/main_edit_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:indeterminate="true" />
<EditText
android:id="#+id/TitleofDoc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:ellipsize="end"
android:hint="#string/title"
android:importantForAutofill="no"
android:inputType=""
android:maxHeight="1dp"
android:maxLength="30"
android:maxLines="1"
android:padding="10dp"
tools:targetApi="o" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:alpha=".3"
android:background="#android:color/black" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<TableLayout
android:id="#+id/tbllays"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/AddRow"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_weight=".1"
android:background="#color/colorAccent"
android:text="#string/add_row"
android:textColor="#color/colorPrimaryDark" />
<Button
android:id="#+id/SaveThis"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_weight=".1"
android:background="#color/colorPrimaryDark"
android:text="#string/save" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:text="#string/task" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:text="#string/to_do" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_weight=".1"
android:text="#string/in_progress" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="3"
android:layout_weight=".1"
android:text="#string/testing" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="4"
android:layout_weight=".1"
android:text="#string/done" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="5"
android:layout_weight=".1"
android:text="#string/delete" />
</TableRow>
</TableLayout>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
</RelativeLayout>
Ignore the user part, that is only if the user is signed in.
This is how it runs
You need to add an Listener at the end of each spinner and store in in the variable for example:
Spinner Done = new Spinner(context);
Done.setAdapter(adapter);
Done.setOnItemSelectedListner(this)
tbr.addView(Done, 4);
Then store this variable Done using DatabaseReference
You don't actually want to save the rows, you want to save the underlying content.
Instead of thinking of the on-screen rows as the content itself, think of them as just displaying your underlying content. This underlying content can be backed up, modified, whatever you want, whilst the representation of it on screen can be completely reconstructed at any time.
To convert your code, I'd suggest the following series of steps:
Create something like a Task class, that has all the fields you want (e.g. name, team).
Store a list of Tasks in your current Activity / Fragment class, e.g. private List<Task> myTasks.
Write a method displayTasks that removes all existing rows from your layout, then iterates through myTasks and draws them all to the screen.
Change addNewRow so that it adds a new Task to myTasks, then calls displayTasks.
You now have a list of Tasks, which can be written directly into Cloud Firestore, and be retrieved later.
I'm fully aware this answer isn't the simple "just do x" you're after, but it's the answer you actually need! All of the steps are very simple, and of course feel free to modify them for your use case.
Once you're comfortable with the concept of "what's on screen isn't my data, just a representation of it", you may want to look into LiveData and ViewModel. They're trickier, but with a lot of benefits (explained within the links).

How to Display Data to Listview from SharedPreferences

I have two activity (DetailProduct and Wishlist) and i want to display data from DetailProduct to Wishlist, in here i using SharedPreferences for put data from DetailProduct to Wishlist.
This is my activity DetailProduct
wishlist.setOnClickListener(new View.OnClickListener() {
String imgpicaso = getIntent().getStringExtra("aaa");
String vardetailed = getIntent().getStringExtra("acb");
String thisname = getIntent().getStringExtra("name");
String text = getIntent().getStringExtra("abb");
#Override
public void onClick(View view) {
Intent tambah = new Intent(DetailProduct.this, Wishlist.class);
SharedPreferences sharedPreferences = DetailProduct.this.getSharedPreferences("baba", MODE_PRIVATE);
SharedPreferences.Editor shreditor = sharedPreferences.edit();
shreditor.putString("aaa", imgpicaso);
shreditor.putString("name", thisname);
shreditor.putString("abb", text);
shreditor.commit();
startActivity(tambah);
}
});
This is img DetailProduct
This is img Wishlist, please open this img
And this is file Wishlist.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wishlist);
setTitle("Your Wishlist");
ImageView resultgmb = (ImageView) findViewById(R.id.resultgmb);
TextView detailtok = (TextView) findViewById(R.id.detailtok);
TextView resulttext = (TextView) findViewById(R.id.resulttext);
Button bayarwish = (Button) findViewById(R.id.check);
Button hapus = (Button) findViewById(R.id.delete);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("baba", MODE_PRIVATE);
String imgpicaso = sharedPreferences.getString("aaa", "");
Picasso.with(getBaseContext()).load(imgpicaso).into(resultgmb);
String detailtext = sharedPreferences.getString("name", "");
detailtok.setText(detailtext);
String text = sharedPreferences.getString("ccc", "");
resulttext.setText("$: " +text);
listproduct = (ListView) findViewById(R.id.listproduct);
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listproduct.setAdapter(arr);
arr.notifyDataSetChanged();
}
this is xml Wishlist
<SearchView
android:id="#+id/search"
android:background="#color/cardview_light_background"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</SearchView>
<LinearLayout
android:orientation="vertical"
android:id="#+id/relone"
android:layout_below="#id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/rel"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:src="#drawable/noimage"
android:id="#+id/resultgmb"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_alignParentRight="true"/>
<TextView
android:layout_marginTop="10dp"
android:text="setext"
android:textStyle="bold"
android:textColor="#000"
android:textSize="17dp"
android:id="#+id/detailtok"
android:layout_width="wrap_content"
android:layout_height="30dp" />
<TextView
android:text="setdescription"
android:layout_below="#id/detailtok"
android:textColor="#f00"
android:id="#+id/resulttext"
android:layout_width="wrap_content"
android:layout_height="30dp" />
<LinearLayout
android:layout_below="#id/resulttext"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CHECK"/>
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DELETE"/>
</LinearLayout>
<ListView
android:id="#+id/listproduct"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
</LinearLayout>
Please help me, thank you
As #sark9012 pointed out, you might want to use Intent Data rather than shared preferences for that purpose. Here is a tutorial on that.
Edit
Although I'd really advise against using Shared Preferences data for the purpose you're looking for, it seems you got the code correct for retrieving the data from the Shared Preferences, what you might be missing out on is populating the ListView. This is the code you sent us:
listproduct = (ListView) findViewById(R.id.listproduct);
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listproduct.setAdapter(arr);
arr.notifyDataSetChanged();
I don't really see you populating the adapter with the data retrieved, so you might want to have a look into that. Check this example from CodePath on how to setup the ListView with an ArrayAdapter.
Generate comma separated string and store that in shared preference
while storing to SP.
like string1 = a1+","a2+","a3;
while retrieving from SP.
like array[] = string1.split(",");
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, array);

How to add jsonarray response in linear layout?

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

Android - Listen to imagebutton click inside listview inside fragment

I am working on a 4 tabs application.
One of my fragment is the search one, containing a searchview, textview, listview.
fragmentSearch.java
JSONObject jsonobject = new JSONObject(result);
textView1.setText((String) jsonobject.get("count"));
Integer count = Integer.parseInt((String) jsonobject.get("count"));
if (count == 0) {
// There are no results
textView1.setText(getString(R.string.no_results, query_string));
} else {
// Display the number of results
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query_string});
textView1.setText(countString);
// Specify the columns we want to display in the result
String[] from = new String[] { "title",
"artist",
"duration",
"url"};
// Specify the corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.title,
R.id.artist,
R.id.duration,
R.id.url};
// -- container for all of our list items
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
// -- list item hash re-used
Map<String, String> group;
//create audio json array
JSONArray audios = jsonobject.getJSONArray("audio");
for (int i = 0; i < audios.length(); i++) {
JSONObject audio = audios.getJSONObject(i);
//get info
String title = audio.getString("title");
String artist = audio.getString("artist");
String duration = audio.getString("duration");
String durationformated = getDurationString(Integer.parseInt(duration));
String url = audio.getString("url");
// -- create record
group = new HashMap<String, String>();
group.put( "title", title );
group.put( "artist", artist );
group.put( "duration", durationformated );
group.put( "url", url );
groupData.add(group);
}
SimpleAdapter adapter = new SimpleAdapter(searchContext , groupData, R.layout.result,
from,
to );
listView1.setAdapter( adapter );
and here is my result.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TextView
android:id="#+id/url"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="gone"/>
<TextView
android:id="#+id/title"
style="#android:style/TextAppearance.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/play"
android:singleLine="true"
android:text="title"
android:textColor="#000000" />
<TextView
android:id="#+id/artist"
style="#android:style/TextAppearance.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/title"
android:layout_toLeftOf="#+id/play"
android:singleLine="true"
android:text="artist"
android:textColor="#7D7D7D" />
<TextView
android:id="#+id/duration"
style="#android:style/TextAppearance.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/artist"
android:layout_alignParentBottom="true"
android:layout_below="#id/artist"
android:layout_toLeftOf="#+id/play"
android:singleLine="true"
android:text="03:24"
android:textColor="#7D7D7D" />
<ImageButton
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toLeftOf="#+id/download"
android:src="#drawable/play" />
<ImageButton
android:id="#+id/download"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:src="#drawable/download" />
</RelativeLayout>
I can't find any way to get the "play" image button to react to a click, I have tried itemclicklistener, onclick attributes...
Can someone please provide me a sample code or working tutorial?
Also, the part of my java code is inside the postexecute of an AsynTask.
The onClick and itemClickListener interacts with the fragment. Once you have interaction with the fragment done, you must send data from the fragment to the parent activity using a listener class or something along those lines.
http://developer.android.com/training/basics/fragments/communicating.html
Not sure whats holding you back but setting an onClickListener always worked for me.
You need to handle the play button in your adapter and have to add a property to play button android:clickable="true"

Listview will not populate

Alright I'm stuck on populating a ListView in Android. This must be a tiring question for you guys but I can't find the problem. Basically it will produce placements in the ListView to hold texts, but it wont produce text. I checked my database class and it seems to be storing the data correctly, and I checked the syntax, but I cant find the problem.
Main activity that holds the list view
public class MainScreen extends ListActivity {
private TextView roommateId;
dbHelper db = new dbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
Log.i("Created", "main created");
ArrayList<HashMap<String, String>> roommates = db.getAllRoommates();
if(roommates.size()!=0){
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
roommateId = (TextView) view.findViewById(R.id.roommateId);
String roommateIdValue = roommateId.getText().toString();
Intent intent = new Intent(getApplication(), RoommateView.class);
intent.putExtra("roommateId", roommateIdValue);
startActivity(intent);
}
});
ListAdapter adapter = new SimpleAdapter(MainScreen.this, roommates, R.layout.contact_entry,
new String[] {"roommateId", "firstName", "lastName"},
new int[]{R.id.roommateId, R.id.lastName, R.id.firstName});
setListAdapter(adapter);
}
}
Database code that returns the array list
public ArrayList<HashMap<String,String>> getAllRoommates(){
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
String query = "SELECT * FROM " + DB_TABLE;
SQLiteDatabase data = this.getWritableDatabase();
Cursor cursor = data.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
HashMap<String,String> roommateMap = new HashMap<String, String>();
roommateMap.put(ID, cursor.getString(0));
Log.d("Roommate ID", cursor.getString(0));
roommateMap.put(FIRST_NAME, cursor.getString(1));
Log.d("First Name", cursor.getString(1));
roommateMap.put(LAST_NAME, cursor.getString(2));
list.add(roommateMap);
}while(cursor.moveToNext());
}
return list;
}
contact entry xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/last_name"
android:id="#+id/lastName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/first_name"
android:id="#+id/firstName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/id"
android:id="#+id/roommateId"/>
</TableRow>
Main screen xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000" >
<TextView
android:id="#+id/contactsTitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/button1"
android:background="#444444"
android:onClick="showAddRoommate"
android:text="#string/add_roommate"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
</TableRow>
</TableLayout>
Alright, I think I found the problem, it was that the String array in the simple adapter wasn't corresponding to the hash map key values, so when it was looking for key values that were not in the Hash Map. Change that and it populated. Putting the answer down incase anyone in the future sees this post.

Categories