First item in ListView from Adapter is missing some constraints - java
Having an issue that popped up recently with seemingly no change to my code. With a list of news that's fetched, the first item in the list always has broken constraints.
The template is a vertical linear layout, that has the title, and a constraint layout under that with the image, description, source, and time of the article. The information gets placed into the template via a custom adapter class, which nothing has changed in since the issue started.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layNewsBackground"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:background="#color/colorDarkSurface1dp"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="6dp"
android:ellipsize="end"
android:fontFamily="#font/source_sans_pro"
android:maxLines="1"
android:scrollHorizontally="true"
android:textAlignment="viewStart"
android:textSize="17sp"
android:textStyle="bold"
tools:text="This is the news title" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="#android:color/transparent"
app:cardCornerRadius="4dp"
app:cardElevation="0dp"
app:cardPreventCornerOverlap="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/galleryImage"
android:layout_width="70dp"
android:layout_height="70dp"
android:contentDescription="TODO" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/sdetails"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:ellipsize="end"
android:fontFamily="#font/source_sans_pro"
android:maxLines="2"
android:minLines="2"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/cardView"
app:layout_constraintTop_toTopOf="parent"
tools:text="Description" />
<TextView
android:id="#+id/source"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/source_sans_pro"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/cardView"
tools:text="Source" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/source_sans_pro"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Time" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
{
"status": "ok",
"totalResults": 41,
"articles": [
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Brian Fung, CNN Business",
"title": "It's never been easier to start a social network. Succeeding is another story",
"description": "So what does it take to launch a successful social platform in the year 2021? The answer is part technical and part strategy, and the breakdown between the two reflects how dramatically different the challenges are for new entrepreneurs compared to the days o…",
"url": "https://www.cnn.com/2021/04/08/tech/social-media-startups/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210406133012-clubhouse-social-media-startups---stock-super-tease.jpg",
"publishedAt": "2021-04-08T13:55:39Z",
"content": "(CNN Business)Former President Donald Trump lost his most-prized megaphone when he was suspended from Facebook and Twitter earlier this year. Since then, he's largely stuck with canned press statemen… [+7456 chars]"
},
{
"source": {
"id": "the-globe-and-mail",
"name": "The Globe And Mail"
},
"author": "Stephen Nellis",
"title": "Apple will argue it faces competition in video game transaction market in Epic lawsuit - The Globe and Mail",
"description": "The dispute arose after Epic tried to implement its own in-app payment system in the popular Fortnite game and Apple subsequently banned the game from its App Store",
"url": "https://www.theglobeandmail.com/business/technology/article-apple-will-argue-it-faces-competition-in-video-game-transaction-market/",
"urlToImage": "https://www.theglobeandmail.com/resizer/fWGZOwQ8InxKixRf7H_p8rDAn2Y=/1200x0/filters:quality(80)/cloudfront-us-east-1.images.arcpublishing.com/tgam/6PBYASTO75J4VLBKZ4THZYACXU.JPG",
"publishedAt": "2021-04-08T10:41:56Z",
"content": "Apple Inc said it plans to argue that it faces abundant competition in the market for video game transactions to defend itself against antitrust allegations by Fortnite maker Epic Games, the iPhone m… [+2022 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Theresa Waldrop, CNN",
"title": "There's a lot of debate about vaccine passports right now. What are they, and how would they work?",
"description": "With millions of Americans being vaccinated against Covid-19 every day, a heated debate is underway -- do these people need proof of immunization in the form of a vaccine passport?",
"url": "https://www.cnn.com/2021/04/07/us/covid-vaccine-passport-explainer/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210324154815-02-new-york-excelsior-pass-ibm-super-tease.jpg",
"publishedAt": "2021-04-08T01:59:40Z",
"content": "(CNN)With millions of Americans being vaccinated against Covid-19 every day, a heated debate is underway -- do these people need proof of immunization in the form of a vaccine passport?\r\nJust like a … [+5359 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Clare Duffy, CNN Business",
"title": "Fintech firm Plaid announces $425 million funding round",
"description": "Financial technology firm Plaid on Wednesday announced a $425 million Series D funding round, more than doubling the total amount the company has raised since its 2012 founding.",
"url": "https://www.cnn.com/2021/04/07/tech/plaid-funding-425-million/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210406201158-zach-perret-jan-2020-super-tease.jpg",
"publishedAt": "2021-04-07T11:00:04Z",
"content": "New York (CNN Business)Financial technology firm Plaid on Wednesday announced a $425 million Series D funding round, more than doubling the total amount the company has raised since its 2012 founding… [+2928 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Matt Villano, CNN",
"title": "World Autism Awareness Day 2021: What you need to know",
"description": "World Autism Awareness Day, which is April 2, encourages awareness about the existence of autism and the roughly 4 million autistic individuals around the world.",
"url": "https://www.cnn.com/2021/04/02/health/autism-awareness-day-wellness/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210401142347-autism-awareness-wellness-super-tease.jpg",
"publishedAt": "2021-04-02T11:24:15Z",
"content": "(CNN)In many ways, Kevin \"Knox\" Johnson III is just like most 8-year-olds.\r\nThe kid enjoys building marble runs. He's obsessed with knock-knock jokes. In school, he excels at math and learning langua… [+8788 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Zachary Cohen, Alex Marquardt and Geneva Sands, CNN",
"title": "Hunting the hunters: How Russian hackers targeted US cyber first responders in SolarWinds breach",
"description": "After infiltrating US government computer networks early last year as part of the SolarWinds data breach, Russian hackers then turned their attention to the very people whose job was to track them down.",
"url": "https://www.cnn.com/2021/04/02/politics/russian-hackers-target-us-cyber-hunters-solarwinds/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/181217084838-20181217-russia-social-media-super-tease.jpg",
"publishedAt": "2021-04-02T10:00:10Z",
"content": "Washington (CNN)After infiltrating US government computer networks early last year as part of the SolarWinds data breach, Russian hackers then turned their attention to the very people whose job was … [+7658 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "By Michael Andronico, Jason Cipriani and Jacob Krol, CNN",
"title": "The best laptops of 2021",
"description": "We spent months testing the latest and greatest laptops we could get our hands on, from Apple to Dell to Microsoft to Lenovo, and we've found the best options for any of your needs.",
"url": "https://www.cnn.com/2021/04/01/cnn-underscored/best-laptops/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/201207080817-best-laptops-lead-december-lead-super-169.jpg",
"publishedAt": "2021-04-01T17:27:02Z",
"content": "Buying a new laptop is both an exciting and potentially frustrating experience. Exciting, of course, because a powerful computer that allows you to communicate and work efficiently and keep yourself … [+28140 chars]"
},
{
"source": {
"id": "cbc-news",
"name": "CBC News"
},
"author": "Isabelle Leger",
"title": "Controversial candidate for Saint John mayor says he can relate to people",
"description": "A candidate for mayor of Saint John whose Facebook postings have included support for conspiracy theories and the January attack on the U.S. Capitol says the city needs a leader who doesn't fit the status quo.",
"url": "https://www.cbc.ca/news/canada/new-brunswick/darrell-bastarache-saint-john-mayor-1.5971169",
"urlToImage": "https://i.cbc.ca/1.5971442.1617213053!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/darrell-bastarache.jpg",
"publishedAt": "2021-03-31T20:33:50Z",
"content": "A candidate for mayor of Saint John whose Facebook postings have included support for conspiracy theories and the January attack on the U.S. Capitol says the city needs a leader who doesn't fit the s… [+2142 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Rishi Iyengar, CNN Business",
"title": "Silicon Valley is starting to bring workers back to the office",
"description": "After years of building huge modern offices and a work culture that many industries have emulated, Silicon Valley was among the first to shutter those offices and go fully remote when the coronavirus pandemic began.",
"url": "https://www.cnn.com/2021/03/31/tech/silicon-valley-office-return-uber-facebook/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210329184012-uber-mission-bay-file-restricted-super-tease.jpg",
"publishedAt": "2021-03-31T11:54:33Z",
"content": "San Francisco (CNN Business)After years of building huge modern offices and a work culture that many industries have emulated, Silicon Valley was among the first to shutter those offices and go fully… [+5899 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Rishi Iyengar and Jon Sarlin, CNN Business",
"title": "NFTs are suddenly everywhere, but they have some big problems",
"description": "For several weeks, it's been near impossible to exist on the internet without at least hearing a mention of NFTs. Short for non-fungible tokens, they are pieces of digital content linked to the blockchain, the digital database underpinning cryptocurrencies su…",
"url": "https://www.cnn.com/2021/03/30/tech/nft-hacking-theft-environment-concerns/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210326185518-03-nft-non-fungible-tokens---stock-super-tease.jpg",
"publishedAt": "2021-03-30T19:17:42Z",
"content": "(CNN Business)For several weeks, it's been near impossible to exist on the internet without at least hearing a mention of NFTs. Short for non-fungible tokens, they are pieces of digital content linke… [+8408 chars]"
},
{
"source": {
"id": "cbc-news",
"name": "CBC News"
},
"author": "Alan Suderman",
"title": "Russian hackers found to have accessed email of U.S. Homeland Security head, cybersecurity staff",
"description": "Suspected Russian hackers gained access to email accounts belonging to the Trump administration's head of the U.S. Department of Homeland Security and members of the department's cybersecurity staff whose jobs included hunting threats from foreign countries, …",
"url": "https://www.cbc.ca/news/world/russian-hack-solarwinds-us-government-1.5968734",
"urlToImage": "https://i.cbc.ca/1.5968859.1617052097!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/dhs-wolf.jpg",
"publishedAt": "2021-03-29T21:56:55Z",
"content": "Suspected Russian hackers gained access to email accounts belonging to the Trump administration's head of the U.S. Department of Homeland Security and members of the department's cybersecurity staff … [+6112 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Samantha Murphy Kelly, CNN Business",
"title": "Vaccine passport apps could help us return to normal. First they need to solve the trust problem",
"description": "The next time you attend a wedding or concert, visit a place of worship, eat indoors at a restaurant or even go to work, you may need to show digital proof of vaccination or negative Covid-19 test results.",
"url": "https://www.cnn.com/2021/03/29/tech/vaccine-passport-app-privacy/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210324154623-01-new-york-excelsior-pass-ibm-super-tease.jpg",
"publishedAt": "2021-03-29T18:23:05Z",
"content": "(CNN)The next time you attend a wedding or concert, visit a place of worship, eat indoors at a restaurant or even go to work, you may need to show digital proof of vaccination or negative Covid-19 te… [+5455 chars]"
},
{
"source": {
"id": "the-globe-and-mail",
"name": "The Globe And Mail"
},
"author": null,
"title": "Reddit to open Toronto office as U.S. tech firms expand in Canada - The Globe and Mail",
"description": "The company said its Canadian user base is growing at a rate of more than 40 per cent year over year, and that they don’t necessarily overlap with traditional social-media users",
"url": "https://www.theglobeandmail.com/business/article-reddit-to-open-toronto-office-as-us-tech-firms-expand-in-canada/",
"urlToImage": "https://www.theglobeandmail.com/resizer/Hp1CCB57XMFHtoHudRhQ1C_75FE=/1200x0/filters:quality(80)/cloudfront-us-east-1.images.arcpublishing.com/tgam/DMLBCJJ4C5MCFHXEF7QFPYPHCI.JPG",
"publishedAt": "2021-03-29T09:00:00Z",
"content": "The company said its Canadian user base is growing at a rate of more than 40 per cent year over year, and that they dont necessarily overlap with traditional social-media users.\r\nDADO RUVIC/Reuters\r\n… [+5234 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Paul R. La Monica, CNN Business",
"title": "Here's why Cathie Wood and Kevin O'Leary are still bullish on growth stocks",
"description": "Tech stocks have taken a hit lately as investors continue to seek comfort in banks, big oil and other value sectors. But some fans of trendy momentum stocks aren't giving up on them just yet.",
"url": "https://www.cnn.com/2021/03/25/investing/cathie-wood-kevin-oleary-vaneck-stocks/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210325113901-cathie-wood-kevin-oleary-jan-van-eck-restricted-super-tease.jpg",
"publishedAt": "2021-03-25T18:01:16Z",
"content": "New York (CNN Business)Tech stocks have taken a hit lately as investors continue to seek comfort in banks, big oil and other value sectors. But some fans of trendy momentum stocks aren't giving up on… [+4491 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "By Michael Andronico",
"title": "Looking for an Xbox Series X? Here's how to have the best shot",
"description": "Still looking for an Xbox Series X? Here's how to have the best shot at securing Microsoft's latest game consoles.",
"url": "https://www.cnn.com/2021/03/25/cnn-underscored/xbox-series-x-restock/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/201104193945-5-xbox-series-x-review-underscored-super-169.jpg",
"publishedAt": "2021-03-25T17:30:12Z",
"content": "If youre reading this, chances are you havent gotten your hands on an Xbox Series X or Xbox Series S yet. And youre far from alone just like with the PS5, finding Microsofts newest consoles has been … [+7159 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Anna Bahney, CNN Business",
"title": "How four working mothers are doing a year into the pandemic",
"description": "It was only supposed to be for a few weeks. A few months at most. One year ago, when the pandemic shut down offices and schools, many working parents were forced to shoehorn their working lives and the school lives of their children into one place: their home…",
"url": "https://www.cnn.com/2021/03/24/success/one-year-later-parents-mothers-working-from-home-feseries/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210324103200-restricted-01-maira-wenzel-super-tease.jpg",
"publishedAt": "2021-03-24T14:51:29Z",
"content": "It was only supposed to be for a few weeks. A few months at most. One year ago, when the pandemic shut down offices and schools, many working parents were forced to shoehorn their working lives and t… [+7711 chars]"
},
{
"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Paul R. La Monica, CNN Business",
"title": "Fed up with FAANG and meme stocks? Here's a new investing strategy",
"description": "Stop us if you've heard this before. Giant tech stocks are finally due for a prolonged cooling-off period and investors need to start adding more value stocks, such as banks, oil firms and retailers, to their portfolios as the economy recovers.",
"url": "https://www.cnn.com/2021/03/24/investing/stocks-value-growth/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/210323101259-nyse-0922-restricted-super-tease.jpg",
"publishedAt": "2021-03-24T11:16:40Z",
"content": "New York (CNN Business)Stop us if you've heard this before. Giant tech stocks are finally due for a prolonged cooling-off period and investors need to start adding more value stocks, such as banks, o… [+5541 chars]"
},
{
"source": {
"id": "cbc-news",
"name": "CBC News"
},
"author": "Reuters",
"title": "Microsoft to allow more employees to work in office again starting next week",
"description": "Microsoft Corp. will start allowing more employees to work from its headquarters in Redmond, Washington and nearby campuses as soon as next week.",
"url": "https://www.cbc.ca/news/business/microsoft-office-1.5960239",
"urlToImage": "https://i.cbc.ca/1.5678543.1596831291!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/usa-tiktok-navarro.jpg",
"publishedAt": "2021-03-23T13:49:44Z",
"content": "Microsoft Corp. will start allowing more employees to work from its headquarters in Redmond, Washington and nearby campuses as soon as next week.\r\nEmployees working at Redmond sites or nearby campuse… [+863 chars]"
},
{
"source": {
"id": "the-globe-and-mail",
"name": "The Globe And Mail"
},
"author": "Reuters",
"title": "Microsoft in talks to acquire messaging platform Discord for more than $10-billion: report - The Globe and Mail",
"description": "<ol><li>Microsoft in talks to acquire messaging platform Discord for more than $10-billion: report The Globe and Mail\r\n</li><li>Microsoft in talks to buy Discord Thurrott.com\r\n</li><li>Report: Discord is looking for a buyer, price tag could exceed $10 billi…",
"url": "https://www.theglobeandmail.com/business/technology/article-microsoft-in-talks-to-acquire-messaging-platform-discord-for-more-than/",
"urlToImage": "https://www.theglobeandmail.com/resizer/jigGCnmeypiACH3xjn0LvCYpfDg=/1200x0/filters:quality(80)/cloudfront-us-east-1.images.arcpublishing.com/tgam/ANFYLDICZFJTLLZKBRJVVUQLEQ.JPG",
"publishedAt": "2021-03-23T11:11:43Z",
"content": "Microsoft Corp. MSFT-Q is in talks to buy messaging platform Discord Inc for more than $10-billion, Bloomberg News reported, citing people familiar with the matter.\r\nDiscord has reached out to potent… [+1464 chars]"
},
{
"source": {
"id": "google-news",
"name": "Google News"
},
"author": "James Serra",
"title": "A new WordPress theme and a new job",
"description": "As you can tell, I have switched to a new WordPress theme for this blog site. I have now been blogging for ten years! It seemed like a good...\nThe post A new WordPress theme and a new job appeared first on SQLServerCentral.",
"url": "http://feedproxy.google.com/~r/JamesSerra/~3/moPhw0kSwGQ/",
"urlToImage": "https://s.w.org/images/core/emoji/13.0.1/72x72/1f642.png",
"publishedAt": "2021-03-20T21:14:48Z",
"content": "As you can tell, I have switched to a new WordPress theme for this blog site. I have now been blogging for ten years! It seemed like a good time to finally make a change \r\nSpeaking of which, I have a… [+1295 chars]"
}
]
}
class ListNewsAdapter extends BaseAdapter {
private final ArrayList<HashMap<String, String>> data;
private final Context context;
boolean isThemeDark;
GetSettings getSettings;
int imageViewDimen;
ListNewsAdapter(Context c, ArrayList<HashMap<String, String>> d) {
context = c;
data=d;
getSettings = new GetSettings(context); //for checking dark theme
imageViewDimen = (int) context.getResources().getDimension(R.dimen.imageViewNews);
}
public int getCount() {
isThemeDark = getSettings.isThemeDark(); //one time check of dark theme
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ListNewsViewHolder holder = new ListNewsViewHolder();
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.template_list_news, parent, false);
holder.galleryImage = convertView.findViewById(R.id.galleryImage);
holder.source = convertView.findViewById(R.id.source);
holder.title = convertView.findViewById(R.id.title);
holder.sdetails = convertView.findViewById(R.id.sdetails);
holder.time = convertView.findViewById(R.id.time);
convertView.setTag(holder);
} else {
holder = (ListNewsViewHolder) convertView.getTag();
}
holder.galleryImage.setId(position);
holder.source.setId(position);
holder.title.setId(position);
holder.sdetails.setId(position);
holder.time.setId(position);
HashMap<String, String> holderMap;
holderMap = data.get(position);
try{
final String KEY_SOURCE = "source";
final String KEY_TITLE = "title";
final String KEY_DESCRIPTION = "description";
final String KEY_URLTOIMAGE = "urlToImage";
final String KEY_PUBLISHEDAT = "publishedAt";
Date date = null;
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", new Locale("en")); //TODO system language or article language
try {
date = dateFormat.parse(Objects.requireNonNull(holderMap.get(KEY_PUBLISHEDAT)));
}
catch (ParseException ignored) {
}
dateFormat.applyPattern("MMM d, yyyy");
if (date != null) { //simple error check
holder.time.setText(dateFormat.format(date));
}
//fill in the details for the article
holder.source.setText(holderMap.get(KEY_SOURCE));
holder.title.setText(holderMap.get(KEY_TITLE));
holder.sdetails.setText(holderMap.get(KEY_DESCRIPTION));
if (isThemeDark) { //set the text colour depending on dark theme
//TODO GET PROPER COLORS
holder.title.setTextColor(Color.WHITE);
holder.sdetails.setTextColor(Color.WHITE);
} else {
holder.title.setTextColor(Color.BLACK);
holder.sdetails.setTextColor(Color.BLACK);
}
int colorAccent = getAccentTextColor(); //set the source and time to the accent colour
holder.source.setTextColor(colorAccent);
holder.time.setTextColor(colorAccent);
if(holderMap.get(KEY_URLTOIMAGE) == null || Objects.requireNonNull(holderMap.get(KEY_URLTOIMAGE)).length() < 5) {
holder.galleryImage.setImageResource(R.drawable.placeholder_image);
} else {
Picasso.get()
.load(holderMap.get(KEY_URLTOIMAGE).replaceFirst("^http:","https:")) //stop insecure pages
.resize(imageViewDimen, imageViewDimen)
.centerCrop()
.into(holder.galleryImage);
}
}catch(Exception ignored) {}
return convertView;
}
}
Related
JsonPath: How to get the whole tree except one node
everyone. My question is quite simple, I think. My use case: Jenkins receives a huge JSON payload from a Gitlab WebHook (more than 2500 lines). I want to get rid of a specific node with more than 2000 lines. The JSON I get is so big that Jenkins is unable to parse it correctly so I want to remove a node I don't need. Assume the sample tree in the documentation page: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } }, "expensive": 10 } How can I get the whole tree except one? For example, if I want to get everything but the book node ... { "store": { "bicycle": { "color": "red", "price": 19.95 } }, "expensive": 10 } I more or less understand the filters feature, and I assume I need to figure out a proper filter but it seems they are only useful to search nodes based on some criteria. I'm not sure if they are useful to remove elements based on filtering conditions. Thanks so much for your help.
JSON Path is a tool for querying, not manipulation. You're not going to be able to alter the input value with it. You need another tool. I'd suggest looking at something like https://jsonnet.org/ which is designed for template-based transformations and generation.
How to design data for complex recursive entities for persistence?
I was assuming that I have an entity as "Person". { "UnqIdr": 125, "FrstNm": "Mark", "LastNm": "Antony", "Gndr": "Male", "DtOfBirth": "06-09-2020", "CtctDtls": { "Addr": [ { "UnqIdr": "10001", "Ln1": "Street name", "Ln2": "Block Number", "Ln3": "Ward number", "Cty": "New York", "ZipCd": "60034", "Stat": "New Jersey", "Ctry": "North America", "IsPrmy": true } ], "PhneNb": [ { "Nm": "Principal", "CtryCd": "+1", "Nb": "1234567890", "IsPrmy": true } ], "Email": "abc#def.com", "CtctURL": "www.def.com", "SclMdia": { "FacebookURL": "www.facebook.com/def", "LinkedInURL": "www.linkedin.com/us/def", "TwitterURL": "www.twitter.com/3634556" } }, "IdntyProof": [{ "UnqIdr": 16537, "Ctry": "India", "IdntyTp": 6548, "IdntyIdr": "INYHGB3462", "IsVerified": true, "VldFrm": "16-01-2000", "VldTill": "4-12-2023" }], "PrsnlIdnty": { "BldGrp": "A", "Id":[{ "Nt": "Mole in right arm" }] }, "Ethncty": "Nadar", "Rlgn": "Hindu", "Ntnlty": "Indian", "PrvsNtnlty": [{ "Ntnlty": "Indian", "IdntyProof": [{ "UnqIdr": 16537, "Ctry": "India", "IdntyTp": 6548, "IdntyIdr": "INYHGB3462", "IsVerified": true, "VldFrm": "16-01-2000", "VldTill": "4-12-2023" }] }], "MrtlSts": "Married", "Rltsh": [{ "RltshTp": "Spouse", "UnqIdr": 134 },{ "RltshTp": "Divorcee", "UnqIdr": 130 }] } However, the same information applies to an Employee, Customer and few more. Structure of employee might be { "UnqIdr": 125, "Department": "Chem Lab", "Person": {...} } However, when building the logic, we found an employee can also be a customer. Hence we thought of bundling as follows: { //person-info "employee-info": {}, "customer-info": {} } Now the problem comes up[ how to query with employee-info or customer-info. I know it is data design; however, we are using Java 11 and Spring JPA for the same. Additionally, which would be effective ways to design the solution. Even using NoSQL database is open for discussion.
Look for data normalization with relational databases. A simple solution is to store Person object in a different table and assigning it a personId field. So the employee structure becomes: { "UnqIdr": 125, "Department": "Chem Lab", "PersonId": 420 }
Relational databases are made for such data domains (eventual consistency for people....... no please). Look here for some database design involving CUSTOMER and EMPLOYEE: https://www.oracletutorial.com/getting-started/oracle-sample-database/ Now, you can still have Java inheritance regarding these People common attributes.
GPath on nested objects
I'm not sure what I'm doing wrong here and I'm having a hell of a time with getting this to work properly. Using this JSON: { "books": [ { "category": "reference", "author": { "name": "Nigel Rees", "age": 45 }, "title": "Sayings of the Century", "price": 8.95, "tax": 7.00 }, { "category": "reference", "author": { "name": "Evelyn Waugh", "age": 30 }, "title": "A cheap book", "price": 6.00, "tax": 3.00 } ] } I'm not able to extract the books where the authors age is 45, for example. I've tried things like the following (with the books document root set) findAll {it.author.age == 45} findAll {it.author}.findAll {it.age == 45} findAll {it.author}*.each {it.age == 45 } I still get back all of the records that have an age item. It can be any arbitrary object, it might not have an author record, etc. And I want the root book object returned. I feel like there's something really obvious I'm missing, but the docs seem to only cover one level of key-values. Maybe it doesn't support it? Thanks!
here is it books.findAll{it.author.age==45} It's not working your way (findAll {it.author.age == 45}) because you work from the root, and 'it' variable returns 'books' object, which has no field 'author'.
How do I obtain only View count from the following JSON Array?
Here is the JSON response of a video for youtube data analytics: { "kind": "youtube#videoListResponse", "etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/nKD2hgTXHwAf_Y8YHghPkBlZJcs\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#video", "etag": "\"q5k97EMVGxODeKcDgp8gnMu79wM/GLcJdYlEeecN5amO819w0A1mSqU\"", "id": "PK_HFb8tkUs", "snippet": { "publishedAt": "2016-03-14T01:52:34.000Z", "channelId": "UCHqC-yWZ1kri4YzwRSt6RGQ", "title": "Full Speech: Donald Trump HUGE Rally in Boca Raton, FL (3-13-16)", "description": "Sunday, March 13, 2016: GOP Presidential candidate Donald Trump held a campaign rally in Boca Raton, FL at Sunset Cove Amphitheater and spoke to a massive crowd of tens of thousands of supporters.\n\nFull Speech: Donald Trump Rally in Boca Raton, FL (3-13-16)", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/PK_HFb8tkUs/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/PK_HFb8tkUs/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/PK_HFb8tkUs/hqdefault.jpg", "width": 480, "height": 360 }, "standard": { "url": "https://i.ytimg.com/vi/PK_HFb8tkUs/sddefault.jpg", "width": 640, "height": 480 } }, "channelTitle": "Right Side Broadcasting", "tags": [ "Donald Trump", "Live Stream", "Boca Raton", "Florida", "Rally", "Speech", "Politics", "Republican Party" ], "categoryId": "25", "liveBroadcastContent": "none", "localized": { "title": "Full Speech: Donald Trump HUGE Rally in Boca Raton, FL (3-13-16)", "description": "Sunday, March 13, 2016: GOP Presidential candidate Donald Trump held a campaign rally in Boca Raton, FL at Sunset Cove Amphitheater and spoke to a massive crowd of tens of thousands of supporters.\n\nFull Speech: Donald Trump Rally in Boca Raton, FL (3-13-16)" }, "defaultAudioLanguage": "en" }, "contentDetails": { "duration": "PT2H41M2S", "dimension": "2d", "definition": "hd", "caption": "false", "licensedContent": true }, "status": { "uploadStatus": "processed", "privacyStatus": "public", "license": "youtube", "embeddable": true, "publicStatsViewable": true }, "statistics": { "viewCount": "371675", "likeCount": "7592", "dislikeCount": "586", "favoriteCount": "0", "commentCount": "1397" } } ] I would only like to extract the viewCount for example from the above response. How do I do that in Java? I have obtained the above response in a string but how do I extract just those single values like viewCount? An example is well appreciated.
You would have to traverse the JSON array to get the viewCount field. I can't give you the exact code to use as you have not told us what JSON library you are using, but here's some pseudocode. // If json is the object containing the JSON data viewCount = json["items"][0]["statistics"]["viewCount"]; From the "items" array, you get the first element, then the "statistics" object from that element, then the "viewCount" field from the statistics object.
Try this - String jsonString=""; JsonParser jParser= Json.createParser(new ByteArrayInputStream(jsonString.getBytes())); while(jParser.hasNext()){ if(jParser.next()==Event.KEY_NAME){ if(jParser.getString().equals("viewCount")){ jParser.next(); System.out.println(jParser.getString()); } } } The library should be imported correctly. Please refer - https://jsonp.java.net/download.html.
How to search inside a json file?
I have a JSON file with content like so : [ { "Name": "A+", "Type": "Array", "Designed by": "Arthur Whitney" }, { "Name": "Ada", "Type": "Compiled, Imperative, Procedural, Object-oriented class-based", "Designed by": "Tucker Taft, Jean Ichbiah" } { "Name": "C", "Type": "Compiled, Curly-bracket, Imperative, Procedural", "Designed by": "Dennis Ritchie" }, { "Name": "C#", "Type": "Compiled, Curly-bracket, Iterative, Object-oriented class-based, Reflective, Procedural", "Designed by": "Microsoft" }, { "Name": "Java", "Type": "Compiled, Curly-bracket, Imperative, Object-oriented class-based, Procedural, Reflective", "Designed by": "James Gosling, Sun Microsystems" }, { "Name": "JavaScript", "Type": "Curly-bracket, Interpreted, Reflective, Procedural, Scripting, Interactive mode", "Designed by": "Brendan Eich" } ] I want to write a web application that user type a word FOR EXAMPLE "java" in a textbox and then click the search button .after that search inside this JSON file and show the result in a web page . I am new in a web application.I don't know how to search through a JSON file and represent the result .Can anyone help me?
If you just want to get the job done, you can use lodash and than simply do something like this: var data = [...] // your jsonfile as array of objects _.findWhere(data, {Name:"Java"}) // returns the object