Populate Listview from JSON

populate: listview from json

You have to deserialize your json array response to arraylist of java object. You can use default Json android json package or gson library to do that.

Then you can feed your adapter with that arraylist of your Book class objects.

For more details you can refer to json to recyclerview.

FYI: You should use updated version of listview which is Recyclerview

Happy coding......:)

Populate a ListView from a Json file in C#

You need a few things and will suggest you change a few others so that it can be easier.

First create an entity/class with the data you will be receiving from the API. Call it as you wish but for this example I will call it EnglishMonarch

public class EnglishMonarch
{
public string Name {get; set;}

public string City {get; set;}

public string House {get; set;}

public string Years {get; set;}
}

As you see I added a public property with each field you will be receiving.

I suggest you to use this library Json.net which will allow you to parse the json data into your entity with only a few lines of code. You can install the nuget package right from XS or VS.

You will need to include some changes to the class we just created. You will add some annotations so json.net knows how to map each json fields with your class properties.

public class EnglishMonarch
{
[JsonProperty("nm")]
public string Name { get; set; }

[JsonProperty("cty")]
public string City { get; set; }

[JsonProperty("hse")]
public string House { get; set; }

[JsonProperty("yrs")]
public string Years { get; set; }
}

Now you can get the response and parse it using json.net like this:

public List<EnglishMonarch> GetData (string jsonData)
{
if (string.IsNullOrWhiteSpace (jsonData))
return new List<EnglishMonarch> ();

return JsonConvert.DeserializeObject<List<EnglishMonarch>> (jsonData);
}

Note: Why a list of EnglishMonarch? because you are receiving from the API more than one item this is the list you will use to populate your ListView.

Now let's put that data into your ListView. In Android for this you need to create an Adapter which is the one that tells the ListView how and what data to display.

Your adapter will look like this:

public class EnglishMonarchAdapter : BaseAdapter<EnglishMonarch>
{
public List<EnglishMonarch> Items { get; set;}

private readonly Context context;

public EnglishMonarchAdapter (Context context, List<EnglishMonarch> items)
{
this.context = context;

Items = items ?? new List<EnglishMonarch> ();
}

public override EnglishMonarch this [int position]
{
get { return Items [position]; }
}

public override int Count
{
get { return Items.Count; }
}

public override long GetItemId (int position)
{
return position;
}

public override View GetView (int position, View convertView, ViewGroup parent)
{
var view = convertView ?? LayoutInflater.FromContext (context).Inflate (Resource.Layout.englishmonarch_item_layout, parent, false);

var item = Items [position];

var tvName = view.FindViewById<TextView> (Resource.Id.tvName);
var tvHouse = view.FindViewById<TextView> (Resource.Id.tvHouse);
var tvYear = view.FindViewById<TextView> (Resource.Id.tvYears);
var tvCity = view.FindViewById<TextView> (Resource.Id.tvCity);

tvName.Text = item.Name;
tvHouse.Text = item.House;
tvYear.Text = item.Years;
tvCity.Text = item.City;

return view;
}
}

The GetView method is the one responsible of creating the ListView Item view (the Cell) and mapping the data to the fields in the view.

For this Adapter to work you will need to create a Layout (XML) which will be the one used as a ItemView/Cell of your ListView. The one I created is very simple and I named it englishmonarch_item_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/tvName"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<TextView
android:id="@+id/tvCity"
android:textSize="14sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<TextView
android:id="@+id/tvHouse"
android:textSize="11sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<TextView
android:id="@+id/tvYears"
android:textSize="11sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

Now you just have to glue some pieces in your startButton click event

    startbutton.Click += async (sender, e) =>
{
// Instantiate the CancellationTokenSource
cts = new CancellationTokenSource();

try
{
// **** GET ****
var jsonData = await LoadDataAsync(cts.Token);

// ** Parse data into your entity ****
var items = GetData(jsonData);

// **** Create your adapter passing the data *****
listview.Adapter = new EnglishMonarchAdapter(this, items);
}
catch (TaskCanceledException)
{
textView0.Text = " Download deleted ";
}
catch (Exception)
{
textView0.Text = "Generic Error";
}

// ***Set the CancellationTokenSource to null when the download is complete.
cts = null;
};

That's all. That should work!

Note: You can skip a few parts like the use of Json.net and parse your data manually, just did mention it so you know there're other options.

Flutter Populate items into listView from sharedPreferenes json

you can do it like this.

import 'package:flutter/material.dart';
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
final String title;

const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
List<portfolioModel> _list = [];

@override
void initState() {
super.initState();
loadData();
}

void loadData() async {
(PortfolioAdapter()).getPortfolio().then((mlist) {
print(_list);
setState(() {
_list.addAll(mlist);
});
}).catchError((e) {
print(e);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _list.isNotEmpty
? ListView.builder(
itemCount: _list.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_list[index].shareNames),
subtitle: Text(_list[index].holdings),
);
})
: const Center(child: Text('loading...')),
);
}
}

class portfolioModel {
String symbol, openingP, closingP, holdings, shareNames;

portfolioModel({
required this.symbol,
required this.openingP,
required this.closingP,
required this.holdings,
required this.shareNames,
});

factory portfolioModel.fromJson(Map<String, dynamic> json,
{openingP, closingP}) {
return portfolioModel(
symbol: json['SYMBOL'],
openingP: openingP,
closingP: closingP,
holdings: json['HOLDINGS'],
shareNames: json['SHARENAME'],
);
}
}

class PortfolioAdapter {
final String jsonData = '''{
"portfolio":{
"holdings":[
{
"CSDNUMBER":"201102042587-0001",
"CLIENTNAME":"MAWOYO T",
"SYMBOL":"FCA.ZW",
"HOLDINGS":"8180900",
"SHARENAME":"FIRST CAPITAL BANK LIMITED",
"SYMBOLID":"X0"
},
{
"CSDNUMBER":"201102042587-0001",
"CLIENTNAME":"MAWOYO T",
"SYMBOL":"SIM.ZW",
"SYMBOLID":"Y1",
"HOLDINGS":"600",
"SHARENAME":"SIMBISA BRANDS LIMITED"
}
],
"openingPrice":{
"X0":"3.6348",
"Y1":"94.9"
},
"closingPrice":{
"X0":"3.6054",
"Y1":"90.0163"
}
}
}''';

Future<List<portfolioModel>> getPortfolio() async {
List<portfolioModel> list = [];

final body = json.decode(jsonData);

body['portfolio']['holdings'].forEach((item) async {
list.add(portfolioModel.fromJson(item,
openingP: body['openingPrice'].toString(),
closingP: body['closingPrice'].toString()));
});

return list;
}
}

Populating listview from json

After updating the data, try something like refreshing the list view like lstTest.invalidateViews(); - so your queryImp() code will change into:

private void queryImp() {
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/wp-json/wp/v2/posts",
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray jsonArray) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();

mJSONAdapter.updateData(jsonArray);
mJSONAdapter.notifyDataSetChanged();
//try refreshing the list-view like this:
lstTest.invalidateViews()
}

@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();

// Log error message
// to help solve any problems
Log.e("Imp android", statusCode + " " + throwable.getMessage());
}
});

}

Let me know if the changes help.



Related Topics



Leave a reply



Submit