I have a problem. I have multiple records that after SAX parsing from a xml file that needs to be inserted into the Hashtable and displayed in a listview. I am able to display the data in the listview but all it gives is the same data for all rows in the listview. I think it has something to do with either my coding for the hashtable or my SAX parsing.
This is the xml file I'm trying to retrieve data from online: http://spark.opac.tp.edu.sg/X?op=present&set_no=007584&set_entry=000000001,000000002,000000003,000000004,000000005&format=marc
Below is my handler where i place my data into the hashtable:
ArrayList<Hashtable<String,String>> list = new ArrayList<Hashtable<String,String>>();
Hashtable<String,String> data = new Hashtable<String,String>();
private final String MY_DEBUG_TAG = "Debugging~";
private Boolean in_record = false;
private Boolean in_author = false;
private Boolean in_format = false;
private Boolean in_title = false;
private Boolean in_callNumber = false;
private String format = "";
private String title = "";
private String author = "";
private String callNumber = "";
//private SearchList sList;
//public SearchList getListData() {
// return this.sList;
//}
#Override
public void startDocument() throws SAXException {
// this.sList = new SearchList();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase("record")) {
this.in_record = true;
}
else
if (localName.equalsIgnoreCase("fixfield")) {
if (attributes.getValue("id").equalsIgnoreCase("FMT")) {
this.in_format = true;
}
}
else
if(localName.equalsIgnoreCase("varfield")) {
if(attributes.getValue("id").equalsIgnoreCase("100")) {
this.in_author = true;
}
else
if(attributes.getValue("id").equalsIgnoreCase("245")) {
this.in_title = true;
}
else
if(attributes.getValue("id").equalsIgnoreCase("099")) {
this.in_callNumber = true;
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
StringBuffer sb = new StringBuffer();
String finalString;
String originalString = "";
String chars = new String(ch, start, length);
chars = chars.trim();
if (this.in_format) {
sb.append(chars);
finalString = sb.toString();
this.format = finalString;
}
else
if (this.in_author) {
if(!(chars.equals(""))) {
sb.append(chars);
finalString = sb.toString();
originalString = this.author + finalString;
this.author = originalString;
}
}
else
if (this.in_title) {
if(!(chars.equals(""))) {
sb.append(chars);
finalString = sb.toString();
originalString = this.title + finalString;
this.title = originalString;
}
}
else
if (this.in_callNumber) {
if(!(chars.equals(""))) {
sb.append(chars);
finalString = sb.toString();
this.callNumber = finalString;
}
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("record")) {
this.in_record=false;
}
else
if (localName.equalsIgnoreCase("fixfield")) {
if (this.in_format) {
//set the foundCharacter to Hashtable
data.put("format", this.format);
//sList.setFormat(this.format);
Log.d(MY_DEBUG_TAG,"Format = " + this.format);
this.in_format = false;
}
}
else
if(localName.equalsIgnoreCase("varfield")) {
if (this.in_author) {
//set the foundCharacter to Hashtable
data.put("author", this.author);
//sList.setAuthor(this.author);
Log.d(MY_DEBUG_TAG,"Author = " + this.author);
this.in_author = false;
}
else
if (this.in_title) {
//set the foundCharacter to Hashtable
data.put("title", this.title);
//sList.setTitle(this.title);
Log.d(MY_DEBUG_TAG,"Title = " + this.title);
this.in_title = false;
}
else
if (this.in_callNumber) {
//set the foundCharacter to Hashtable
data.put("callNumber", this.callNumber);
//sList.setCallNumber(this.callNumber);
Log.d(MY_DEBUG_TAG,"Call Number = " + this.callNumber);
this.in_callNumber = false;
}
}
//add the hashtable into ArrayList
list.add(data);
}
Any suggestions guys?
I don't have time to read completly your code ...
But this is a simple example :
ListView myListView;
myListView = (ListView) findViewById(R.id.mylistview);
ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
//load your data
String[][] items = database.getItems("Blog");
//check if the database was empty
if(items != null){
for(int i = 0; i < items[0].length; i++) {
map = new HashMap<String, String>();
map.put("pubdate", items[2][0]);
map.put("title", items[0][i]);
map.put("description", items[1][i]);
listItem.add(map);
}
//Creation of a SimpleAdapter to put items in your list (listitems) in your listview
// You need to have a xml file called list_full_news_item with elements
// called android:id="#+id/title" etc.
SimpleAdapter mSimpleAdaptor = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.list_full_news_item,
new String[] {"pubdate", "title", "description"}, new int[] {R.id.itemPubdate, R.id.itemTitle, R.id.itemDescription});
//Assign to the listView the created adapter
myListView.setAdapter(mSimpleAdaptor);
}
Hope this will help you to understand.
You should not use the SAX Parser and use the Simple XML Library instead. It has the #ElementMap annotation for exactly this purpose. This turns your entire problem into one annotation and three lines of code to read the XML in. Look at my blog post on including the library in an android project and look at the Simple tutorial if you want to see how to use all of its cool features.
Edit: I just realised that I have answered this question before in one of your previous questions. I'm done trying to convince you to look into Simple XML; but please, stop posting essentially the exact same question in five different ways here; people have helped you already, give you answers and lead you in the right direction. It is now time to read more, experiment and learn.
Related
Now in detail. I am writing an App for a dictionary. For that I have created a custom Object called Word. This Word contains the term and its' corresponding translation:
public class Word implements Serializable {
private int _id;
private int wordType;
private String engWordSi;
private String okyWordPl;
private String engWordPl;
private String okyWordSi;
private String engEx;
private String okyEx;
/** Creates a custom class, which allows save a term, it's translation, as well as the plural and example in both
* languages
* #param _id saves the Id of the Word in the Database
* #param engWordSi saves the English translation of the word
* #param okyWordSi saves the Oshikwanyama translation of the word
* #param wordType saves the type of word in form of a number:
* 0 = phrase; 1 = noun; 2 = verb; 3 = adjective; 4 = pronoun; 5 = other
*/
public Word(int _id, int wordType, String engWordSi, String okyWordSi){
this._id = _id;
this.wordType = wordType;
this.engWordSi = engWordSi;
this.okyWordSi = okyWordSi;
}public int get_id(){
return _id;
}
public void set_id(int i){
_id = i;
}
public int getWordType(){
return wordType;
}
public void setWordType(int i){
if(i < 0 || i > 6){
return;
}
wordType = i;
}
public String getEngWordSi(){
return engWordSi;
}
public void setEngWordSi(String word){
engWordSi = word;
}
public String getOkyWordSi(){
return okyWordSi;
}
public void setOkyWordSi(String word){
okyWordSi = word;
}
public String getEngWordPl(){
return engWordPl;
}
public void setEngWordPl(String word){
engWordPl = word;
}
public String getOkyWordPl(){
return okyWordPl;
}
public void setOkyWordPl(String word){
okyWordPl = word;
}
public String getEngEx(){
return engEx;
}
public void setEngEx(String word){
engEx = word;
}
public String getOkyEx(){
return okyEx;
}
public void setOkyEx(String word){
okyEx = word;
}
The data is loaded via a php file connected to the database. The ORDER BY statement only allows me to choose one language to order the results by. But what I need is, that the search term, which might be found in words of both languages, defines if the English word or the Oshikwanyama word is the word which is being arranged in the order. I have check which translation to use in each case. My guess would be to do it in onPostExecute(). The data is returned by the PHP file in the JSON format. From there I put them into an ArrayList.
private class Query extends AsyncTask<Void, Void, Void>{
#Override
protected void onPostExecute(Void aVoid) {
try{
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Word word = new Word(jsonObject.getInt("_id"), jsonObject.getInt("type"), jsonObject.getString("eng"), jsonObject.getString("oky") );
arrayList.add(word);
Log.d("JSON", word.toString());
}
}catch (JSONException e){
e.printStackTrace();
}
ProgressBar bar = (ProgressBar) findViewById(R.id.bar);
bar.setVisibility(View.GONE);
Button button = (Button) findViewById(R.id.SearchButton);
button.setVisibility(View.VISIBLE);
super.onPostExecute(aVoid);
if (arrayList.isEmpty()){
Toast.makeText(SearchActivity.this, "Unfortunately there were no results, the missing word was sent to our developers.", Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(SearchActivity.this, ResultActivity.class);
ItemDetailsWrapper wrapper = new ItemDetailsWrapper(arrayList);
intent.putExtra("results", wrapper);
intent.putExtra("term", searchTerm);
startActivity(intent);
}
InputStream inputStream = null;
String result = "";
#Override
protected void onPreExecute() {
if (arrayList != null){
arrayList.clear();}
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri.toString());
//httpPost.setEntity(new UrlEncodedFormEntity(null));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
}
catch (UnsupportedEncodingException e1){
e1.printStackTrace();
} catch (ClientProtocolException e2){
e2.printStackTrace();
}catch (IllegalStateException e3){
e3.printStackTrace();
}catch (IOException e4){
e4.printStackTrace();
}try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}}
I already have a place to check whether the term searched for is contained in the English or Oshikwanyama word. There I use it to define the flag used in the layout.
public class WordAdapter extends ArrayAdapter<Word> {
private Context mContext;
private List<Word> wordList = new ArrayList<>();
private int srcCode;
private String term;
/** uses words and puts them into a list
*
* #param context stores the context of the calling activity
* #param list stores the ArrayList that was passed into the constructor, and which contains the
* content
* #param searchTerm stores the term that was searched for in SearchActivity to later compare it
* to the contents of the Word and to arrange the correct flag for the source
* language
*/
public WordAdapter(#NonNull Context context, ArrayList<Word> list, String searchTerm) {
super(context, 0 , list);
mContext = context;
wordList = list;
term = searchTerm;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if(listItem == null){
listItem = LayoutInflater.from(mContext).inflate(R.layout.list_item,parent,false);}
final Word currentWord = wordList.get(position);
//Add Images for the flags of the countries and the flag
final TextView sourceTerm = (TextView) listItem.findViewById(R.id.searchTerm);
final TextView translationTerm = (TextView) listItem.findViewById(R.id.translationTerm);
ImageView flag = (ImageView) listItem.findViewById(R.id.src_flag);
ImageButton button = (ImageButton) listItem.findViewById(R.id.flag);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), EditorActivity.class);
intent.putExtra("mode", "report");
intent.putExtra("id", currentWord.get_id());
intent.putExtra("source", sourceTerm.getText());
intent.putExtra("trans", translationTerm.getText());
getContext().startActivity(intent);
}
});
if (currentWord.getOkyWordPl() == null){
currentWord.setOkyWordPl("");
}
if (currentWord.getEngWordPl() == null){
currentWord.setEngWordPl("");
}
if (currentWord.getEngWordSi().contains(term) || currentWord.getEngWordPl().contains(term)){
srcCode = 0;
}
if (currentWord.getOkyWordSi().contains(term) || currentWord.getOkyWordPl().contains(term)){
srcCode = 1;
}
if (srcCode == 0){
sourceTerm.setText(currentWord.getEngWordSi());
translationTerm.setText(currentWord.getOkyWordSi());
flag.setImageResource(R.drawable.britain);
}
if (srcCode == 1){
sourceTerm.setText(currentWord.getOkyWordSi());
translationTerm.setText(currentWord.getEngWordSi());
flag.setImageResource(R.drawable.namibia);
}
return listItem;
}}
Thank you in advance. :)
EDIT:
Adding example Words:
1.
EngWordSi: good
OkyWordSi: nawa
wordType: 2
2.
EngWordSi: good morning
OkyWordSi: wa lele po?
wordType: 0
3.
EngWordSi: morning
OkyWordSi: ongula
WordType: 1
what you can do is, sort your object property like below in your adapter,
public WordAdapter(#NonNull Context context, ArrayList<Word> list, String searchTerm) {
super(context, 0 , list);
mContext = context;
wordList = list;
term = searchTerm;
Collections.sort(list, new Comparator<Word>() {
#Override
public int compare(Word word1, word2) {
return word1.getEngWordSi().compareToIgnoreCase(word2.getEngWordSi());
}
});
}
this is helpful to you.
Here is my demo code
public class Main {
static class Word{
String prority1;
#Override
public String toString() {
return "Word{" +
"prority1='" + prority1 + '\'' +
'}';
}
}
public static void main(String[] args) {
ArrayList<Word> words = new ArrayList<>();
Word word;
for (int i = 0; i < 5; i++) {
word =new Word();
word.prority1 = "aaaa"+(5-i);
words.add(word);
System.out.println("wrod "+i+" is "+word);
}
Collections.sort(words, new Comparator<Word>() {
#Override
public int compare(Word o1, Word o2) {
int ret = o1.prority1.compareTo(o2.prority1);
if (ret > 0) {
return 1;
} else if (ret < 0) {
return -1;
}
return 0;
}
});
System.out.println("after sort check words");
for (Word w : words) {
System.out.println("check word:"+w);
}
}
}
and following is console's output:
wrod 0 is Word{prority1='aaaa5'}
wrod 1 is Word{prority1='aaaa4'}
wrod 2 is Word{prority1='aaaa3'}
wrod 3 is Word{prority1='aaaa2'}
wrod 4 is Word{prority1='aaaa1'}
after sort check words
check word:Word{prority1='aaaa1'}
check word:Word{prority1='aaaa2'}
check word:Word{prority1='aaaa3'}
check word:Word{prority1='aaaa4'}
check word:Word{prority1='aaaa5'}
Hope that can help you.
Here is my code displaying a list that is being parsed from an html file.
private class getItemDesc extends AsyncTask<Void, Void, Void> {
private ArrayList<String> descArray;
#Override
protected Void doInBackground(Void... arg0) {
try {
File file = new File(dir, getString(R.string.html_file));
descArray = new ArrayList<String>();
FileInputStream in = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
Document doc = Jsoup.parse(line);
Elements descs = doc.select("p");
for (Element desc : descs) {
descArray.add(desc.text());
}
}
in.close();
br.close();
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
MyAdapter mAdapter = new MyAdapter(getApplicationContext(),
R.layout.list_layout, descArray);
listView.setAdapter(mAdapter);
}
There is a lot of data coming from this (over 100 items in the array) and it's taking a while to load. I was wondering if there is a way to load 10 items at a time and use an OnScrollListener to continue loading the data from the file? Any suggestions will be appreciated.
Unfortunetly I haven't used that approach before but how about loading for instance 10 elements when list is scrolled to the very bottom . It can be done by simply reseting the adapter , yet there's a question of efficienty . But in my opinion 10 elements would do the thing.
lv = (ListView)findViewById(R.id.list_view);
adapter = new CustomAdaper(this ,/* List of elements*/);
lv.setAdapter(adapter);
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//Check if the last view is visible
if (++firstVisibleItem + visibleItemCount > totalItemCount) {
adapter = new CustomAdapter(getApplicationContext() , /*UpdateYourListData*/)
lv.setAdapter(adapter);
}
}
});
So basicly whenever ListView reach bottom you need to create new Adapter if with List of current + 10 elements.
I would use a Streaming Parser either from GSON or JacksonJSON.
Example from GSON docs:
JsonStreamParser parser = new JsonStreamParser(br); // br is your BufferedReader()
JsonElement element;
synchronized (parser) { // synchronize on an object shared by threads
if (parser.hasNext()) {
element = parser.next();
}
}
I would add extra to do call on listAdapter.notifyDataSetChanged() // ON MAIN THREAD whenever you hit 10. There's obviously other ways you can organize the code.
I have a full blown pagination example here.
There appear to be many ways to accomplish running background code when you reach the end of a listview, the following snippet is what I chose to implement:
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = lv.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (lv.getLastVisiblePosition() >= count - threshold) {
items = (AddItems) new AddItems().execute(count);
}
}
}
});
As for the class AddItem, what I wanted required creating a custom array object, Gift()
public class Gift {
private String descs;
private String itemName;
private String price;
private String imageUrl;
public Gift() {
}
public Gift(String p, String i, String d, String u) {
this.descs = d;
this.itemName = i;
this.price = p;
this.imageUrl = u;
}
public String getDetails() {
return descs;
}
public void setDetails(String details) {
this.descs = details;
}
} // You get the idea
Then I would have to iterate through the file, adding desired strings to their respect ArrayList, and combine all three lists into an ArrayList<Gift> which is shown below.
private class AddItems extends AsyncTask<Integer, Void, ArrayList<Gift>> {
#Override
protected ArrayList<Gift> doInBackground(Integer... integer) {
try {
amountArray = new ArrayList<String>();
itemArray = new ArrayList<String>();
descArray = new ArrayList<String>();
imageUrls = new ArrayList<String>();
finalArray = new ArrayList<Gift>();
File file = new File(Ids.dir, getString(R.string.html_file));
FileInputStream in = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
String line;
int itemNumber = 0;
while ((line = br.readLine()) != null) {
Document doc = Jsoup.parse(line);
Elements titles = doc.select("h4[class=title]");
Elements amounts = doc.select("div[class=price]");
Elements descs = doc.select("p");
Elements urls = doc.select("img[class=gallery-image]");
for (Element price : amounts) {
itemNumber++;
amountArray.add(price.text());
}
for (Element title : titles) {
itemArray.add(title.text());
}
for (Element desc : descs) {
descArray.add(desc.text());
}
for (Element url : urls) {
imageUrls.add(url.attr("src"));
}
// totalShowing is a final integer with a value of 10
// which only iterates through 10 objects plus
// integer[0], which is the total number of items
// shown in the listview.
if (itemNumber == totalShowing + integer[0] + 1) {
break;
}
}
in.close();
br.close();
finalArray = new ArrayList<Gift>();
// Only add to finalArray the items after position integer[0]
// so we don't add items we've already added
for (int i = integer[0]; i < amountArray.size(); i++) {
finalArray.add(new Gift(amountArray.get(i), itemArray
.get(i), descArray.get(i), imageUrls.get(i)));
}
} catch (Exception e) {
e.printStackTrace();
}
return finalArray;
}
#Override
protected void onPostExecute(ArrayList<Gift> result) {
super.onPostExecute(result);
da.addItems(result);
}
}
After that, all I had to do was change my adapter to extend ArrayList<Gift> and add the following code:
public void addItems(ArrayList<Gift> newItems) {
if (null == newItems || newItems.size() <= 0) {
return;
}
if (null == finalArray) {
finalArray = new ArrayList<Gift>();
}
finalArray.addAll(newItems);
notifyDataSetChanged();
}
Hi below is my working code to parse RSS and populate it in ListView, but I want to add CustomAdapter rather than simple Adapter, so that I can add an ImageView in ListView and design my own ListView. Can someone help with code.
SocialFeeds.Java
public class SocialFeeds extends Activity {
// A reference to the local object
private SocialFeeds local;
/**
* This method creates main application view
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
setContentView(R.layout.tweet);
// Set reference to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
// Start download RSS task
task.execute("https:url");
// Debug the thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem>> {
private final ProgressDialog dialog = new ProgressDialog(SocialFeeds.this);
#Override
protected List<RssItem> doInBackground(String... urls) {
// Debug the task thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
// Create RSS reader
RssReader rssReader = new RssReader(urls[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPreExecute() {
dialog.setMessage("Please Wait.");
dialog.setCancelable(true);
dialog.show();
}
#Override
protected void onPostExecute(List<RssItem> result) {
if (dialog.isShowing())
{
dialog.dismiss();
}
// Get a ListView from main view
ListView itcItems = (ListView) findViewById(R.id.list);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1, result);
// Set list adapter for the ListView
itcItems.setAdapter(adapter);
// Set list view item click listener
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}
ListListener.java
public class ListListener extends Activity implements OnItemClickListener {
// List item's reference
List<RssItem> listItems;
// Calling activity reference
Activity activity;
AlertDialog.Builder alert;
WebView wv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public ListListener(List<RssItem> aListItems, Activity anActivity) {
listItems = aListItems;
activity = anActivity;
}
/**
* Start a browser with url from the rss item.
*/
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
/*Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(listItems.get(pos).getLink()));
activity.startActivity(i);*/
}
}
RssParseHandler.java
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
// Used to reference item while parsing
private RssItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// A buffer used to build current title being parsed
private StringBuffer currentTitleSb;
// Parsing pubDate indicator
private boolean parsingpubDate;
// A buffer used to build current pubDate being parsed
private StringBuffer currentpubDateSb;
// Parsing description indicator
private boolean parsingDescription;
// A buffer used to build current description being parsed
private StringBuffer currentDescriptionSb;
// Parsing link indicator
private boolean parsingLink;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("item".equals(qName)) {
currentItem = new RssItem(0, qName, qName, qName);
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
}
else if ("pubDate".equals(qName)) {
parsingpubDate = true;
currentpubDateSb = new StringBuffer();
}
else if ("description".equals(qName)) {
parsingDescription = true;
currentDescriptionSb = new StringBuffer();
}
else if ("link".equals(qName)) {
parsingLink = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
}
else if ("title".equals(qName)) {
parsingTitle = false;
// Set item's title when we parse item->title tag not the channel title tag
if (currentItem != null) {
// Set item's title here
currentItem.setTitle(currentTitleSb.toString());
}
}
else if ("pubDate".equals(qName)) {
parsingpubDate = false;
// Set item's pubDate when we parse item->pubDate tag not the channel pubDate tag
if (currentItem != null) {
// Set item's pubDate here
currentItem.setpubDate(currentpubDateSb.toString());
}
}
else if ("description".equals(qName)) {
parsingDescription = false;
// Set item's description when we parse item->description tag not the channel description tag
if (currentItem != null) {
// Set item's description here
currentItem.setDescription(currentDescriptionSb.toString());
}
}
else if ("link".equals(qName)) {
parsingLink = false;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null) {
// Here we append the title to the buffer due to network issues.
// Sometimes this characters method is called multiple times for a tag contents.
currentTitleSb.append(new String(ch, start, length));
}
}
if (parsingpubDate) {
if (currentItem != null) {
// Here we append the pubDate to the buffer due to network issues.
// Sometimes this characters method is called multiple times for a tag contents.
currentpubDateSb.append(new String(ch, start, length));
}
}
if (parsingDescription) {
if (currentItem != null) {
// Here we append the description to the buffer due to network issues.
// Sometimes this characters method is called multiple times for a tag contents.
currentDescriptionSb.append(new String(ch, start, length));
}
}
else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
RssReader.java
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
// Used to reference item while parsing
private RssItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// A buffer used to build current title being parsed
private StringBuffer currentTitleSb;
// Parsing pubDate indicator
private boolean parsingpubDate;
// A buffer used to build current pubDate being parsed
private StringBuffer currentpubDateSb;
// Parsing description indicator
private boolean parsingDescription;
// A buffer used to build current description being parsed
private StringBuffer currentDescriptionSb;
// Parsing link indicator
private boolean parsingLink;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("item".equals(qName)) {
currentItem = new RssItem(0, qName, qName, qName);
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
}
else if ("pubDate".equals(qName)) {
parsingpubDate = true;
currentpubDateSb = new StringBuffer();
}
else if ("description".equals(qName)) {
parsingDescription = true;
currentDescriptionSb = new StringBuffer();
}
else if ("link".equals(qName)) {
parsingLink = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
}
else if ("title".equals(qName)) {
parsingTitle = false;
// Set item's title when we parse item->title tag not the channel title tag
if (currentItem != null) {
// Set item's title here
currentItem.setTitle(currentTitleSb.toString());
}
}
else if ("pubDate".equals(qName)) {
parsingpubDate = false;
// Set item's pubDate when we parse item->pubDate tag not the channel pubDate tag
if (currentItem != null) {
// Set item's pubDate here
currentItem.setpubDate(currentpubDateSb.toString());
}
}
else if ("description".equals(qName)) {
parsingDescription = false;
// Set item's description when we parse item->description tag not the channel description tag
if (currentItem != null) {
// Set item's description here
currentItem.setDescription(currentDescriptionSb.toString());
}
}
else if ("link".equals(qName)) {
parsingLink = false;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null) {
// Here we append the title to the buffer due to network issues.
// Sometimes this characters method is called multiple times for a tag contents.
currentTitleSb.append(new String(ch, start, length));
}
}
if (parsingpubDate) {
if (currentItem != null) {
// Here we append the pubDate to the buffer due to network issues.
// Sometimes this characters method is called multiple times for a tag contents.
currentpubDateSb.append(new String(ch, start, length));
}
}
if (parsingDescription) {
if (currentItem != null) {
// Here we append the description to the buffer due to network issues.
// Sometimes this characters method is called multiple times for a tag contents.
currentDescriptionSb.append(new String(ch, start, length));
}
}
else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
RssItem.java
public class RssItem {
public int imageId;
// item title
public String title;
// item link
public String link;
// item pubDate
public String pubDate;
// item description
public String description;
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getpubDate() {
return pubDate;
}
public void setpubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public RssItem(int imageId, String title, String description, String link) {
this.imageId = imageId;
this.title = title;
this.description = description;
this.link = link;
}
#Override
public String toString() {
return title + "\n" + description + "\n" + pubDate;
}
}
Use Below url
http://iamvijayakumar.blogspot.in/2012/06/android-rss-feed-reader-example.html
RSS Parser with CustomAdapter using AsyncTask
I'm sorry for my bad english firstly.
Here is my goal;
I need to read xml (actually from web service but there are some problem with my host and i use direct xml link, as my web services return data) from my link. Then i need to write those data to listView.
And here is my problem;
I read that xml from web link and i think parsed xml. I say like this because when i debug project i can see some data on my GettersSetters variable. But when i send those data to my adapter class, there is no action, i guess. Because i can not see any changes on my listView.
Here is my MainActivity.java
public class MainActivity extends Activity {
XMLGettersSetters data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://utkuyegen.com/dersProgramiListele.xml");
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
Log.e("xmlParser", e.getMessage());
System.out.println(e);
}
data = XMLHandler.data;
System.out.println("data = XMLHandler.data");
try {
ListView lv = (ListView) findViewById(R.id.listView1);
System.out.println("listView tanımlandı");
dataAdapter adapter = new dataAdapter(this, R.layout.listview_row,
data.getDersID(), data.getDersAdi());
System.out.println("adapter tanımlandı");
lv.setAdapter(adapter);
System.out.println("adapter listView 'e atandı");
// TextView textView1 = (TextView) findViewById(R.id.textView1);
// textView1.setText(data.getDersID().get(2));
System.out.println("onCreate son satır");
} catch (Exception e) {
Log.d("tag", e.getMessage());
}
}
public class dataAdapter extends ArrayAdapter<XMLGettersSetters> {
// XMLGettersSetters items;
ArrayList<String> _dID, _dAdi;
public dataAdapter(Context context, int textViewResourceId,
ArrayList<String> dID, ArrayList<String> dAdi) {
super(context, textViewResourceId);
this._dID = dID;
this._dAdi = dAdi;
Log.d("da", "1");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listview_row, null);
Log.d("da", "5");
}
Log.d("da", "2");
TextView dersID = (TextView) convertView.findViewById(R.id.dersID);
TextView dersAdi = (TextView) convertView
.findViewById(R.id.dersAdi);
Log.d("da", "3");
dersID.setText(_dID.get(position));
dersAdi.setText(_dAdi.get(position));
Log.d("da", "4");
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And XMLGettersSetters.java
public class XMLGettersSetters {
private ArrayList<String> dersID = new ArrayList<String>();
private ArrayList<String> dersAdi = new ArrayList<String>();
public XMLGettersSetters(ArrayList<String> dersID, ArrayList<String> dersAdi) {
this.dersID = dersID;
this.dersAdi = dersAdi;
}
public XMLGettersSetters() {
}
public String getDersID_tek(int i) {
return dersID.get(i);
}
public ArrayList<String> getDersID() {
return dersID;
}
public void setDersID(String dersID) {
this.dersID.add(dersID);
}
public String getDersAdi_tek(int i) {
return dersAdi.get(i);
}
public ArrayList<String> getDersAdi() {
return dersAdi;
}
public void setDersAdi(String dersAdi) {
this.dersAdi.add(dersAdi);
}
}
And XMLHandler.java
public class XMLHandler extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("ArrayOfDersProgrami"))
{
data = new XMLGettersSetters();
} else if (localName.equals("dersProgrami"))
{
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("DersID"))
data.setDersID(elementValue);
if (localName.equalsIgnoreCase("DersAdi"))
data.setDersAdi(elementValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
BTW, i got some point with my code and debug.
When i debug this codes, i see that i can not understand data.
This is my xml file
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDersProgrami xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<dersProgrami>
<DersID>0</DersID>
<DersAdi>0</DersAdi>
</dersProgrami>
<dersProgrami>
<DersID>1</DersID>
<DersAdi>1</DersAdi>
</dersProgrami>
<dersProgrami>
<DersID>2</DersID>
<DersAdi>4</DersAdi>
</dersProgrami>
<dersProgrami>
<DersID>3</DersID>
<DersAdi>9</DersAdi>
</dersProgrami>
<dersProgrami>
<DersID>4</DersID>
<DersAdi>16</DersAdi>
</dersProgrami>
</ArrayOfDersProgrami>
As you see there is five data but as i said when i debug i see 12 data in my array.
I scope data variable "data = XMLHandler.data;" and i see two arrayList, dersAdi and dersID. Then i scope dersAdi, i see array = Object[12], modCount = 5, size = 5. Then i scope array = Obj.. i see [0, 1, 4, 9, 16, null, null, null, null, null, null, null].
What is that mean? I got 5 datas in my xml but there is 12 datas.
And What i want;
I need some suggestion and i'm close to deadline.
This project is my season
It’s a normal behavior I think, you are debugging an ArrayList<> so what you see are the variables into the class ArrayList as you can see there is an array into that initially has size 12 and null cells and also there is an integer that holds the real number of your items (modCount)
so don’t worry about that the class ArrayList is well developed :P
to get sure from what I say you can debug any other ArrayList you will get same behavior.
EDIT:
try to call adapter.notifyDataSetChanged();after setting your adapter to listview
I parsing the xml using sax parser in android. My xml structure is as given below
<customerlist>
<Customer>
<customerId>2</customerId>
<customerFname>prabhu</customerFname>
<customerLname>kumar</customerLname>
<customerImage>
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
</customerImage>
</Customer>
</customerlist>
I am able to get customerId, customerFname, customrLname, but for customerImage I am not getting complete string I am only getting part of the string i.e (iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABHNCSVQICAgIfAhkiAAACJ9JREFUaIHtmllsXFcZx3/n3Due8XgcO3a8xG72tGkTknRJG7qAaEtbhFjVJUpBoBahgkoRUCFe+lCJvkAKCGgFPJQK0VKWqIhShMhL0mahLU1ImjZp0ziZLN5dezxje5Z7z/l4uDOOl9mcOskLf+vTle79fM63nPM/53xn4P+4tFDzrDffkEoKpQxTgAZcoCYvzpT3FxKWwHAD5PLiT3k/DW6JRjQQAupuuadx/VWbYk9b5dcg+uJkQlnR4uaOvjn28J7ticPAOOARODVdtUQTYaDu+7/86GONLfqbvvUiF9DcknB1KJMYtL/a9shrTxA4kWNGFkploAaoa1+t7mxfWhcRqTgULwiUUpG+02N3Aj8jyEBupk4xBxRBBmLJVEqiEznEWgBEBI8MYVVbdHYpFEZ8tNIUT65CrAEFSjmAxZcsIRUp3p7WJFNZAWJAOi/+VJ1SE9IBQmKsgwGsAgth3cCVTZ9FRIFViBXESjC9rCKTG+MjLfcRdRZjJ7+d0/P8LEsab6YxshxjfMK6gU9f/hS+tfk+ZogBMdYhmI8FEpmGcpO4xs8pba1grQCWzcsfYVH0ckbHexkcP8K1nV+jNbaWfad+zliml8+seYpoaCEnh3ZzZfMXuKzhBg50P8v69nuJ1SzmpSPfwPiGnJ+jM7aZtW1fpCW6FusJ6Nk50Br8nNIEQ7posEtlQEGet0QQEayxdMQ2se/U06xsvh3P5NjQvpUzI6+zsul2Wus3MjT+PuO5IXybZVnjzYxMxLFiibhNdCf307HgBqI1bcTcdm5c+m26R/fjKBfBTvYzU+wMm+bkQDaXYiKTJJ1JIlaTM0lWNt7GFc2fIuZ2MJB6l8M9L+JZD7GKkx/sYTDVRSY7Qcab4N8nf01qYpDB1HFOD7+OlhqyuVE8P4OIomvwFTw/O9nHTJnIJMnmUlNtqnoIAbChfQurlrVj
)
My xmlHandler code is below
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.bvbi.invoicing.client.android.customer.model.CustomerPojoInList;
public class CustomerListParser extends DefaultHandler {
Boolean currentElement = false;
String tempValue = null;
CustomerPojoInList customer = null;
public static ArrayList<CustomerPojoInList> customers = null;
#Override
public void startDocument() throws SAXException {
customers = new ArrayList<CustomerPojoInList>();
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("Customer"))
{
/** Start */
customer = new CustomerPojoInList();
}
}
/** Called when tag closing */
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
String currentValue = tempValue;
tempValue = "";
/** set value */
if (localName.equalsIgnoreCase("customerId"))
customer.setCustomerId(currentValue.toString());
else if (localName.equalsIgnoreCase("customerFname"))
customer.setCustomerFname(currentValue.toString());
else if (localName.equalsIgnoreCase("customerLname"))
customer.setCustomerLname(currentValue.toString());
else if (localName.equalsIgnoreCase("customerImage"))
{
Log.d("prabhu","Customer image in parser......"+currentValue);
customer.setCustomerImage(currentValue.toString());
}
else if (localName.equalsIgnoreCase("Customer"))
customers.add(customer);
}
/** Called to get tag characters */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
tempValue = new String(ch,start, length);
if(tempValue.equals(null))
tempValue = "";
currentElement = false;
}
}
#Override
public void endDocument() throws SAXException {
}
}
Please help me to fix the issue.
In sax parser, characters() method parses only maximum of 1024 characters each time. So we need to append the strings until all the characters are parsed.
I changed the above code as follows
public void characters(char[] ch, int start, int length)
throws SAXException
{
Log.d("prabhu","Customer image length in parser......"+length);
if (currentElement ) {
tempValue = new String(ch,start, length);
if(tempValue.equals(null))
tempValue = "";
}
tempValue = tempValue+new String(ch,start, length);
}
The output you posted is exactly 1024 characters. This looks like a certain buffer size. How do you get this output? Maybe check that method and / or your CustomerPojoInList.
I very much believe, that there is some buffer involved that has a maximum of 1024 characters...
Good luck!
first time post. Updated answer with something that might help others. I hope it is not too specific to my particular problem. I am parsing an RSS feed that I create myself with a really long description but the other tags you are interested in, i.e. feed title, date and URL are always short. The description contains information about social events. Within the description, I use tags that I later parse to give me information about the event such as event date (different from RSS pubDate), (Location), (ticketDetails), (Phone), etc, you get the idea.
A good way to handle this is with a slight modification of the answer in this post. I added tags to the description for (Event) and (EndEvent) and I keep appending to my String Builder until I get "(EndEvent)". That way i know i have the full string. It might not work for your situation if you dont control the feed unless you know there is always a certain string at the end of your RSS description.
Posting in case this (cough, hack) helps anyone. Code is as follows:
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
strBuilder = new StringBuilder();
if ("item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("link".equals(qName)) {
parsingLink = true;
}
else if ("pubDate".equals(qName)) {
parsingDate = true;
}
else if ("description".equals(qName)) {
strBuilder = new StringBuilder(); //reset the strBuilder variable to null
parsingDescription = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String descriptionTester = strBuilder.toString();
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
} else if ("link".equals(qName)) {
parsingLink = false;
}
else if ("pubDate".equals(qName)) {
parsingDate = false;
}
//else
// currentItem.setDescription(descriptionTester);
else if ("description".equals(qName) && descriptionTester.contains("(EndEvent)")) {
parsingDescription = false;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (strBuilder != null) {
for (int i=start; i<start+length; i++) {
strBuilder.append(ch[i]);
}
}
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
parsingTitle = false;
}
else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
else if (parsingDate) {
if (currentItem != null) {
currentItem.setDate(new String(ch, start, length));
parsingDate = false;
}
}
else if (parsingDescription) {
if (currentItem != null && strBuilder.toString().contains("(EndEvent)" )) {
String descriptionTester = strBuilder.toString();
currentItem.setDescription(descriptionTester);
parsingDescription = false;
}
}
}
As I said, hope that helps someone as I was stumped on this for a while!