getActivity() method return null - android

I wrote this code but getActivity method return null out onCreateView method.
public class HomeScreen extends Fragment {
private Context context;
ViewPager viewPager;
GridView listGrid;
Bitmap[] bitmaps ;
LinearLayout indicator;
Button first,second;
String[] path ;
TextView imageTitle;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_screen, container, false);
listGrid = (GridView) v.findViewById(R.id.grid_view);
viewPager = (ViewPager)v.findViewById(R.id.view_pager);
indicator = (LinearLayout)v.findViewById(R.id.indicator);
first = (Button) v.findViewById(R.id.bfirst);
second = (Button) v.findViewById(R.id.bsecond);
imageTitle = (TextView) v.findViewById(R.id.myImageTitle);
Typeface tf = Typeface.createFromAsset(HomeScreen.this.getActivity().getAssets(), "fonts/Medium.otf");
imageTitle.setTypeface(tf);
new GetCategories().execute();
return v;
}
class GetCategories extends AsyncTask {
#Override
protected Object doInBackground(Object[] params) {
JSONArray dataJsonArr = null;
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl("http://192.168.88.12/index.php");
try{
// get the array of users
dataJsonArr = json.getJSONArray("Users");
//Arrays of data
bitmaps = new Bitmap[dataJsonArr.length()];
path = new String[dataJsonArr.length()];
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
InputStream in = new URL(c.getString("image")).openStream();
bitmaps[i] = BitmapFactory.decodeStream(in);
path[i] = c.getString("title");
}
}catch (JSONException e){
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
ListAdapter adapter=new ListAdapter(HomeScreen.this.getActivity(), path,bitmaps);
listGrid.setAdapter(adapter);
ImageAdapter sliderAdapter = new ImageAdapter(HomeScreen.this.getActivity(),bitmaps,indicator,first,second,imageTitle,path);
viewPager.setAdapter(sliderAdapter);
}
}
public void onItemClick(int mPosition){
Log.i("Log:", " on item click : " + context);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
}
public class ListAdapter extends ArrayAdapter {
private final Activity context;
private final String[] title;
private final Bitmap[] image;
public ListAdapter(Activity context, String[] title, Bitmap[] image) {
super(context, R.layout.list_row, title);
this.context=context;
this.title=title;
this.image=image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.list_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.text);
ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
txtTitle.setTypeface(Typeface.createFromAsset(ListAdapter.this.getContext().getAssets(), "fonts/Light.otf"));
txtTitle.setText(title[position]);
imageView.setImageBitmap(image[position]);
rowView.setOnClickListener(new OnItemClickListener(position));
return rowView;
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements View.OnClickListener {
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View v) {
HomeScreen homeScreen = new HomeScreen();
homeScreen.onItemClick(mPosition);
}
}
}

This is done because your Fragment is not attached to any activity so far.
getActivity returns null before the onAttach(Activity) returs and after the onDetach() better check out Fragment Documentation to see the proper usage of fragments.
Also, stop using such references to context
ListAdapter.this.getContext() or HomeScreen.this.getActivity() they are prune to crashes and far from android logic.
To avoid these issues consider using Loader instead of AsyncTask here is a good tutorial how loaders work implement: https://stackoverflow.com/a/20991394/944070

You are not using a FragmentTransaction to interact with your Fragment. This means that the FragmentManager is not able to play a role when it comes to the Fragment lifecycle, hence your Activity is null because the Fragment is never attached to the Activity.

Related

The images in my listview changes when I scroll

This is my code:
public class GetAllCategoriesListViewAdapter extends BaseAdapter{
private JSONArray dataArray;
private Activity activity;
private static final String baseUrlForCategoryImage = "link here";
private static LayoutInflater inflater = null;
public GetAllCategoriesListViewAdapter(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(final int position, View convertView, ViewGroup parent) {
final ListCell cell;
if(convertView == null){
convertView = inflater.inflate(R.layout.get_all_categories_list_view_cell, null);
cell = new ListCell();
cell.category_name = (TextView) convertView.findViewById(R.id.category_name);
cell.category_image = (ImageView) convertView.findViewById(R.id.category_image);
cell.category_image.setTag(cell);
convertView.setTag(cell);
}else{
cell = (ListCell) convertView.getTag();
}
try{
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.category_name.setText(jsonObject.getString("category_name"));
String nameOfImage = jsonObject.getString("category_image");
String urlForImageInServer = baseUrlForCategoryImage + nameOfImage;
new AsyncTask<String, Void, Bitmap>(){
protected Bitmap doInBackground(String... params){
String url = params[0];
Bitmap icon = null;
try{
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return icon;
}
#Override
protected void onPostExecute(Bitmap result) {
cell.category_image.setImageBitmap(result);
}
}.execute(urlForImageInServer);
}catch (JSONException e){
e.printStackTrace();
}
return convertView;
}
private class ListCell{
private ImageView category_image;
private TextView category_name;
}
}
The code gets the images from my webhost and place it in every cell in my listvew. The problem is everytime I scroll, the images are shuffled and returns in few seconds. How to stop the images from changing when I scroll? I tried to use the solution on other post but it won't work. Please help.
Looks like you are new to android. So you are fetching the images in the getView method. The getView method is called every time a new list item is drawn. So For every image, a new request is made to internet. SO that will be a lot of requests . You should firstly get your images and get them in some ArryayList . Then pass that Arraylist to your adapter. Here is tutorial for you
Using AsyncTask
http://www.devexchanges.info/2015/04/android-custom-listview-with-image-and.html
Using Volley
https://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
Go for Volley for better performance. Cheers!

android: listview load incorrectly

My listview load properly but when I go back to my MainActivity then again go to ViewAll activity then it load incorrectly like below.
Here is my ViewAll activity where I have load list view.
public class ViewAll extends Activity {
private ListView listView;
public ArrayList<Model> arrayList;
private Database_Handler database_handler;
private SQLiteDatabase db;
private MyAdapter adapter;
private SwipeRefreshLayout swipeContainer;
private long i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
listView = (ListView) findViewById(R.id.listView);
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
addNewData();
database_handler = new Database_Handler(ViewAll.this);
db = database_handler.getReadableDatabase();
arrayList = database_handler.getAllContacts();
adapter = new MyAdapter(ViewAll.this, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
database_handler = new Database_Handler(ViewAll.this);
db = database_handler.getReadableDatabase();
arrayList = database_handler.getAllContacts();
adapter = new MyAdapter(ViewAll.this, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void addNewData() {
try {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
String str1 = "List "+i+" ", str2 = "Handler testing";
database_handler = new Database_Handler(ViewAll.this);
db = database_handler.getWritableDatabase();
database_handler.addRegister(str1, str2, db);
database_handler.close();
handler.postDelayed(this, 60 * 10);
i++;
}
}, 60 * 10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my adapter.
public class MyAdapter extends BaseAdapter{
private Context context;
private ArrayList<Model> arrayList;
private static LayoutInflater inflater;
public MyAdapter(ViewAll viewAll, ArrayList<Model> arrayList) {
this.context = viewAll;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tvFirstName,tvLastName;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = null;
try {
Holder holder;
myView = convertView;
if (myView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.adapter, null);
holder = new Holder();
holder.tvFirstName= (TextView) myView.findViewById(R.id.tvFirstName);
holder.tvLastName= (TextView) myView.findViewById(R.id.tvLastName);
myView.setTag(holder);
}
else {
holder = (Holder) myView.getTag();
}
holder.tvFirstName.setText(arrayList.get(position).getF_name());
holder.tvLastName.setText(arrayList.get(position).getL_name());
} catch (Exception e) {
e.printStackTrace();
}
return myView;
}
}
Actually I am inserting data into database using handler class and show all data into listview in my ViewAll activity and it work fine but when i go to my previous MainActivity and again go to ViewAll activity then listview load incorrectly which show in the image like after "List 24" data inserted incorrectly.
Please Clear your Arraylist and also clear your adapter when you are loading it from first item of listview.
You can clear this by lstVwList.setAdapter(null);

Update Images in Gridview via custom adapter

I am able to show images (set by default) in the gridview properly using a custom adapter.
However when I try to change the string[] in ForecastFragment (snippets below), the updateList function is not getting called. I would like the all the views in the grid to be recreated.
ImageAdapter.java :
public class ImageAdapter extends BaseAdapter {
public Context mContext; ImageAdapter(Context c) {
mContext = c;
String LOG_TAG = ImageAdapter.class.getSimpleName();
Log.e(LOG_TAG,"Constructor Context : "+mContext);
}
public int getCount() {
return this.eatFoodyImages.length;
}
public int size1;
public int size2;
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public void updateList(String[] string)
{
this.eatFoodyImages=string;
this.notifyDataSetChanged();
String LOG_TAG = ImageAdapter.class.getSimpleName();
Log.e(LOG_TAG, "\n\nupdatelist : " + this.eatFoodyImages);
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
size1 = (int) this.mContext.getResources().getDimension(R.dimen.image_size1);
size2 = (int) this.mContext.getResources().getDimension(R.dimen.image_size2);
imageView.setLayoutParams(new GridView.LayoutParams(size1,size2));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
String LOG_TAG = ImageAdapter.class.getSimpleName();
Log.e(LOG_TAG, "\n\n\nPosition : " + position + " Strings Array : \n\n" + eatFoodyImages[position].toString());
//System.out.println();
Picasso.with(mContext)
.
load(eatFoodyImages[position])
.
into(imageView);
return imageView;
}
// references to our images
public String[] eatFoodyImages = {
"http://i.imgur.com/rFLNqWI.jpg", //Default Random Data!!!
"http://i.imgur.com/C9pBVt7.jpg",
"http://i.imgur.com/rT5vXE1.jpg",
"http://i.imgur.com/aIy5R2k.jpg",
"http://i.imgur.com/MoJs9pT.jpg",
"http://i.imgur.com/S963yEM.jpg",
"http://i.imgur.com/rLR2cyc.jpg",
"http://i.imgur.com/SEPdUIx.jpg",
"http://i.imgur.com/aC9OjaM.jpg",
"http://i.imgur.com/76Jfv9b.jpg",
"http://i.imgur.com/fUX7EIB.jpg",
"http://i.imgur.com/syELajx.jpg",
"http://i.imgur.com/COzBnru.jpg",
"http://i.imgur.com/Z3QjilA.jpg",
};
}
ForecastFragment.java :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
movieadapter = new ImageAdapter(this.getActivity());
gridview.setAdapter(movieadapter);
});
return rootView;
}
Calling updateList :
public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
{//Showing only relevant code
IA.updateList(eatFoodyImages); //Here eatFoodyImages contains the new String[] to be used for image loading.
Here it goes, i have a adapter like below
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_tile, parent, false);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(this.getContext()).load(Constants.MOVIE_POSTER_PATH_SMALL + movie.getPosterPath()).placeholder(ContextCompat.getDrawable(this.getContext(), R.drawable.movie)).error(ContextCompat.getDrawable(this.getContext(), R.drawable.movie)).into(imageView);
return convertView;
}
which sets a tile in a gridview.
I trigger a asynctask and get the movies from API then notify the dataset which loads the movies and refreshes the view.
So essentially your notifyDataSet() should be in onPostExecute() of AsyncTask.
Here is my Async task code for better understanding.
public class CallMovieDBAPI extends AsyncTask<String, Void, List<Movie>> {
ProgressDialog dialog;
private Activity activity;
private GridView gridView;
public CallMovieDBAPI(Activity activity, GridView gridView) {
this.activity = activity;
this.gridView = gridView;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage(activity.getString(R.string.progressDialogText));
dialog.show();
}
#Override
protected List<Movie> doInBackground(String... params) {
InputStream in = null;
String jsonResponse = null;
String apiURL = params[0];
try {
URL url = new URL(apiURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
jsonResponse = getJsonObject(in);
movieList = JsonParser.parse(jsonResponse);
} catch (Exception e) {
Log.e("CallMovieDBAPI", "Exception occurred in AsyncTask - CallMovieDBAPI", e);
}
return movieList;
}
#Override
protected void onPostExecute(List<Movie> movies) {
Log.d("Popular Movies", "Got data successfully");
if (dialog.isShowing()) {
dialog.dismiss();
}
movieAdapter = new MovieAdapter(activity, movieList);
gridView.setAdapter(movieAdapter);
movieAdapter.notifyDataSetChanged();
if (isTablet) {
((MovieClickedCallback) getActivity()).onMovieClicked(0, movieAdapter);
}
}
Let me know if this solves.

How to Clear The Previous Gridview Item and refill with new adapter in android?

how to clear the gridview when i request for another adapter if i use the lazy adapter here i put my code for gridview activity and lazyadapter i m use the asynctask for gridview items
here i put my code for gridview
Gridview Activity.java
public class VisitorActivity extends Activity implements OnClickListener{
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new visitormiddlelistasyntask.execute("");
}
public class VisitorMiddleListAsyncTask extends AsyncTask<String,ArrayList<HashMap<String, String>>,ArrayList<HashMap<String, String>>>
{
String city;
JsonParser jparser=new JsonParser();
String visitorurl="http://digitalhoteladnetwork.com/vixxa_beta/index.php/visitors/webvisitorlist";
//String visitorurl="http://digitalhoteladnetwork.com/vixxa_beta/index.php/visitors/websearch_visitor_guide";
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params)
{
//For Get city
Geocoder geocoder = new Geocoder(VisitorActivity.this, Locale.getDefault());
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
Log.e("Addresses","-->"+addresses);
city = addresses.get(0).getSubAdminArea();
// Log.e("Cityname","--->"+city);
}
catch (IOException e)
{
e.printStackTrace();
// Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
WebServiceData wsd=new WebServiceData();
String visitorstring=wsd.VisitorGuide(city, visitorurl);
//Log.e("webservice visitorstring","-->"+wsd.VisitorGuide(city, visitorurl));
Log.e("webservice visitorstring","-->"+visitorstring);
try
{
JSONObject jobject=new JSONObject(visitorstring);
JSONArray jvisitorlist=jobject.getJSONArray(TAG_VISITORGUIDELIST);
for(int i=0;i<jvisitorlist.length();i++)
{
HashMap<String, String> map=new HashMap<String, String>();
String id=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDEID).toString();
//Log.e("Id","-->"+id);
String title=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDETITLE).toString();
//Log.e("Title","-->"+title);
String image=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDEIMAGE).toString();
//Log.e("Image","-->"+image);
//String show=jvisitorlist.getJSONObject(i).getString(TAG_VISITORTITLESHOW).toString();
map.put(TAG_VISITORGUIDEID,id);
map.put(TAG_VISITORGUIDETITLE,title);
map.put(TAG_VISITORGUIDEIMAGE, image);
//map.put(TAG_VISITORTITLESHOW,show );
visitormiddle.add(map);
}
//Log.e("Visitor Guide List","-->"+jvisitorlist);
}
catch (Exception e)
{
e.printStackTrace();
}
return visitormiddle;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result)
{
gridview=(GridView)findViewById(R.id.gridview);
adapter=new LazyAdapter(VisitorActivity.this, visitormiddle);
gridview.setAdapter(adapter);
}
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private static final String TAG_VISITORGUIDELIST="visitorlist";
private static final String TAG_VISITORGUIDEID="visitor_guide_id";
private static final String TAG_VISITORGUIDETITLE="visitor_guide_cat_title";
private static final String TAG_VISITORGUIDEIMAGE="visitor_guide_cat_image";
//private static final String TAG_VISITORTITLESHOW="visitor_guide_cat_titleshow";
private Activity activity;
private ArrayList<HashMap<String, String>> result;
private static LayoutInflater inflater=null;
public GridImageLoader gridimageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> r) {
activity = a;
result=r;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridimageLoader=new GridImageLoader(activity.getApplicationContext());
}
public int getCount() {
return result.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.griditem, null);
//vi = inflater.inflate(R.layout.griditem,parent,false);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textview);;
holder.image=(ImageView)vi.findViewById(R.id.imageview);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(result.get(position).get(TAG_VISITORGUIDETITLE));
holder.image.setTag(result.get(position).get(TAG_VISITORGUIDEIMAGE));
gridimageLoader.DisplayImage(result.get(position).get(TAG_VISITORGUIDEIMAGE), activity, holder.image);
return vi;
}
}
You can use ArrayAdapter and then call adapter.clear() to clear the grid view and then refill it with new data.
You can use same VisitorMiddleListAsyncTask to fill the data again.
To clear gridView you can set empty adapter or set it's visibility invisible or gone.

OnItemClickListener getting data from model

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
}

Categories

Resources