I am new to Android Development.
I purely like to work with JSON Objects and Arrays for my simple application considering the lightness of the JSON Carrier compared to XMLs.
I had challenges with ArrayAdapter to populate the ListView.
This is how I overcome and need your suggestions on it.
Extend the Adaptor class.
Then pass the JSONArray to the constructor.
Here the constructor calls super with dummy String array setting the length of the JSONArray.
Store the constructor arguments in class for further use.
public myAdaptor(Context context, int resource, JSONArray array)
{
super(context, resource, new String[array.length()]);
// Store in the local varialbles to the adapter class.
this.context = context;
this.resource = resource;
this.profiles = objects;
}
The getView() will do the job of fetching JSONObjects from JSONArray to build view.
public View getView(int position, View convertView, ViewGroup parent)
{
View view;
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(resource, parent, false);
}
else
{
view = convertView;
}
// Here
JSONObject item = (JSONObject) profiles.getJSONObject(position);
// READY WITH JSONObject from the JSONArray
// YOUR CODE TO BUILD VIEW OR ACCESS THE
}
Now Any improvements/suggestions/thoughful-question??
I would advise you to use google GSON instead JSON. It is a library that gives you a create objects from JSON-request, and you don't need to parse JSON everymore. Just create an object which contains all the fields from your JSON request and are named the same, and do with it whatever you want - for example:
Your JSON request
{
[
{
"id": "2663",
"title":"qwe"
},
{
"id": "1234",
"title":"asd"
},
{
"id": "5678",
"title":"zxc"
}
]
}
Your class - item of JSON-Array
public class MyArrayAdapterItem{
int id;
String title;
}
Somwhere in your code where you downloading data. I didn't know how are you doing it so i'll post my code for example:
mGparser = new JsonParser();
Gson mGson = new Gson();
Url url = "http://your_api.com"
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
JsonArray request = (JsonArray) mGparser.parse(in.readLine());
in.close();
ArrayList<MyArrayAdapterItem> items = mGson.fromJson(request, new TypeToken<ArrayList<MyArrayAdapterItem>>() {}.getType());
So that's all, for now just put "items" instead JSON-array in your adapter's constructor
You can pass null to super instead of creating a string array and implement getCount method:
public myAdaptor(Context context, int resource, JSONArray array)
{
super(context, resource, null);
// Store in the local varialbles to the adapter class.
this.context = context;
this.resource = resource;
this.profiles = array;
}
public int getCount(){
return profiles.length();
}
create one textview and assign with item.getString("key") and add that string to the local string array and return that view
This is the listview adapter class.
public class Adapter extends BaseAdapter {
Context context = null;
ArrayList<OffersAvailable> offers = null;
public Adapter(Context context, ArrayList<OffersAvailable> offer) {
this.context = context;
this.offers = offer;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return offers.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return offers.get(position).getTitle();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
final TextView tvpoints;
final TextView tv,tv_quantity;
if (convertView == null) {
LayoutInflater li = ((Activity) context).getLayoutInflater();
v = li.inflate(R.layout.design_userlist, null);
} else {
v = convertView;
}
tvpoints = (TextView) v.findViewById(R.id.tvpointlist);
tv_quantity= (TextView) v.findViewById(R.id.tv_quantity);
tv = (TextView) v.findViewById(R.id.tvdatalist);
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tv.setText(offers.get(position).getTitle().toUpperCase());
tv_quantity.setText(offers.get(position).getQuatity().toUpperCase());
tvpoints.setText(offers.get(position).getPoint() + "");
}
});
return v;
}
}
Object class
public class OffersAvailable {
String title, point, quatity, description,nid;
public String getNid() {
return nid;
}
public void setNid(String nid) {
this.nid = nid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoint() {
return point;
}
public void setPoint(String point) {
this.point = point;
}
public String getQuatity() {
return quatity;
}
public void setQuatity(String quatity) {
this.quatity = quatity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Use the json in the main class and store it inthe Arraylist of type OffersAvailable.
and pass it to the listviews adapter.
if you are getting the response from the internet use asynchttpclient method.And parse the json.
Related
I am new to android. I am trying to create a GridView
consisting of ImageView. The images are from flickr and I am using flickr API to search flickr and receive JSON response. I parse the JSON data to get image URL. The API call and parsing JSON data is done inside FlickrAdapter which extends BaseAdapter. But the problem is my getView() method is never called. I searched stackoverflow for this and I found that if there is no data to show then getView() will not be called. But I am setting the data in FlickrAdapter constructor. I've set some debug texts in the methods and I see that getCount() is called before the data is set which means getCount() is called before the FlickrAdapter constructor finishes executing. So getView() is never called.
I want getCount() method to be called after the constructor method of my FlickrAdapter finishes executing.
How can I solve this problem?
Here is my code for the BaseAdapter and other classes
FlickrAdapter.java
public class FlickrAdapter extends BaseAdapter {
public ArrayList<FlickrImage> flickrImagesList;
private Context context;
public static FlickrAdapter instance;
FlickrAdapter(final Context context, String searchText, Activity activity) {
this.flickrImagesList = new ArrayList<FlickrImage>();
this.context = context;
instance = this;
Flickr flickr = new Flickr(searchText, context, activity);
//row[0] = inflater.inflate(R.layout.template, null, false);
Log.d("URL", flickr.buildApiUrl());
DownloadManager.getJsonResponse(flickr.buildApiUrl(), context, new VolleyCallBack<JSONObject>() {
#Override
public void onSuccess(JSONObject success) {
//Log.d("JSON",success.toString());
try {
success = success.getJSONObject("photos");
JSONArray photo = success.getJSONArray("photo");
for (int i = 0; i < photo.length(); i++) {
JSONObject tempObject = photo.getJSONObject(i);
String result = new StringBuilder("https://farm" + tempObject.get("farm").toString() +
".staticflickr.com/" +
tempObject.get("server").toString() +
"/" +
tempObject.get("id").toString() +
"_" +
tempObject.get("secret").toString() +
"_n.jpg").toString();
FlickrImage image = new FlickrImage(i, result);
instance.flickrImagesList.add(image);
Log.d("SIZE", String.valueOf(instance.flickrImagesList.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public int getCount() {
Log.d("COUNT",String.valueOf(flickrImagesList.size()));
return flickrImagesList.size();
}
#Override
public Object getItem(int position) {
return flickrImagesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
ImageView myImage;
ViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.individulaImage);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.individual_image, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
FlickrImage tempImage = flickrImagesList.get(position);
Log.d("Address", tempImage.imageName);
//ImageView iv = (ImageView) convertView.findViewById(R.id.individulaImage);
//Picasso.with(context).load(tempImage.imageName).into(iv);
return row;
}}
Flickr.java
public class Flickr {
private StringBuilder urlBuilder = new StringBuilder("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e78808f6cf756218d6981fcdf8021f0c&tags=");
private String apiUrl = "";
private Context context = null;
private Activity activity;
private String[] individualImageUrl;
private String keyWord = "";
public Flickr(String keyWord, Context context, Activity activity) {
this.keyWord=keyWord;
this.apiUrl = buildApiUrl();
this.context = context;
this.activity = activity;
//Log.d("APIURL", this.apiUrl);
}
public String buildApiUrl() {
String[] temp;
StringBuilder sb = new StringBuilder();
temp = this.keyWord.split(" ");
for (int i = 0; i < temp.length; i++) {
sb.append(temp[i]);
if (i != (temp.length - 1)) {
sb.append("+");
}
}
urlBuilder.append(sb);
urlBuilder.append("&text=");
urlBuilder.append(sb);
urlBuilder.append("&format=json&nojsoncallback=1");
return urlBuilder.toString();
}}
FlickrImage.java
public class FlickrImage {
public int imageId;
public String imageName;
FlickrImage(int imageId, String imageURL) {
this.imageId = imageId;
this.imageName = imageURL;
}
}
VolleyCallBack.java
public interface VolleyCallBack<T> {
public void onSuccess(T success);
}
DownloadManager.java
public class DownloadManager {
public static void getJsonResponse(final String Url, Context context, final VolleyCallBack callBack) {
JsonObjectRequest flickrJsonRequest = new JsonObjectRequest(Request.Method.GET, Url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callBack.onSuccess(response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(context).add(flickrJsonRequest);
}
}
It is not being called before your constructor completes. YOur web code runs in a seperate thread so your constructor code completes and then getCount is called. Once your web code is complete onSuccess is called.
It is never advisable to run network code in adapter. Run it in your activity or fragment and once it completes call notifyDatasetChanged() on your adapter.
I have pictures from my online database in my GridView and I want it in reverse order.
So I want when I add a new picture to my database to be the first in the GridView.
I tried to find an answer but there is nothing about it at stackoverflow.
This is my ListViewAdapter:
public class GetMovieImagesListViewAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
private static final String baseUrlForImage = "http://google.com";
private static LayoutInflater inflater = null;
public GetMovieImagesListViewAdapter(JSONArray jsonArray, Activity a){
this.dataArray = jsonArray;
this.activity = a;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position){
return position;
}
#Override
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ListCell cell;
if (convertView == null) {
convertView = inflater.inflate(R.layout.get_images_from_movies_list_cell, null);
cell = new ListCell();
cell.MovieImages = (ImageView) convertView.findViewById(R.id.movie_images_id);
convertView.setTag(cell);
} else {
cell = (ListCell) convertView.getTag();
}
try {
JSONObject jsonObject = this.dataArray.getJSONObject(position);
String nameOfImage = jsonObject.getString("image");
String urlForImageInServer = baseUrlForImage + nameOfImage;
new AsyncTask<String, Void, Bitmap>(){
#Override
protected Bitmap doInBackground(String... params)
{
String url = params[0];
Bitmap icon = null;
try
{
InputStream in = new URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return icon;
}
#Override
protected void onPostExecute(Bitmap result)
{
cell.MovieImages.setImageBitmap(result);
}
}.execute(urlForImageInServer);
} catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell{
private ImageView MovieImages;
}}
You could fetch each JSONObject by starting from the end of the array and working backwards to the start:
JSONObject jsonObject = this.dataArray.getJSONObject(getCount() - position - 1);
The result that you have received try to iterate through it in the reverse order.
Your Bitmap result data seems to be a single data that you get. I am expecting an array, or arraylist of data that you get in onPostExecute() method parameter while you query your online database.
Say for example, if you get the data in the form of onPostExecute(ArrayList result), then you can simply iterate the 'result' data in reverse order in order to populate your grid view in reverse order.
Check out Iterate arraylist in reverse order
public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
CustomList adapter = new CustomList(this, rowItems);
listView1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
rowItems = new ArrayList<RowItem>();
}
}
}
This my code i am able to display the value after Jason parsing in this line System.out.println(Id + "" + Designation + ""
+ EmployeeName);
But i am unable to print data in Listview there is Error coming while i have created
Datamodel
public class RowItem {
public RowItem(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private String title;
private String desc;
}
I have create adapter which i s extending from Base adapter that work fine can u please tell me how to bind value and display in list view after Json Parsing please suggest me i m trying to Implement .
Use Custom Adapter for binding your JSON data to your Listview like below :
public class ListViewAdapterForLead extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<SpinnerNavItem> data;
TextView txtText;
public ListViewAdapterForLead(Context context,ArrayList<SpinnerNavItem> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int index) {
return data.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
public View getDropDownView(int position,View convertView,ViewGroup parent){
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
}
bind your values in the getView() method of your custom adapter.
You should set the data after the background task gets completed.
* First try to set list adapter in onPostExecute() method.
* Make sure all the details in your model gets filled.
* Make use of getView() method in your Adapter class to parse the data.
For sample code for ListView with BaseAdapter, refer the below link
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
You forgot one thing,this is why the List is empty
Add the parsed data to your List
//initialize your list here
rowItems = new List<RowItems>();
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
RowItemsr = new RowItems();
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
// you must create an object and add it to your list
r.setTitle(EmployeeName);
r.setDesc(Designation);
rowItems.add(r);
}
This is what you need
I have a class that looks like this:
public class Vizita {
public int icon;
public String titlu;
public String loc;
public String idviz;
public Vizita(){
super();
}
public Vizita(int icon, String titlu, String loc, String idviz) {
super();
this.icon = icon;
this.titlu = titlu;
this.loc = loc;
this.idviz = idviz;
}
}
I use AsyncTask to retrieve a JSON array from a PHP. All works perfect for simple layout of listview. But I want to use a more complex layout, so I designed one that uses all 4 values from Vizita.class above. But I do not know how to set the adapter for it, because the way I try it, gives me errors.
Of course I am trying to do it in onPostExecute, like this:
public class MyActivity extends Activity {
{...}
JSONArray lststat;
{...}
public JSONArray liststatus() {
JSONArray jdata=post.getserverdataX(url_connectX);
return jdata;
}
class asyncpost extends AsyncTask< String, String, String > {
Vizita weather_data[];
....
protected void onPostExecute(String result) {
VizitaAdapter adapter = new VizitaAdapter(MyActivity.this,R.layout.listview_item_row, weather_data);
myListView.setAdapter(adapter);
...}
And in doInBackground I am processing the JSON like this:
lststat = liststatus();
JSONObject json_data;
try {
int length = lststat.length();
Vizita weather_data[] = new Vizita[length];
for (int i = 0; i < length; i++)
{
json_data = lststat.getJSONObject(i);
weather_data[i].titlu =json_data.getString("clientnume");
weather_data[i].idviz =json_data.getString("idvizite");
weather_data[i].loc =json_data.getString("localitate");
}
} catch (Exception e) {
Log.e(null, e.toString());
}
where liststatus() is where I call the asyncTask to retrieve the needed JSONArray.
But I receive a java.lang.NullPointerException in the for loop (if I comment the setAdapter line).
I assume I did not initialize the weather_data array properly ?!?!?
If I (uncomment) set the adapter in onPostExecute I receive a crash error "Force close"
I do not receive any errors in the IDE, seeming that the syntaxes are fine.
Please tell me what am I doing wrong? And how can I fix it?
The code for the VizitaAdapter is bellow
public class VizitaAdapter extends ArrayAdapter<Vizita>{
Context context;
int layoutResourceId;
Vizita data[] = null;
public VizitaAdapter(Context context, int layoutResourceId, Vizita[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.txtLoco = (TextView)row.findViewById(R.id.txtLocalitate);
holder.txtIdviz = (TextView)row.findViewById(R.id.txtIdVizite);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Vizita weather = data[position];
holder.txtTitle.setText(weather.titlu);
holder.txtLoco.setText(weather.loc);
holder.txtIdviz.setText(weather.idviz);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtLoco;
TextView txtIdviz;
}
}
Probably you forgot initialize Vizita object in loop:
json_data = lststat.getJSONObject(i);
weather_data[i] = new Vizita();
weather_data[i].titlu =json_data.getString("clientnume");
weather_data[i].idviz =json_data.getString("idvizite");
weather_data[i].loc =json_data.getString("localitate");
I am fairly new to Android development and I am trying to build a ListView which get data from web service using gson. I have a model class, a list class, an adapter class and the activity class.
The list works fine and it got the data, and now I want to integrate the OnItemClickListener to it and pass the data to the 2nd activity. And I'd like to get the item id (DistrictId) and pass it to the next Activity(listView) instead of the row id. It would be great if someone could show me the light... as the documentation is not as clear to understand and because I am new.
Below is my code.
The model class
package com.sample.myapp;
public class DistrictModel {
private String id;
private String districtName;
public String getDistrictId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDistrictName(){
return districtName;
}
public void setDistrictEN(String districtName){
this.districtName = districtName;
}
}
The List class
public class DistrictList {
private List<DistrictModel> districts;
public List<DistrictModel> getDistricts(){
return districts;
}
public void setDistrictList(List<DistrictModel> districts){
this.districts = districts;
}
}
The Adapter class
public class DistrictAdapter extends ArrayAdapter<DistrictModel>{
int resource;
String response;
Context context;
private LayoutInflater dInflater;
public DistrictAdapter(Context context, int resource, List<DistrictModel> objects) {
super(context, resource, objects);
this.resource = resource;
dInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
DistrictModel lm = (DistrictModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = dInflater.inflate(R.layout.item_district, null);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.district_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(lm.getDistrictName());
return convertView;
}
}
The activity class
public class DistrictListActivity extends Activity{
LocationManager lm;
ArrayList<DistrictModel> districtArray = null;
DistrictAdapter districtAdapter;
DistrictList list;
ListView lv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.districtlist_layout);
lv = (ListView) findViewById(R.id.list_district);
districtArray = new ArrayList<DistrictModel>();
districtAdapter = new DistrictAdapter(DistrictListActivity.this, R.layout.item_district, districtArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(districtAdapter);
try {
new DistrictSync().execute("http://aws.something.com/service");
} catch(Exception e) {}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DistrictListActivity.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+(lv.getItemIdAtPosition(position)));
adb.setPositiveButton("Ok", null);
adb.show();
}
}); **//i'd like to get the DistrictId from the json data.**
}
private class DistrictSync extends AsyncTask<String, Integer, DistrictList> {
protected DistrictList doInBackground(String... urls) {
DistrictList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, DistrictList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(DistrictList dislist) {
for(DistrictModel lm : dislist.getDistricts())
{
districtArray.add(lm);
}
districtAdapter.notifyDataSetChanged();
}
}
}
For testing purpose, now I click the row it will show me the row id, so I know the onclick listener works, but I just want it to grab me the DistrictId so I can use it to pass to the next activity.
Thank you so much.
(out of my head) Try this:
((DistrictModel)lv.getAdapter().getItem(position)).getDistrictId();
Generally when you want to pass data from one Activity to another, you just place it into the Intent that you use to create the new Activity.
For example (and here are some additional examples):
Intent i = new Intent(context, MyNewActivity.class);
i.putExtra("MyCurrentHealth", mCurrentHealth);
context.startActivity(i);
To retrieve the data do this:
Bundle extras = getIntent().getExtras();
if (extra != null) {
... // Do stuff with extras
}