How to retrieve all data from an xml document using XMLPullParser and how to store them to be distributed...
[Here is a screenshot of the DetailActivity
&& Here is a screenshot of the Main Activity ][1]I am trying to parse an XML document using xmlPullParser
and distribute the retrieved data to two activities:
MainActivity
: includes 3 properties
DetailActivity
: includes all the other data.
I have two questions:
- How to parse all the tags and retrieve their data in xml document using
xmlPullParser
. - How to display the data of the
DetailActiviy
whenever aRecyclerView
item is clicked.
I have tried to parse the xml document twice. Once for the main data and second for the extra data i need for the detail activity either by opening connection twice (work around but too bad way) or by storing the retrieved data in a list and returning two new constructors instead of one(the list is not displaying anymore).
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements AdsAdapter.AdsAdapterOnClickHandler
{
public static final String URL = "DISPLAYED BELOW";
private static final String TAG = MainActivity.class.getSimpleName();
public static List entries = new ArrayList<>();
private RecyclerView mRecyclerView;
private AdsAdapter mAdsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_ad);
int recyclerViewOrientation = LinearLayoutManager.VERTICAL;
boolean shouldReverseLayout = false;
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, recyclerViewOrientation, shouldReverseLayout);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mAdsAdapter = new AdsAdapter(this);
mRecyclerView.setAdapter(mAdsAdapter);
loadPage();
}
public void loadPage() {
new DownloadXmlTask().execute(URL);
System.out.print("Result" + "Succeed");
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<AdEntry>>
{
@Override
protected List<AdEntry> doInBackground(String... urls)
{
try
{
return loadXmlFromNetwork(urls[0]);
}
catch (IOException e)
{
return null;
}
catch (XmlPullParserException e)
{
return null;
}
}
@Override
protected void onPostExecute(List<AdEntry> adEntries)
{
Toast.makeText(MainActivity.this, "Successfully Processed", Toast.LENGTH_SHORT).show();
System.out.println("Successfully Processed");
mAdsAdapter.setAdData(adEntries);
super.onPostExecute(adEntries);
}
}
public List<AdEntry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
try
{
stream = downloadUrl(urlString);
entries = parse(stream);
}
finally
{
if (stream != null)
stream.close();
}
System.out.println("FinalDataResult" + entries);
return entries;
}
public InputStream downloadUrl(String urlString) throws IOException
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
return conn.getInputStream();
}
@Override
public void onClick(AdEntry ad)
{
Context context = this;
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(context, destinationClass);
intentToStartDetailActivity.putExtra("Product Name",ad.productName);
intentToStartDetailActivity.putExtra("Product Thumbnail", ad.productThumbnail);;
startActivity(intentToStartDetailActivity);
}
}
Here is my XMLPullParser:
public class AdXmlParser {
private static final String ns = null;
public static List parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readAds(parser);
} finally {
in.close();
}
}
public static List detailParse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readExtras(parser);
} finally {
in.close();
}
}
private static List readAds(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> entries = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("ad"))
entries.add(readEntry(parser));
else
skip(parser);
}
System.out.println("entries" + entries);
return entries;
}
private static List<AdEntry> readExtras(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> extras = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("ad")) {
extras.add(readExtraData(parser));
} else {
skip(parser);
}
}
return extras;
}
private static AdEntry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String productName = null;
String productThumbnail = null;
String rating = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
switch (name) {
case "productName":
productName = readNameProduct(parser);
System.out.println("productName" + productName);
break;
case "productThumbnail":
productThumbnail = readThumbnail(parser);
System.out.println("productThumbnail" + productThumbnail);
break;
case "rating":
rating = readRating(parser);
System.out.println("rating" + rating);
break;
default:
skip(parser);
break;
}
}
return new AdEntry(productName, productThumbnail, rating);
}
private static AdEntry readExtraData(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String averageRatingImageURL = null;
String numberOfRatings = null;
String categoryName = null;
String appId = null;
String productDescription = null;
String clickProxyURL = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("averageRatingImageURL")) {
averageRatingImageURL = readRating(parser);
System.out.println("rating" + averageRatingImageURL);
} else if (name.equals("numberOfRatings")) {
numberOfRatings = readNumberOfRatings(parser);
System.out.println("numberOfRatings" + numberOfRatings);
} else if (name.equals("categoryName")) {
categoryName = readCategoryName(parser);
System.out.println("categoryName" + categoryName);
} else if (name.equals("appId")) {
appId = readAppId(parser);
System.out.println("appId" + appId);
} else if (name.equals("productDescription")) {
productDescription = readProductDescription(parser);
System.out.println("productDescription" + productDescription);
} else if (name.equals("clickProxyURL")) {
productDescription = readProxyLink(parser);
System.out.println("clickProxyURL" + clickProxyURL);
} else
skip(parser);
}
return new AdEntry(averageRatingImageURL, productDescription, categoryName, numberOfRatings, appId, clickProxyURL);
}
private static String readProxyLink(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "clickProxyURL");
String clickProxyURL = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "clickProxyURL");
return clickProxyURL;
}
private static String readProductDescription(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productDescription");
String productDescription = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productDescription");
return productDescription;
}
private static String readAppId(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "appId");
String appId = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "appId");
return appId;
}
private static String readNameProduct(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productName");
String productName = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productName");
return productName;
}
private static String readThumbnail(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productThumbnail");
String productThumbnail = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productThumbnail");
return productThumbnail;
}
private static String readNumberOfRatings(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "numberOfRatings");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "numberOfRatings");
return numberOfRatings;
}
private static String readCategoryName(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "categoryName");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "categoryName");
return numberOfRatings;
}
private static String readRating(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "rating");
String rating = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "rating");
return rating;
}
private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG)
throw new IllegalStateException();
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
Here is my Adapter:
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsAdapterViewHolder> {
final private AdsAdapterOnClickHandler mClickHandler;
public TextView thumbnail_textView;
public TextView name_textView;
public TextView rating_textView;
private List<AdEntry> mAdData;
public AdsAdapter(AdsAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
@Override
public AdsAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.ad_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new AdsAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(AdsAdapterViewHolder adsAdapterViewHolder, int position) {
AdEntry ad_item = mAdData.get(position);
String thumbnail = ad_item.getProductThumbnail();
name_textView.setText(thumbnail);
String productName = ad_item.getProductName();
thumbnail_textView.setText(productName);
String productRating = ad_item.getProductRating();
rating_textView.setText(productRating);
}
@Override
public int getItemCount() {
if (null == mAdData) return 0;
return mAdData.size();
}
public void setAdData(List<AdEntry> adData) {
mAdData = adData;
System.out.println("mAdData Result" + mAdData);
notifyDataSetChanged();
}
public interface AdsAdapterOnClickHandler {
void onClick(AdEntry ad);
}
public class AdsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public AdsAdapterViewHolder(View view) {
super(view);
thumbnail_textView = (TextView) view.findViewById(R.id.detail_product_thumbnail);
name_textView = (TextView)view.findViewById(R.id.product_name);
rating_textView = (TextView)view.findViewById(R.id.product_rating);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
AdEntry ad = mAdData.get(adapterPosition);
mClickHandler.onClick(ad);
}
}
}
Here is the XML Document I am trying to parse:
<ad>
<appId>com.zynga.ozmatch</appId>
<averageRatingImageURL>
https://cdn1.appia.com/cdn/adpub/appwallv1/rated-5-5.png
</averageRatingImageURL>
<bidRate>0.000</bidRate>
<billingTypeId>1</billingTypeId>
<callToAction>Install Now</callToAction>
<campaignDisplayOrder>1</campaignDisplayOrder>
<campaignId>24058</campaignId>
<campaignTypeId>2</campaignTypeId>
<categoryName>Puzzle</categoryName>
<clickProxyURL>
http://prlds.appia.com/v2/preloadAd.jsp?siteId=10777&deviceId=4230&spotId=&sessionId=techtestsession&campaignId=24058&creativeId=483970&packageName=com.zynga.ozmatch&fulfillmentTypeId=1&placementId=&campaignDisplayOrder=1&enc=true&ts=1680f0e88d8&algorithmId=-4&partner=154&homeScreen=false
</clickProxyURL>
<creativeId>483970</creativeId>
<homeScreen>false</homeScreen>
<impressionTrackingURL>
https://imps.appia.com/v2/impressionAd.jsp?siteId=10777&campaignId=24058&creativeId=483970&campaignDisplayOrder=1&ts=1680f0e88d8&sessionId=techtestsession&packageName=com.zynga.ozmatch&enc=true&eventGroupId=EVTGID1546440837284181712958668&algorithmId=-4&partner=154
</impressionTrackingURL>
<isRandomPick>false</isRandomPick>
<numberOfRatings>10,000+</numberOfRatings>
<productDescription>
Match your way to meet the wonderful Wizard of Oz in this amazing puzzle adventure!
</productDescription>
<productId>15338</productId>
<productName>Wizard of Oz: Magic Match</productName>
<productThumbnail>
https://prod-static-images.s3.amazonaws.com/shared/creatives/15338/1385be772f424a3cb42cd8f07747b05b.png
</productThumbnail>
<rating>5.0</rating>
</ad>
Here is my model Class:
public class AdEntry {
public String productThumbnail;
public String productName;
public String productRating ;
public String productDescription;
public String productCategory;
public String numberOfRatings;
public String appId;
public String proxyLink;
public String averageRatingImageURL;
public AdEntry(String productThumbnail, String productName, String productRating) {
this.productThumbnail = productThumbnail;
this.productName = productName;
this.productRating = productRating;
}
public AdEntry(String productRating, String productDescription, String productCategory, String numberOfRatings, String appId, String proxyLink){
this.productRating = productRating;
this.productDescription = productDescription;
this.productCategory = productCategory;
this.numberOfRatings = numberOfRatings;
this.appId = appId;
this.proxyLink = proxyLink;
}
public String getProductThumbnail() {
return productThumbnail;
}
public String getProductName() {
return productName;
}
public String getProductRating() {
return productRating;
}
public String getProductDescription() {
return productDescription;
}
public String getProductCategory() {
return productCategory;
}
public String getNumberOfRatings() {
return numberOfRatings;
}
public String getAppId() {
return appId;
}
public String getProxyLink() {
return proxyLink;
}
public String getAverageRatingImageURL() {
return averageRatingImageURL;
}
}
Here is the DetailActivity:
public class DetailActivity extends AppCompatActivity {
private static List<AdEntry> entries = new ArrayList<>();
public TextView description_textView;
public TextView category_textView;
public TextView rating_textView;
public TextView link_textView;
public TextView numberOfRating_textView;
public TextView name_textView;
public TextView thumbnail_textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
name_textView = (TextView)findViewById(R.id.detail_product_name);
thumbnail_textView = (TextView)findViewById(R.id.detail_product_thumbnail);
retrieveData();
}
public void retrieveData() {
String productName = getIntent().getStringExtra("Product Name");
String productThumbnail = getIntent().getStringExtra("Product Thumbnail");
System.out.println("productThumbnail Result" + productThumbnail);
thumbnail_textView.setText(productThumbnail);
name_textView.setText(productName);
}
java android xmlpullparser
add a comment |
[Here is a screenshot of the DetailActivity
&& Here is a screenshot of the Main Activity ][1]I am trying to parse an XML document using xmlPullParser
and distribute the retrieved data to two activities:
MainActivity
: includes 3 properties
DetailActivity
: includes all the other data.
I have two questions:
- How to parse all the tags and retrieve their data in xml document using
xmlPullParser
. - How to display the data of the
DetailActiviy
whenever aRecyclerView
item is clicked.
I have tried to parse the xml document twice. Once for the main data and second for the extra data i need for the detail activity either by opening connection twice (work around but too bad way) or by storing the retrieved data in a list and returning two new constructors instead of one(the list is not displaying anymore).
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements AdsAdapter.AdsAdapterOnClickHandler
{
public static final String URL = "DISPLAYED BELOW";
private static final String TAG = MainActivity.class.getSimpleName();
public static List entries = new ArrayList<>();
private RecyclerView mRecyclerView;
private AdsAdapter mAdsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_ad);
int recyclerViewOrientation = LinearLayoutManager.VERTICAL;
boolean shouldReverseLayout = false;
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, recyclerViewOrientation, shouldReverseLayout);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mAdsAdapter = new AdsAdapter(this);
mRecyclerView.setAdapter(mAdsAdapter);
loadPage();
}
public void loadPage() {
new DownloadXmlTask().execute(URL);
System.out.print("Result" + "Succeed");
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<AdEntry>>
{
@Override
protected List<AdEntry> doInBackground(String... urls)
{
try
{
return loadXmlFromNetwork(urls[0]);
}
catch (IOException e)
{
return null;
}
catch (XmlPullParserException e)
{
return null;
}
}
@Override
protected void onPostExecute(List<AdEntry> adEntries)
{
Toast.makeText(MainActivity.this, "Successfully Processed", Toast.LENGTH_SHORT).show();
System.out.println("Successfully Processed");
mAdsAdapter.setAdData(adEntries);
super.onPostExecute(adEntries);
}
}
public List<AdEntry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
try
{
stream = downloadUrl(urlString);
entries = parse(stream);
}
finally
{
if (stream != null)
stream.close();
}
System.out.println("FinalDataResult" + entries);
return entries;
}
public InputStream downloadUrl(String urlString) throws IOException
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
return conn.getInputStream();
}
@Override
public void onClick(AdEntry ad)
{
Context context = this;
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(context, destinationClass);
intentToStartDetailActivity.putExtra("Product Name",ad.productName);
intentToStartDetailActivity.putExtra("Product Thumbnail", ad.productThumbnail);;
startActivity(intentToStartDetailActivity);
}
}
Here is my XMLPullParser:
public class AdXmlParser {
private static final String ns = null;
public static List parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readAds(parser);
} finally {
in.close();
}
}
public static List detailParse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readExtras(parser);
} finally {
in.close();
}
}
private static List readAds(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> entries = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("ad"))
entries.add(readEntry(parser));
else
skip(parser);
}
System.out.println("entries" + entries);
return entries;
}
private static List<AdEntry> readExtras(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> extras = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("ad")) {
extras.add(readExtraData(parser));
} else {
skip(parser);
}
}
return extras;
}
private static AdEntry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String productName = null;
String productThumbnail = null;
String rating = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
switch (name) {
case "productName":
productName = readNameProduct(parser);
System.out.println("productName" + productName);
break;
case "productThumbnail":
productThumbnail = readThumbnail(parser);
System.out.println("productThumbnail" + productThumbnail);
break;
case "rating":
rating = readRating(parser);
System.out.println("rating" + rating);
break;
default:
skip(parser);
break;
}
}
return new AdEntry(productName, productThumbnail, rating);
}
private static AdEntry readExtraData(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String averageRatingImageURL = null;
String numberOfRatings = null;
String categoryName = null;
String appId = null;
String productDescription = null;
String clickProxyURL = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("averageRatingImageURL")) {
averageRatingImageURL = readRating(parser);
System.out.println("rating" + averageRatingImageURL);
} else if (name.equals("numberOfRatings")) {
numberOfRatings = readNumberOfRatings(parser);
System.out.println("numberOfRatings" + numberOfRatings);
} else if (name.equals("categoryName")) {
categoryName = readCategoryName(parser);
System.out.println("categoryName" + categoryName);
} else if (name.equals("appId")) {
appId = readAppId(parser);
System.out.println("appId" + appId);
} else if (name.equals("productDescription")) {
productDescription = readProductDescription(parser);
System.out.println("productDescription" + productDescription);
} else if (name.equals("clickProxyURL")) {
productDescription = readProxyLink(parser);
System.out.println("clickProxyURL" + clickProxyURL);
} else
skip(parser);
}
return new AdEntry(averageRatingImageURL, productDescription, categoryName, numberOfRatings, appId, clickProxyURL);
}
private static String readProxyLink(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "clickProxyURL");
String clickProxyURL = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "clickProxyURL");
return clickProxyURL;
}
private static String readProductDescription(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productDescription");
String productDescription = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productDescription");
return productDescription;
}
private static String readAppId(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "appId");
String appId = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "appId");
return appId;
}
private static String readNameProduct(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productName");
String productName = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productName");
return productName;
}
private static String readThumbnail(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productThumbnail");
String productThumbnail = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productThumbnail");
return productThumbnail;
}
private static String readNumberOfRatings(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "numberOfRatings");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "numberOfRatings");
return numberOfRatings;
}
private static String readCategoryName(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "categoryName");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "categoryName");
return numberOfRatings;
}
private static String readRating(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "rating");
String rating = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "rating");
return rating;
}
private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG)
throw new IllegalStateException();
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
Here is my Adapter:
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsAdapterViewHolder> {
final private AdsAdapterOnClickHandler mClickHandler;
public TextView thumbnail_textView;
public TextView name_textView;
public TextView rating_textView;
private List<AdEntry> mAdData;
public AdsAdapter(AdsAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
@Override
public AdsAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.ad_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new AdsAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(AdsAdapterViewHolder adsAdapterViewHolder, int position) {
AdEntry ad_item = mAdData.get(position);
String thumbnail = ad_item.getProductThumbnail();
name_textView.setText(thumbnail);
String productName = ad_item.getProductName();
thumbnail_textView.setText(productName);
String productRating = ad_item.getProductRating();
rating_textView.setText(productRating);
}
@Override
public int getItemCount() {
if (null == mAdData) return 0;
return mAdData.size();
}
public void setAdData(List<AdEntry> adData) {
mAdData = adData;
System.out.println("mAdData Result" + mAdData);
notifyDataSetChanged();
}
public interface AdsAdapterOnClickHandler {
void onClick(AdEntry ad);
}
public class AdsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public AdsAdapterViewHolder(View view) {
super(view);
thumbnail_textView = (TextView) view.findViewById(R.id.detail_product_thumbnail);
name_textView = (TextView)view.findViewById(R.id.product_name);
rating_textView = (TextView)view.findViewById(R.id.product_rating);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
AdEntry ad = mAdData.get(adapterPosition);
mClickHandler.onClick(ad);
}
}
}
Here is the XML Document I am trying to parse:
<ad>
<appId>com.zynga.ozmatch</appId>
<averageRatingImageURL>
https://cdn1.appia.com/cdn/adpub/appwallv1/rated-5-5.png
</averageRatingImageURL>
<bidRate>0.000</bidRate>
<billingTypeId>1</billingTypeId>
<callToAction>Install Now</callToAction>
<campaignDisplayOrder>1</campaignDisplayOrder>
<campaignId>24058</campaignId>
<campaignTypeId>2</campaignTypeId>
<categoryName>Puzzle</categoryName>
<clickProxyURL>
http://prlds.appia.com/v2/preloadAd.jsp?siteId=10777&deviceId=4230&spotId=&sessionId=techtestsession&campaignId=24058&creativeId=483970&packageName=com.zynga.ozmatch&fulfillmentTypeId=1&placementId=&campaignDisplayOrder=1&enc=true&ts=1680f0e88d8&algorithmId=-4&partner=154&homeScreen=false
</clickProxyURL>
<creativeId>483970</creativeId>
<homeScreen>false</homeScreen>
<impressionTrackingURL>
https://imps.appia.com/v2/impressionAd.jsp?siteId=10777&campaignId=24058&creativeId=483970&campaignDisplayOrder=1&ts=1680f0e88d8&sessionId=techtestsession&packageName=com.zynga.ozmatch&enc=true&eventGroupId=EVTGID1546440837284181712958668&algorithmId=-4&partner=154
</impressionTrackingURL>
<isRandomPick>false</isRandomPick>
<numberOfRatings>10,000+</numberOfRatings>
<productDescription>
Match your way to meet the wonderful Wizard of Oz in this amazing puzzle adventure!
</productDescription>
<productId>15338</productId>
<productName>Wizard of Oz: Magic Match</productName>
<productThumbnail>
https://prod-static-images.s3.amazonaws.com/shared/creatives/15338/1385be772f424a3cb42cd8f07747b05b.png
</productThumbnail>
<rating>5.0</rating>
</ad>
Here is my model Class:
public class AdEntry {
public String productThumbnail;
public String productName;
public String productRating ;
public String productDescription;
public String productCategory;
public String numberOfRatings;
public String appId;
public String proxyLink;
public String averageRatingImageURL;
public AdEntry(String productThumbnail, String productName, String productRating) {
this.productThumbnail = productThumbnail;
this.productName = productName;
this.productRating = productRating;
}
public AdEntry(String productRating, String productDescription, String productCategory, String numberOfRatings, String appId, String proxyLink){
this.productRating = productRating;
this.productDescription = productDescription;
this.productCategory = productCategory;
this.numberOfRatings = numberOfRatings;
this.appId = appId;
this.proxyLink = proxyLink;
}
public String getProductThumbnail() {
return productThumbnail;
}
public String getProductName() {
return productName;
}
public String getProductRating() {
return productRating;
}
public String getProductDescription() {
return productDescription;
}
public String getProductCategory() {
return productCategory;
}
public String getNumberOfRatings() {
return numberOfRatings;
}
public String getAppId() {
return appId;
}
public String getProxyLink() {
return proxyLink;
}
public String getAverageRatingImageURL() {
return averageRatingImageURL;
}
}
Here is the DetailActivity:
public class DetailActivity extends AppCompatActivity {
private static List<AdEntry> entries = new ArrayList<>();
public TextView description_textView;
public TextView category_textView;
public TextView rating_textView;
public TextView link_textView;
public TextView numberOfRating_textView;
public TextView name_textView;
public TextView thumbnail_textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
name_textView = (TextView)findViewById(R.id.detail_product_name);
thumbnail_textView = (TextView)findViewById(R.id.detail_product_thumbnail);
retrieveData();
}
public void retrieveData() {
String productName = getIntent().getStringExtra("Product Name");
String productThumbnail = getIntent().getStringExtra("Product Thumbnail");
System.out.println("productThumbnail Result" + productThumbnail);
thumbnail_textView.setText(productThumbnail);
name_textView.setText(productName);
}
java android xmlpullparser
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jan 2 at 23:07
add a comment |
[Here is a screenshot of the DetailActivity
&& Here is a screenshot of the Main Activity ][1]I am trying to parse an XML document using xmlPullParser
and distribute the retrieved data to two activities:
MainActivity
: includes 3 properties
DetailActivity
: includes all the other data.
I have two questions:
- How to parse all the tags and retrieve their data in xml document using
xmlPullParser
. - How to display the data of the
DetailActiviy
whenever aRecyclerView
item is clicked.
I have tried to parse the xml document twice. Once for the main data and second for the extra data i need for the detail activity either by opening connection twice (work around but too bad way) or by storing the retrieved data in a list and returning two new constructors instead of one(the list is not displaying anymore).
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements AdsAdapter.AdsAdapterOnClickHandler
{
public static final String URL = "DISPLAYED BELOW";
private static final String TAG = MainActivity.class.getSimpleName();
public static List entries = new ArrayList<>();
private RecyclerView mRecyclerView;
private AdsAdapter mAdsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_ad);
int recyclerViewOrientation = LinearLayoutManager.VERTICAL;
boolean shouldReverseLayout = false;
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, recyclerViewOrientation, shouldReverseLayout);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mAdsAdapter = new AdsAdapter(this);
mRecyclerView.setAdapter(mAdsAdapter);
loadPage();
}
public void loadPage() {
new DownloadXmlTask().execute(URL);
System.out.print("Result" + "Succeed");
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<AdEntry>>
{
@Override
protected List<AdEntry> doInBackground(String... urls)
{
try
{
return loadXmlFromNetwork(urls[0]);
}
catch (IOException e)
{
return null;
}
catch (XmlPullParserException e)
{
return null;
}
}
@Override
protected void onPostExecute(List<AdEntry> adEntries)
{
Toast.makeText(MainActivity.this, "Successfully Processed", Toast.LENGTH_SHORT).show();
System.out.println("Successfully Processed");
mAdsAdapter.setAdData(adEntries);
super.onPostExecute(adEntries);
}
}
public List<AdEntry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
try
{
stream = downloadUrl(urlString);
entries = parse(stream);
}
finally
{
if (stream != null)
stream.close();
}
System.out.println("FinalDataResult" + entries);
return entries;
}
public InputStream downloadUrl(String urlString) throws IOException
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
return conn.getInputStream();
}
@Override
public void onClick(AdEntry ad)
{
Context context = this;
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(context, destinationClass);
intentToStartDetailActivity.putExtra("Product Name",ad.productName);
intentToStartDetailActivity.putExtra("Product Thumbnail", ad.productThumbnail);;
startActivity(intentToStartDetailActivity);
}
}
Here is my XMLPullParser:
public class AdXmlParser {
private static final String ns = null;
public static List parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readAds(parser);
} finally {
in.close();
}
}
public static List detailParse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readExtras(parser);
} finally {
in.close();
}
}
private static List readAds(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> entries = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("ad"))
entries.add(readEntry(parser));
else
skip(parser);
}
System.out.println("entries" + entries);
return entries;
}
private static List<AdEntry> readExtras(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> extras = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("ad")) {
extras.add(readExtraData(parser));
} else {
skip(parser);
}
}
return extras;
}
private static AdEntry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String productName = null;
String productThumbnail = null;
String rating = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
switch (name) {
case "productName":
productName = readNameProduct(parser);
System.out.println("productName" + productName);
break;
case "productThumbnail":
productThumbnail = readThumbnail(parser);
System.out.println("productThumbnail" + productThumbnail);
break;
case "rating":
rating = readRating(parser);
System.out.println("rating" + rating);
break;
default:
skip(parser);
break;
}
}
return new AdEntry(productName, productThumbnail, rating);
}
private static AdEntry readExtraData(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String averageRatingImageURL = null;
String numberOfRatings = null;
String categoryName = null;
String appId = null;
String productDescription = null;
String clickProxyURL = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("averageRatingImageURL")) {
averageRatingImageURL = readRating(parser);
System.out.println("rating" + averageRatingImageURL);
} else if (name.equals("numberOfRatings")) {
numberOfRatings = readNumberOfRatings(parser);
System.out.println("numberOfRatings" + numberOfRatings);
} else if (name.equals("categoryName")) {
categoryName = readCategoryName(parser);
System.out.println("categoryName" + categoryName);
} else if (name.equals("appId")) {
appId = readAppId(parser);
System.out.println("appId" + appId);
} else if (name.equals("productDescription")) {
productDescription = readProductDescription(parser);
System.out.println("productDescription" + productDescription);
} else if (name.equals("clickProxyURL")) {
productDescription = readProxyLink(parser);
System.out.println("clickProxyURL" + clickProxyURL);
} else
skip(parser);
}
return new AdEntry(averageRatingImageURL, productDescription, categoryName, numberOfRatings, appId, clickProxyURL);
}
private static String readProxyLink(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "clickProxyURL");
String clickProxyURL = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "clickProxyURL");
return clickProxyURL;
}
private static String readProductDescription(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productDescription");
String productDescription = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productDescription");
return productDescription;
}
private static String readAppId(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "appId");
String appId = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "appId");
return appId;
}
private static String readNameProduct(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productName");
String productName = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productName");
return productName;
}
private static String readThumbnail(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productThumbnail");
String productThumbnail = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productThumbnail");
return productThumbnail;
}
private static String readNumberOfRatings(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "numberOfRatings");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "numberOfRatings");
return numberOfRatings;
}
private static String readCategoryName(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "categoryName");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "categoryName");
return numberOfRatings;
}
private static String readRating(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "rating");
String rating = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "rating");
return rating;
}
private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG)
throw new IllegalStateException();
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
Here is my Adapter:
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsAdapterViewHolder> {
final private AdsAdapterOnClickHandler mClickHandler;
public TextView thumbnail_textView;
public TextView name_textView;
public TextView rating_textView;
private List<AdEntry> mAdData;
public AdsAdapter(AdsAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
@Override
public AdsAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.ad_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new AdsAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(AdsAdapterViewHolder adsAdapterViewHolder, int position) {
AdEntry ad_item = mAdData.get(position);
String thumbnail = ad_item.getProductThumbnail();
name_textView.setText(thumbnail);
String productName = ad_item.getProductName();
thumbnail_textView.setText(productName);
String productRating = ad_item.getProductRating();
rating_textView.setText(productRating);
}
@Override
public int getItemCount() {
if (null == mAdData) return 0;
return mAdData.size();
}
public void setAdData(List<AdEntry> adData) {
mAdData = adData;
System.out.println("mAdData Result" + mAdData);
notifyDataSetChanged();
}
public interface AdsAdapterOnClickHandler {
void onClick(AdEntry ad);
}
public class AdsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public AdsAdapterViewHolder(View view) {
super(view);
thumbnail_textView = (TextView) view.findViewById(R.id.detail_product_thumbnail);
name_textView = (TextView)view.findViewById(R.id.product_name);
rating_textView = (TextView)view.findViewById(R.id.product_rating);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
AdEntry ad = mAdData.get(adapterPosition);
mClickHandler.onClick(ad);
}
}
}
Here is the XML Document I am trying to parse:
<ad>
<appId>com.zynga.ozmatch</appId>
<averageRatingImageURL>
https://cdn1.appia.com/cdn/adpub/appwallv1/rated-5-5.png
</averageRatingImageURL>
<bidRate>0.000</bidRate>
<billingTypeId>1</billingTypeId>
<callToAction>Install Now</callToAction>
<campaignDisplayOrder>1</campaignDisplayOrder>
<campaignId>24058</campaignId>
<campaignTypeId>2</campaignTypeId>
<categoryName>Puzzle</categoryName>
<clickProxyURL>
http://prlds.appia.com/v2/preloadAd.jsp?siteId=10777&deviceId=4230&spotId=&sessionId=techtestsession&campaignId=24058&creativeId=483970&packageName=com.zynga.ozmatch&fulfillmentTypeId=1&placementId=&campaignDisplayOrder=1&enc=true&ts=1680f0e88d8&algorithmId=-4&partner=154&homeScreen=false
</clickProxyURL>
<creativeId>483970</creativeId>
<homeScreen>false</homeScreen>
<impressionTrackingURL>
https://imps.appia.com/v2/impressionAd.jsp?siteId=10777&campaignId=24058&creativeId=483970&campaignDisplayOrder=1&ts=1680f0e88d8&sessionId=techtestsession&packageName=com.zynga.ozmatch&enc=true&eventGroupId=EVTGID1546440837284181712958668&algorithmId=-4&partner=154
</impressionTrackingURL>
<isRandomPick>false</isRandomPick>
<numberOfRatings>10,000+</numberOfRatings>
<productDescription>
Match your way to meet the wonderful Wizard of Oz in this amazing puzzle adventure!
</productDescription>
<productId>15338</productId>
<productName>Wizard of Oz: Magic Match</productName>
<productThumbnail>
https://prod-static-images.s3.amazonaws.com/shared/creatives/15338/1385be772f424a3cb42cd8f07747b05b.png
</productThumbnail>
<rating>5.0</rating>
</ad>
Here is my model Class:
public class AdEntry {
public String productThumbnail;
public String productName;
public String productRating ;
public String productDescription;
public String productCategory;
public String numberOfRatings;
public String appId;
public String proxyLink;
public String averageRatingImageURL;
public AdEntry(String productThumbnail, String productName, String productRating) {
this.productThumbnail = productThumbnail;
this.productName = productName;
this.productRating = productRating;
}
public AdEntry(String productRating, String productDescription, String productCategory, String numberOfRatings, String appId, String proxyLink){
this.productRating = productRating;
this.productDescription = productDescription;
this.productCategory = productCategory;
this.numberOfRatings = numberOfRatings;
this.appId = appId;
this.proxyLink = proxyLink;
}
public String getProductThumbnail() {
return productThumbnail;
}
public String getProductName() {
return productName;
}
public String getProductRating() {
return productRating;
}
public String getProductDescription() {
return productDescription;
}
public String getProductCategory() {
return productCategory;
}
public String getNumberOfRatings() {
return numberOfRatings;
}
public String getAppId() {
return appId;
}
public String getProxyLink() {
return proxyLink;
}
public String getAverageRatingImageURL() {
return averageRatingImageURL;
}
}
Here is the DetailActivity:
public class DetailActivity extends AppCompatActivity {
private static List<AdEntry> entries = new ArrayList<>();
public TextView description_textView;
public TextView category_textView;
public TextView rating_textView;
public TextView link_textView;
public TextView numberOfRating_textView;
public TextView name_textView;
public TextView thumbnail_textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
name_textView = (TextView)findViewById(R.id.detail_product_name);
thumbnail_textView = (TextView)findViewById(R.id.detail_product_thumbnail);
retrieveData();
}
public void retrieveData() {
String productName = getIntent().getStringExtra("Product Name");
String productThumbnail = getIntent().getStringExtra("Product Thumbnail");
System.out.println("productThumbnail Result" + productThumbnail);
thumbnail_textView.setText(productThumbnail);
name_textView.setText(productName);
}
java android xmlpullparser
[Here is a screenshot of the DetailActivity
&& Here is a screenshot of the Main Activity ][1]I am trying to parse an XML document using xmlPullParser
and distribute the retrieved data to two activities:
MainActivity
: includes 3 properties
DetailActivity
: includes all the other data.
I have two questions:
- How to parse all the tags and retrieve their data in xml document using
xmlPullParser
. - How to display the data of the
DetailActiviy
whenever aRecyclerView
item is clicked.
I have tried to parse the xml document twice. Once for the main data and second for the extra data i need for the detail activity either by opening connection twice (work around but too bad way) or by storing the retrieved data in a list and returning two new constructors instead of one(the list is not displaying anymore).
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements AdsAdapter.AdsAdapterOnClickHandler
{
public static final String URL = "DISPLAYED BELOW";
private static final String TAG = MainActivity.class.getSimpleName();
public static List entries = new ArrayList<>();
private RecyclerView mRecyclerView;
private AdsAdapter mAdsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_ad);
int recyclerViewOrientation = LinearLayoutManager.VERTICAL;
boolean shouldReverseLayout = false;
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, recyclerViewOrientation, shouldReverseLayout);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mAdsAdapter = new AdsAdapter(this);
mRecyclerView.setAdapter(mAdsAdapter);
loadPage();
}
public void loadPage() {
new DownloadXmlTask().execute(URL);
System.out.print("Result" + "Succeed");
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<AdEntry>>
{
@Override
protected List<AdEntry> doInBackground(String... urls)
{
try
{
return loadXmlFromNetwork(urls[0]);
}
catch (IOException e)
{
return null;
}
catch (XmlPullParserException e)
{
return null;
}
}
@Override
protected void onPostExecute(List<AdEntry> adEntries)
{
Toast.makeText(MainActivity.this, "Successfully Processed", Toast.LENGTH_SHORT).show();
System.out.println("Successfully Processed");
mAdsAdapter.setAdData(adEntries);
super.onPostExecute(adEntries);
}
}
public List<AdEntry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
try
{
stream = downloadUrl(urlString);
entries = parse(stream);
}
finally
{
if (stream != null)
stream.close();
}
System.out.println("FinalDataResult" + entries);
return entries;
}
public InputStream downloadUrl(String urlString) throws IOException
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
return conn.getInputStream();
}
@Override
public void onClick(AdEntry ad)
{
Context context = this;
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(context, destinationClass);
intentToStartDetailActivity.putExtra("Product Name",ad.productName);
intentToStartDetailActivity.putExtra("Product Thumbnail", ad.productThumbnail);;
startActivity(intentToStartDetailActivity);
}
}
Here is my XMLPullParser:
public class AdXmlParser {
private static final String ns = null;
public static List parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readAds(parser);
} finally {
in.close();
}
}
public static List detailParse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readExtras(parser);
} finally {
in.close();
}
}
private static List readAds(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> entries = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("ad"))
entries.add(readEntry(parser));
else
skip(parser);
}
System.out.println("entries" + entries);
return entries;
}
private static List<AdEntry> readExtras(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> extras = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("ad")) {
extras.add(readExtraData(parser));
} else {
skip(parser);
}
}
return extras;
}
private static AdEntry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String productName = null;
String productThumbnail = null;
String rating = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
switch (name) {
case "productName":
productName = readNameProduct(parser);
System.out.println("productName" + productName);
break;
case "productThumbnail":
productThumbnail = readThumbnail(parser);
System.out.println("productThumbnail" + productThumbnail);
break;
case "rating":
rating = readRating(parser);
System.out.println("rating" + rating);
break;
default:
skip(parser);
break;
}
}
return new AdEntry(productName, productThumbnail, rating);
}
private static AdEntry readExtraData(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
String averageRatingImageURL = null;
String numberOfRatings = null;
String categoryName = null;
String appId = null;
String productDescription = null;
String clickProxyURL = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("averageRatingImageURL")) {
averageRatingImageURL = readRating(parser);
System.out.println("rating" + averageRatingImageURL);
} else if (name.equals("numberOfRatings")) {
numberOfRatings = readNumberOfRatings(parser);
System.out.println("numberOfRatings" + numberOfRatings);
} else if (name.equals("categoryName")) {
categoryName = readCategoryName(parser);
System.out.println("categoryName" + categoryName);
} else if (name.equals("appId")) {
appId = readAppId(parser);
System.out.println("appId" + appId);
} else if (name.equals("productDescription")) {
productDescription = readProductDescription(parser);
System.out.println("productDescription" + productDescription);
} else if (name.equals("clickProxyURL")) {
productDescription = readProxyLink(parser);
System.out.println("clickProxyURL" + clickProxyURL);
} else
skip(parser);
}
return new AdEntry(averageRatingImageURL, productDescription, categoryName, numberOfRatings, appId, clickProxyURL);
}
private static String readProxyLink(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "clickProxyURL");
String clickProxyURL = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "clickProxyURL");
return clickProxyURL;
}
private static String readProductDescription(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productDescription");
String productDescription = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productDescription");
return productDescription;
}
private static String readAppId(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "appId");
String appId = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "appId");
return appId;
}
private static String readNameProduct(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productName");
String productName = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productName");
return productName;
}
private static String readThumbnail(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "productThumbnail");
String productThumbnail = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "productThumbnail");
return productThumbnail;
}
private static String readNumberOfRatings(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "numberOfRatings");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "numberOfRatings");
return numberOfRatings;
}
private static String readCategoryName(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "categoryName");
String numberOfRatings = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "categoryName");
return numberOfRatings;
}
private static String readRating(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "rating");
String rating = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "rating");
return rating;
}
private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG)
throw new IllegalStateException();
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
Here is my Adapter:
public class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.AdsAdapterViewHolder> {
final private AdsAdapterOnClickHandler mClickHandler;
public TextView thumbnail_textView;
public TextView name_textView;
public TextView rating_textView;
private List<AdEntry> mAdData;
public AdsAdapter(AdsAdapterOnClickHandler clickHandler) {
mClickHandler = clickHandler;
}
@Override
public AdsAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.ad_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new AdsAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(AdsAdapterViewHolder adsAdapterViewHolder, int position) {
AdEntry ad_item = mAdData.get(position);
String thumbnail = ad_item.getProductThumbnail();
name_textView.setText(thumbnail);
String productName = ad_item.getProductName();
thumbnail_textView.setText(productName);
String productRating = ad_item.getProductRating();
rating_textView.setText(productRating);
}
@Override
public int getItemCount() {
if (null == mAdData) return 0;
return mAdData.size();
}
public void setAdData(List<AdEntry> adData) {
mAdData = adData;
System.out.println("mAdData Result" + mAdData);
notifyDataSetChanged();
}
public interface AdsAdapterOnClickHandler {
void onClick(AdEntry ad);
}
public class AdsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public AdsAdapterViewHolder(View view) {
super(view);
thumbnail_textView = (TextView) view.findViewById(R.id.detail_product_thumbnail);
name_textView = (TextView)view.findViewById(R.id.product_name);
rating_textView = (TextView)view.findViewById(R.id.product_rating);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
AdEntry ad = mAdData.get(adapterPosition);
mClickHandler.onClick(ad);
}
}
}
Here is the XML Document I am trying to parse:
<ad>
<appId>com.zynga.ozmatch</appId>
<averageRatingImageURL>
https://cdn1.appia.com/cdn/adpub/appwallv1/rated-5-5.png
</averageRatingImageURL>
<bidRate>0.000</bidRate>
<billingTypeId>1</billingTypeId>
<callToAction>Install Now</callToAction>
<campaignDisplayOrder>1</campaignDisplayOrder>
<campaignId>24058</campaignId>
<campaignTypeId>2</campaignTypeId>
<categoryName>Puzzle</categoryName>
<clickProxyURL>
http://prlds.appia.com/v2/preloadAd.jsp?siteId=10777&deviceId=4230&spotId=&sessionId=techtestsession&campaignId=24058&creativeId=483970&packageName=com.zynga.ozmatch&fulfillmentTypeId=1&placementId=&campaignDisplayOrder=1&enc=true&ts=1680f0e88d8&algorithmId=-4&partner=154&homeScreen=false
</clickProxyURL>
<creativeId>483970</creativeId>
<homeScreen>false</homeScreen>
<impressionTrackingURL>
https://imps.appia.com/v2/impressionAd.jsp?siteId=10777&campaignId=24058&creativeId=483970&campaignDisplayOrder=1&ts=1680f0e88d8&sessionId=techtestsession&packageName=com.zynga.ozmatch&enc=true&eventGroupId=EVTGID1546440837284181712958668&algorithmId=-4&partner=154
</impressionTrackingURL>
<isRandomPick>false</isRandomPick>
<numberOfRatings>10,000+</numberOfRatings>
<productDescription>
Match your way to meet the wonderful Wizard of Oz in this amazing puzzle adventure!
</productDescription>
<productId>15338</productId>
<productName>Wizard of Oz: Magic Match</productName>
<productThumbnail>
https://prod-static-images.s3.amazonaws.com/shared/creatives/15338/1385be772f424a3cb42cd8f07747b05b.png
</productThumbnail>
<rating>5.0</rating>
</ad>
Here is my model Class:
public class AdEntry {
public String productThumbnail;
public String productName;
public String productRating ;
public String productDescription;
public String productCategory;
public String numberOfRatings;
public String appId;
public String proxyLink;
public String averageRatingImageURL;
public AdEntry(String productThumbnail, String productName, String productRating) {
this.productThumbnail = productThumbnail;
this.productName = productName;
this.productRating = productRating;
}
public AdEntry(String productRating, String productDescription, String productCategory, String numberOfRatings, String appId, String proxyLink){
this.productRating = productRating;
this.productDescription = productDescription;
this.productCategory = productCategory;
this.numberOfRatings = numberOfRatings;
this.appId = appId;
this.proxyLink = proxyLink;
}
public String getProductThumbnail() {
return productThumbnail;
}
public String getProductName() {
return productName;
}
public String getProductRating() {
return productRating;
}
public String getProductDescription() {
return productDescription;
}
public String getProductCategory() {
return productCategory;
}
public String getNumberOfRatings() {
return numberOfRatings;
}
public String getAppId() {
return appId;
}
public String getProxyLink() {
return proxyLink;
}
public String getAverageRatingImageURL() {
return averageRatingImageURL;
}
}
Here is the DetailActivity:
public class DetailActivity extends AppCompatActivity {
private static List<AdEntry> entries = new ArrayList<>();
public TextView description_textView;
public TextView category_textView;
public TextView rating_textView;
public TextView link_textView;
public TextView numberOfRating_textView;
public TextView name_textView;
public TextView thumbnail_textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
name_textView = (TextView)findViewById(R.id.detail_product_name);
thumbnail_textView = (TextView)findViewById(R.id.detail_product_thumbnail);
retrieveData();
}
public void retrieveData() {
String productName = getIntent().getStringExtra("Product Name");
String productThumbnail = getIntent().getStringExtra("Product Thumbnail");
System.out.println("productThumbnail Result" + productThumbnail);
thumbnail_textView.setText(productThumbnail);
name_textView.setText(productName);
}
java android xmlpullparser
java android xmlpullparser
edited Jan 2 at 20:26
Laura
asked Jan 2 at 18:04
LauraLaura
13
13
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jan 2 at 23:07
add a comment |
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jan 2 at 23:07
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jan 2 at 23:07
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jan 2 at 23:07
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54011081%2fhow-to-retrieve-all-data-from-an-xml-document-using-xmlpullparser-and-how-to-sto%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54011081%2fhow-to-retrieve-all-data-from-an-xml-document-using-xmlpullparser-and-how-to-sto%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jan 2 at 23:07