Using Jsoup to populate a ListView - java

I am trying to parse a website using Jsoup, take the info I get and populate a ListView. The HTML looks like this:
<ul class="list_view">
<li>
<a href="/username/" >
<table class="pinner">
<tbody>
<tr>
<td class="first_td">
<img src="http://myimgurl.com/img.jpg">
</td>
<td>
<span class="user_name">User Name</span>
</td>
</tr>
</tbody>
</table>
</a>
</li>
</ul>
So, from this HTML, I need to get the href from the a tag, and also the span.user_name text. I need to take both of these elements and store them in a HashMap (I think??) Right now, I have this in an AsyncTask like so (but I don't think I am doing this the correct way):
private class MyTask extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
#Override
protected List<HashMap<String, String>> doInBackground(Void... params) {
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
try {
Document doc = Jsoup.connect("http://myurl.com").get();
Elements formalNames = doc.select("li a table tbody tr td span.user_name");
Elements userNames = doc.select("li a");
for (Element formalName : formalNames) {
map.put("col_1", formalName.text());
fillMaps.add(map);
System.out.println(formalName.text());
}
for (Element userName : userNames) {
map.put("col_2", userName.attr("href").toString());
fillMaps.add(map);
System.out.println(userName.attr("href").toString());
}
} catch (IOException e) {
e.printStackTrace();
}
return fillMaps;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] from = new String[] {"col_1", "col_2"};
int[] to = new int[] { R.id.text1, R.id.text2 };
ListView _listview = (ListView)findViewById(R.id.listView1);
SimpleAdapter _adapter = new SimpleAdapter(FriendsActivity.this, fillMaps, R.layout.friends, from, to);
_listview.setAdapter(_adapter);
}
}
This successfully prints out the info I want, but it does not populate the ListView. I am have tried rearranging, etc. but still, no luck. I would be mighty grateful for any help at all.

check getView() in your SimpleAdapter class. the returned view by getView() should show one each item properly.
You can call _adapter.notifyDataSetChanged() when the process finished
updated
ok i guess i found the example u might referenced.
The problem is, you are using the same HashMap again and again.
if you put any String on any key("col_1" or "col_2") again and again, it will only save the last one.
So when the time you show it on the screen(after onPostExecute), the all views will show the last formalName and userName, because all HashMap added on your list are saving the same last one only(they are actually the one same HashMap).
I suggest you to make new HashMap for each time you add it on the fillMaps.

Related

How to display ArrayList Object in Thymeleaf page

I try to display Arraylist object in Thmeleaf page but I got null for the value.
I can display the arraylist in controller on console. Is it correct the way I pass arraylist in function.
In controller
#RequestMapping("/searchSummon")
public String Search(Model model) {
model.addAttribute("summonsDetailType", new SummonsDetailType());
model.addAttribute("rowType", new RowType());
return "searchSummon";
}
#RequestMapping(value = "/searchProcess", method = RequestMethod.POST)
public String searchProcess(SummonsDetailType summonsDetailType, RowType rowType) {
ArrayList<RowType> rowTypes2 = new ArrayList<RowType>();
SummonsDetailType summonsDetailType2 = pdxiRes.getRequest().getSummonsDetail();
for (RowType rowType3 : summonsDetailType2.getRow()) {
rowTypes2.add(rowType3);
}
System.out.println(rowTypes2.get(0).getDistrictCode());
return "/searchResult";
}
html page
<tr th:each="rowType : ${rowType}">
<td th:text="'NRIC NO: ' + ${rowType.DistrictCode}"></td>
</tr>
I solved the problem by adding the arraylist in model
model.addAttribute("rowTypes2", rowTypes2);

Display all images from Database (blob) on a jsp file in a table

i need your help. I want to display all the images from my database (there are 6 images in there) on a jsp file. Why JSP File and not using outputreader? -> Cause i want to style the table with css in the next step so i have to do this on this special way.
Select all the pictures of the database:
public static List<Picture> displayPicture() {
List<Picture> list = new ArrayList<Picture>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:9999/xxx", "xxx", "xxx");
String sql = "SELECT * FROM PICTURES";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
byte[] imageData = rs.getBytes("File_Data");
String imageFileName = rs.getString("File_Name");
Picture picture = new Picture();
picture.setImageData(imageData);
picture.setImageFileName(imageFileName);
list.add(picture);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
Now i want to save this List in setAttribute to send it to the JSP-File:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Picture> list =null;
list = DBUtils.displayPicture();
request.setAttribute("pictureList", list);
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/pictureView.jsp");
dispatcher.forward(request, response);
And finally the JSP-File:
<table>
<c:forEach items="${pictureList}" var="picture">
<tr>
<td>${picture.imageData}</td>
</tr>
</c:forEach>
So i want to display all the images in a table. At the moment it doesnt matter how the table looks like. With this code i get only a table with special numbers and letters. I think its the binary code, right? (For example: beans.Picture#22debaab or [B#3f391312])
Now where is the mistake? in the Code of the JSP-File cause i have to use
<img src="">
or something else? If this was the mistake, how should be coding this?
Thank you guys
Dear Newbie
Use the code snippet in controller side.
List<String> list = new ArrayList<String>();
while (rs.next()) {
byte[] imageData = rs.getBytes("File_Data");
list.add(org.apache.commons.codec.binary.Base64.encodeBase64String(imageData));
}
request.setAttribute("pictureList", list);
And show it in html page like that,
<table>
<c:forEach items="${pictureList}" var="picture">
<tr>
<td><img src="data:image/jpg;base64,${picture}"/></td>
</tr>
</c:forEach>
</table>

How to write code for insertion and deletion of table data with many buttons from front-end?

I write code for one web page in jsp. Here, it shows the table values. Every table row contain two buttons. One for deletion, another for insertion of another table. How can I handle this situation?
make diffent function for insertion and deletion in in different class like
Class DC()
{
public void insert()
{
your code
}
public void delete()
{
your code
}
}
then use in jsp code
<td> <input type="button" value="insert" onsubmit=<% insert1(); %></td>
The easiest way I think i to use links
try this idea :
add in your table a row like this :
<td style=" width: 100px;"><a class=" "
href="SERVLET-NAME?DATA=/*WHAT-YOU-WANT*/&DATA2=/*WHAT-YOU-WANT*/">DELETE</a>
//you can put ${} instead of /WHAT-YOU-WANT/
then in your servlet take the data a perform the wanted Action on database for example
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String DATA1 = request.getParameter("DATA");
String DATA2 = request.getParameter("DATA2");
Database obj= new Database();
obj.delete(DATA1,DATA2);
//...
}

How to show one Item at a time from Java ArrayList

I wonder if anyone can help, I'd like to Iterate over ArrayList but One item at a time with help of some button so when I press that button it would show me the next item in the list and so forth. Or if there's another way I'd be happy to take any advice. I'm trying to design a test so a student would get one question at a time he/she would submit the answer and it would move to the next question. This is what I have as showing full list on JSP.
My Servlet
String vassId = request.getParameter("vassId");
List<Assessment> qList = new ArrayList<Assessment>();
Assessment qObj = null;
DbConnection dbConn = null;
Connection conn = null;
CallableStatement proc = null;
response.setContentType("text/html");
ResultSet rs = null;
try {
dbConn = new DbConnection();
conn = DbConnection.connection();
String dbCall = "{ ? = call pa_customer_admin.fn_list_question(?) }";
proc = DbConnection.connection().prepareCall(dbCall);
proc.registerOutParameter(1, OracleTypes.CURSOR);
proc.setInt(2, Integer.parseInt(vassId));
proc.execute();
rs = (ResultSet) proc.getObject(1);
while (rs.next()) {
qObj = new Assessment();
qObj.setVassId(Integer.parseInt(rs.getString(1)));
qObj.setDescr(rs.getString(2));
qObj.setQuesStatus(rs.getString(3));
qObj.setQuesTypeCode(rs.getString(4));
qObj.setCreatedDate(rs.getString(6));
qObj.setQuestion(rs.getString(7));
qObj.setMark(rs.getString(8));
qObj.setTimeLimit(rs.getInt(9));
qList.add(qObj);
}
request.setAttribute("qObj", qObj);
request.setAttribute("qList", qList);
proc.close();
JSP
<form action="AnswerSaveProcess" method="POST" >
<c:if test="${empty qList}">
Empty list
</c:if>
<c:if test="${! empty qList}">
<c:forEach items="${qList}" var="q">
<label>Question</label>
<input type="hidden" value="<%= vassId%>">
<textArea readonly="readonly">${q.question}</textarea>
<input type="text" value="${q.mark}" readonly="readonly">
<input type="hidden" id="userTime" value="${q.timeLimit}" />
<label>Answer 1</label>
<input type="text" ><input name="ansStatusCode" type="radio"><br/>
<label>Answer 2</label>
<input type="text" ><input name="ansStatusCode" type="radio"><br/>
<input type="submit" name="submit" value="Save Answer">
</c:forEach>
</c:if>
</form>
ArrayList implements the Iterable interface and has index-based access to its members. All you need is to read some Java docs on usage examples.
Try something like (untested):
final List<String> questions = Arrays.asList(new String[]{"question1", "question2", "question3"});
JButton b = new JButton("Press Me");
final JLabel label = new JLabel();
final cnt = 0;
b.addActionListener(new ActionListener(){
pubic void actionPerformed(ActionEvent e) {
label.setText(question.get(cnt++));
if(cnt > questions.size()) cnt = 0;
}
});
JFrame frame = new JFrame();
frame.getConentPane().add(b);
frame.getConentPane().add(label);
frame.setSize(800,600);
frame.setVisible(true);
As it's an ArrayList you can use indexing. When the button is pressed increment the index and get the next item from the ArrayList.
Example
package items;
import java.util.List;
public class GetNextItem {
private static int itemIndex;
private List<String> itemList;
// Constructor with itemList
public GetNextItem(List<String> itemList) {
this.itemList = itemList;
itemIndex = 0; // start at the first item.
}
/**
* Get the current Item from the itemList
* #return the current item from the itemList or NULL if all the items are processed.
*/
public String getItem() {
if (itemIndex >= itemList.size()) {
return null; // end of list
}
return itemList.get(itemIndex);
}
/**
* Get the next Item from the itemList
* #return the next item from the itemList or NULL if all the items are processed.
*/
public String getNextItem() {
itemIndex ++;
return getItem();
}
}
Elements of an ArrayList can easily be accessed by index.
From a web page (built by JSP), you can request a specific question using a query parameter, e.g. showquestion.jsp?question=4.
The JSP-generated page can then include a button to show next question by generating a new link (Next) with the next higher index, as long as there are more questions.

How to pass an ArrayList from Java class to jsp

Attempting to send an ArrayList from java class to servlet. The returned values of ResultSet is passed on to a model object and this object is added to an ArrayList. However I need retrieve this ArrayList in vieitems.jsp.
DBController.java
public void getAvailableItems(String sqlst) throws Exception {
Connection connection = getConnection();
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sqlst);
ArrayList<Item> avitems = new ArrayList<Item>();
while (rst.next()) {
String itemname = rst.getString("ItemName");
String description = rst.getString("Description");
int qtyonhand = rst.getInt("QtyOnHand");
int reorderlevel = rst.getInt("ReorderLevel");
double unitprice = rst.getDouble("unitprice");
Item item = new Item(itemname, description, qtyonhand, reorderlevel, unitprice);
avitems.add(item);
}
//i need to send avitems to ViewItems.jsp
}
ViewItems.jsp
<form>
<Table border="1">
<tbody>
<tr> <td>Item Code</td><td>Item Name</td><td>Description</td><td> Qty On Hand</td><td>Reorder Level</td></tr>
//here i need to set the values of arraylist avitems
</tbody>
</Table>
</form>
In the servlet code, with the instruction request.setAttribute("itemList", avitems), you save your list in the request object, and use the name "itemList" for refering it.
When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute("itemList") method.
//Servlet page code DBController.java
request.setAttribute("itemList", avitems);
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/ViewItems.jsp");
rd.forward(request, response);
// Jsp Page code ViewItems.jsp
<%
// retrieve your list from the request, with casting
ArrayList<Item> list = (ArrayList<Item>) request.getAttribute("itemList");
// print the information about every category of the list
for(Item item : list)
{
// do your work
}
%>
Make that ArrayList declaration static in DbController.java
In DbController create one method
void static ArrayList<items> getList()
{
return avitems;
}
it will return you the list in view.jsp
in view.jsp import DbController.java and add this scriplet
<%
ArrayList<Item> list = DbController.getList(); //it will return the list
%>
iterate and do whatever you want to do with this list in your view.jsp
i think this will help you.

Categories

Resources