How to pass value from Activity to Page Adapter - android

i am quiet new to android. please help me out with this doubt.
i have created a image slider.
and i have an API i want to load the images from those API into slider.
i have created a Activity file.
public class MoreImage extends Activity {
ImageView ProductImage;
private ConnectionDetector cd;
UserFunctions userFunction;
ProgressDialog mProgressDialog;
JSONObject jsonobject,jsonobj1;
JSONObject jsonobj_prodPriceDetails, jsonobj_RUPEE;
HListView listView;
Button img_buy_now;
String Vendor_id=null;
SharedPreferences pref;
String Store_id_pref=null;
String item_id_pref=null;
EditText edt_search;
public static Typeface font;
String from=null;
RelativeLayout pb_progress;
GridView related_grid;
ImageView add_cart;
String full_path_re;
static TextView notifCount;
ListView list;
SrollviewAdapter scrAdapter;
JSONArray jsonarray = null;
JSONArray jsonarray1=null;
JSONArray json_store_array = null;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> store_arraylist;
String images;
static String PRODUCT_IMAGES = "image_list";
static String COUNT = "count";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_item);
userFunction = new UserFunctions();
cd = new ConnectionDetector(getApplicationContext());
arraylist = new ArrayList<HashMap<String, String>>();
new DownloadJSON().execute();
pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Vendor_id=pref.getString("user_id", null);
Store_id_pref=pref.getString("store_id", null);
item_id_pref = pref.getString("item_id", null);
getActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Product List");
getActionBar().setIcon(R.drawable.ic_launcher);
Intent myIntent = getIntent();
from = myIntent.getStringExtra("from");
font = Typeface.createFromAsset(getBaseContext().getAssets(),
"fonts/Amaranth-Regular.otf");
if (cd.isConnectingToInternet()) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
//pb_progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
jsonobject = userFunction.imageG("9");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("image_gallery");
jsonarray1 =jsonobj1.getJSONArray("count");
String s= jsonarray1.toString();
System.out.print("jsonarray1:::::"+jsonarray1);
int b= Integer.parseInt(s);
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("image_list", jsonobject.getString("image_list"));
map.put("count","jsonarray1");
arraylist.add(map);
System.out.print("all data::::::"+map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter adapter = new MoreImageAdapter(MoreImage.this);
viewPager.setAdapter(adapter);
//pb_progress.setVisibility(View.GONE);
}
}
}
and this is a page adapter file
public class MoreImageAdapter extends PagerAdapter{
HashMap<String, String> resultp = new HashMap<String, String>();
Context context;
int count1;
// int[] imageId = {
// R.drawable.slide1,
// R.drawable.slide2,
// R.drawable.unfollow,
// R.drawable.facebook_icon,
// R.drawable.ic_launcher,
// R.drawable.follow_unfollow,};
public MoreImageAdapter(Context context){
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.image_item, container, false);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
imageView.setImageResource(imageId[position]);
((ViewPager)container).addView(viewItem);
return viewItem;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imageId.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((View)object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}
}
there are two json objects one is image and other is count. image contains more then 1 image.
i am able to get the data from json parsing in activity class but i want to set the data in page adapter class as that shows my slider.
so how can i pass those value i got in activity file to page adapter class???
please help......

You can pass those values using the constructor.
PagerAdapter adapter = new MoreImageAdapter(MoreImage.this, String images, ArrayList<Sting> something,...);
then in the MoreImageAdapter get those images from constructor
public MoreImageAdapter(Context context, String images, ArrayList<String> something,...){
this.context = context;
this.images = images;
this.something = new ArrayList<String>(something);
}
You can send what all you want to send and get it from the constructor.

Related

activity shows blank result?

I am developing an app using api to display list, and listview contains data. But when i run the project, activity shows blank result and logcat shown 'no value of "program"(i.e.array name)' message.
How do i show result of following code?
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String AID = "asanaid";
static String ANAME = "asananame";
static String DURATION = "duration";
static String IMGURL = "imgeurl";
static String IMGVERSION = "imgeversion";
static String AUDIOURL = "audiourl";
static String AUDIOVERSION = "audioversion";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_relaxation_lv);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://www.....");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("program");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("asanaid", jsonobject.getString("asanaid"));
map.put("asananame", jsonobject.getString("asananame"));
map.put("duration", jsonobject.getString("duration"));
map.put("imgeurl", jsonobject.getString("imgeurl"));
map.put("imgeversion", jsonobject.getString("imgeversion"));
map.put("audiourl", jsonobject.getString("audiourl"));
map.put("audioversion", jsonobject.getString("audioversion"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
public class ListViewAdapter extends BaseAdapter{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView tvAname, tvId, imgUrl, imgVersion, audioUrl, audioVersion, duration;
ImageView imgPose;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.relaxationlv_single_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
tvAname = (TextView) itemView.findViewById(R.id.lv_aname);
tvAname.setText(resultp.get(MainActivity.ANAME));
tvId = (TextView)itemView.findViewById(R.id.lv_aid);
tvId.setText(resultp.get(MainActivity.AID));
duration = (TextView)itemView.findViewById(R.id.lv_duration);
duration.setText(resultp.get(MainActivity.DURATION));
imgVersion = (TextView)itemView.findViewById(R.id.lv_imgversion);
imgVersion.setText(resultp.get(MainActivity.IMGURL));
audioVersion = (TextView)itemView.findViewById(R.id.lv_audioversion);
audioVersion.setText(resultp.get(MainActivity.AUDIOVERSION));
audioUrl= (TextView)itemView.findViewById(R.id.lv_audiourl);
audioUrl.setText(resultp.get(MainActivity.AUDIOURL));
imgPose = (ImageView)itemView.findViewById(R.id.lv_imgurl);
imageLoader.DisplayImage(resultp.get(MainActivity.IMGURL), imgPose);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, RelaxationLvAudioPlayerActivity1.class);
intent.putExtra("asanaid", resultp.get(MainActivity.AID));
intent.putExtra("asananame", resultp.get(MainActivity.ANAME));
intent.putExtra("duration", resultp.get(MainActivity.DURATION));
intent.putExtra("imgeurl", resultp.get(MainActivity.IMGURL));
intent.putExtra("imgeversion", resultp.get(MainActivity.IMGVERSION));
intent.putExtra("audiourl", resultp.get(MainActivity.AUDIOURL));
intent.putExtra("audioversion", resultp.get(MainActivity.AUDIOVERSION));
context.startActivity(intent);
}
});
return itemView;
}
}
You are getting the JSONException -
Please check if one of the following field is missing in your JSON Response -
map.put("asanaid", jsonobject.getString("asanaid"));
map.put("asananame", jsonobject.getString("asananame"));
map.put("duration", jsonobject.getString("duration"));
map.put("imgeurl", jsonobject.getString("imgeurl"));
map.put("imgeversion", jsonobject.getString("imgeversion"));
map.put("audiourl", jsonobject.getString("audiourl"));
map.put("audioversion", jsonobject.getString("audioversion"));
You can check this buy printing the value of jsonobject.getString("asaname") and so on.
Or the another case might be the value is of different dataType. E.g. audioversion you are trying to get as String but in JSON it is type of Integer.

Combining two asynk task in one activity sharing same adapter for both viewpager

I want to add two asynk task for 2 viewpager and need to combine below two codes in main activity. when i am adding one asynk task runs. i have added two viewpager view in xml file names pager and pager2.
can i use same adapter for both viewpager as values are same in json file?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager viewPager;
PagerAdapter pagerAdapter;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
static String FILMNAME = "film";
static String FILMPOSTER = "poster";
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setClipToPadding(false);
viewPager.setPadding(4, 0, 4, 0);
new DownloadJSON().execute();
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("eFilmsWorld");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = new JSONfunctions().getJSONfromURL("/upcomingFilms.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("upcomingFilms");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("film", jsonobject.getString("filmName"));
map.put("poster", jsonobject.getString("path"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
pagerAdapter = new ViewPagerAdapter(MainActivity.this, arraylist);
viewPager.setAdapter(pagerAdapter);
mProgressDialog.dismiss();
}
}
I want to add one more asynk task to above code as i am running two viewpager, one is for upcoming films and second is for films in theatres:
the second asynk task is:
// DownloadJSON2 AsyncTask
private class DownloadJSON2 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("eFilmsWorld");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = new JSONfunctions()
.getJSONfromURL("/filmsIntheatres.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("filmsIntheatres");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("film", jsonobject.getString("filmName"));
map.put("poster", jsonobject.getString("path"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
pagerAdapter = new ViewPagerAdapter(MainActivity.this, arraylist);
viewPager.setAdapter(pagerAdapter);
mProgressDialog.dismiss();
}
}
PagerAdapter Code:
public class ViewPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ViewPagerAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
this.data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
resultp = data.get(position);
// Declare Variables
TextView tvFilm;
ImageView ivPoster;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container, false);
// Locate the TextViews in viewpager_item.xml
tvFilm = (TextView) itemView.findViewById(R.id.filmnamePager);
ivPoster = (ImageView) itemView.findViewById(R.id.filmposterPager);
//Log.e("filmdetails", "Item "+data.get(position).get(MainActivity.FILMNAME));
// Capture position and set to the TextViews
tvFilm.setText(resultp.get(MainActivity.FILMNAME));
Uri posterUri = Uri.parse(resultp.get(MainActivity.FILMPOSTER));
Picasso.with(ViewPagerAdapter.this.context)
.load(posterUri)
.placeholder(R.drawable.coming_soon_placeholder)
.error(R.drawable.coming_soon_placeholder)
.into(ivPoster);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
I have used two viewpager adapter in mainactivity using two asynk task. it might help someone to use the code so answering my own question
used resources in this code:
Json asynk task, viewpager
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager viewPager;
ViewPager viewPager2;
PagerAdapter pagerAdapter;
PagerAdapter pagerAdapter2;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ProgressDialog mProgressDialog2;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> arraylist2 = new ArrayList<HashMap<String, String>>();
static String FILMNAME = "film";
static String FILMPOSTER = "poster";
static String FILMNAME2 = "film2";
static String FILMPOSTER2 = "poster2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Button upcomingFilms = (Button)findViewById(R.id.upcomingFilms);
upcomingFilms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUpcomingFilmsActivity();
}
});
Button filmsInTheatres = (Button)findViewById(R.id.filmsInTheatres);
filmsInTheatres.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FilmsInTheatresActivity();
}
});
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setClipToPadding(false);
viewPager.setPadding(4, 0, 4, 0);
viewPager2 = (ViewPager) findViewById(R.id.pager2);
viewPager2.setClipToPadding(false);
viewPager2.setPadding(4, 0, 4, 0);
new DownloadJSON().execute();
new DownloadJSON2().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("eFilmsWorld");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = new JSONfunctions()
.getJSONfromURL("...../upcomingFilms.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("upcomingFilms");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("film", jsonobject.getString("filmName"));
map.put("poster", jsonobject.getString("path"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
pagerAdapter = new ViewPagerAdapter(MainActivity.this, arraylist);
viewPager.setAdapter(pagerAdapter);
mProgressDialog.dismiss();
}
}
// DownloadJSON AsyncTask
private class DownloadJSON2 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(MainActivity.this);
mProgressDialog2.setTitle("eFilmsWorld");
mProgressDialog2.setMessage("Loading...");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist2 = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = new JSONfunctions()
.getJSONfromURL("...../filmsInTheatres.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("filmsInTheatres");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("film2", jsonobject.getString("filmName"));
map.put("poster2", jsonobject.getString("path"));
// Set the JSON Objects into the array
arraylist2.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
pagerAdapter2 = new ViewPagerAdapter2(MainActivity.this, arraylist2);
viewPager2.setAdapter(pagerAdapter2);
mProgressDialog2.dismiss();
}
}
private void goToUpcomingFilmsActivity(){
Intent intent = new Intent(this, UpcomingFilmsActivity.class);
startActivity(intent);
}
private void FilmsInTheatresActivity(){
Intent intent = new Intent(this, FilmsInTheatresActivity.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
/* if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
viewpager adapter 1
/**
* Created by pandeyrr on 18-Jan-16.
*/
public class ViewPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ViewPagerAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
this.data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
resultp = data.get(position);
// Declare Variables
TextView tvFilm;
ImageView ivPoster;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container, false);
itemView = inflater.inflate(R.layout.viewpager_item2, container, false);
// Locate the TextViews in viewpager_item.xml
tvFilm = (TextView) itemView.findViewById(R.id.filmnamePager);
ivPoster = (ImageView) itemView.findViewById(R.id.filmposterPager);
//Log.e("filmdetails", "Item "+data.get(position).get(MainActivity.FILMNAME));
// Capture position and set to the TextViews
tvFilm.setText(resultp.get(MainActivity.FILMNAME));
Uri posterUri = Uri.parse(resultp.get(MainActivity.FILMPOSTER));
Picasso.with(ViewPagerAdapter.this.context)
.load(posterUri)
.placeholder(R.drawable.coming_soon_placeholder)
.error(R.drawable.coming_soon_placeholder)
.into(ivPoster);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
view pager adaptor2
public class ViewPagerAdapter2 extends PagerAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ViewPagerAdapter2(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
this.data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
resultp = data.get(position);
// Declare Variables
TextView tvFilm;
ImageView ivPoster;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item2, container, false);
// Locate the TextViews in viewpager_item.xml
tvFilm = (TextView) itemView.findViewById(R.id.filmnamePager);
ivPoster = (ImageView) itemView.findViewById(R.id.filmposterPager);
tvFilm.setText(resultp.get(MainActivity.FILMNAME2));
Uri posterUri = Uri.parse(resultp.get(MainActivity.FILMPOSTER2));
Picasso.with(ViewPagerAdapter2.this.context)
.load(posterUri)
.placeholder(R.drawable.coming_soon_placeholder)
.error(R.drawable.coming_soon_placeholder)
.into(ivPoster);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
Viewpagers in activity_main
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="200dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager2"
android:layout_width="wrap_content"
android:layout_height="200dp" />
viewpager layout1
<ImageView
android:id="#+id/filmposterPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
<TextView
android:id="#+id/filmnamePager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
viewpager layout2
<ImageView
android:id="#+id/filmposterPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
<TextView
android:id="#+id/filmnamePager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

List View Items Deleted When Back Button Pressed Android

I am new to android development. I have implemented an activity which is Loading Json data to a listview. I have two activities now. First one is login Activity.Second one is loading list view activity.the json data is loading perfectly. but my problem is, when i pressed back button, the list view data is removing one by one. i have no idea where the problem is.
here is my main activity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
ImageButton login;
public static ArrayList<HashMap<String, String>> oslist;
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
static final String TAG_OS = "android";
static final String TAG_VER = "ver";
static final String TAG_NAME = "name";
static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loging);
oslist = new ArrayList<HashMap<String, String>>();
login = (ImageButton)findViewById(R.id.imageButton1);
new ArrayList<HashMap<String, String>>();
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.title);
name = (TextView)findViewById(R.id.artist);
api = (TextView)findViewById(R.id.time);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
Intent reult = new Intent(MainActivity.this,ViewList.class);
//reult.putStringArrayListExtra("map", oslist);
//startActivity(reult);
reult.putExtra("arraylist", oslist);
startActivityForResult(reult, 500);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my Listview Activity
public class ViewList extends Activity {
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Intent getres = getIntent();
//HashMap<String, String> hashMap = (HashMap<String, String>)getres.getSerializableExtra("map");
final ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
ListView list=(ListView)findViewById(R.id.list);
/* ListAdapter adapter = new SimpleAdapter(ViewList.this, arl,
R.layout.row,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.title,R.id.artist, R.id.time});*/
NewsRowAdapter adapter = new NewsRowAdapter(ViewList.this, R.layout.row, arl);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(ViewList.this, "You Clicked at "+arl.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
this is my Adapter Class
public class NewsRowAdapter extends BaseAdapter {
/*//ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
//ArrayList<HashMap<String, String>> data;
private List<Item> items;
//private Item objBean;
private int row;*/
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/*public NewsRowAdapter(Activity act, int resource, HashMap<String, List<String>> listChildData)) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.data = arrayList;
}*/
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
TextView title = (TextView) vi.findViewById(R.id.title);
TextView artist = (TextView) vi.findViewById(R.id.artist);
TextView time = (TextView) vi.findViewById(R.id.time);
ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
title.setText(song.get(MainActivity.TAG_VER));
artist.setText(song.get(MainActivity.TAG_NAME));
time.setText(song.get(MainActivity.TAG_API));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);
Button accept = (Button) vi.findViewById(R.id.btnaccept);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//CustomizedListView getlist = new CustomizedListView();
final int x = (int) getItemId(position);
Toast.makeText(parent.getContext(),"you clicked "+ x , Toast.LENGTH_SHORT).show();
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "view clicked: " , Toast.LENGTH_SHORT).show();
}
});
return vi;
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int possision) {
// TODO Auto-generated method stub
return possision;
}
#Override
public long getItemId(int possision) {
// TODO Auto-generated method stub
return possision;
}
}
please some one help me...
Yes it will do so, When you press back button your activity get finished , So the view inside the activity will get deleted , Either you must keep the data in a seperate class, outside activity or keep the activity alive.

adding data to existing listview

I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.

Populating Gridview from JSON response

I am trying to populate Grid View from JSON response received from Async Task. Below is the activity file
public class OpenTableActivity extends Activity implements AsyncResponse{
String serUri, method;
OpenTableAdapter op;
WebServiceAsyncTask webTask = new WebServiceAsyncTask(this);
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_table);
getTables();
webTask.listener = this;
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new OpenTableAdapter(this,tableList));
LinearLayout layout = (LinearLayout) findViewById(R.id.opentableLinear);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
hideKeyboard(view);
return false;
}
});
Button btn = (Button) findViewById(R.id.table_home_btn);
btn.setOnClickListener(homeBtn);
}
public boolean getTables() {
serUri = "tables.json";
method = "get";
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask(OpenTableActivity.this);
webServiceTask.execute(serUri, method, this);
return true;
}
#Override
public void WriteJsonArray(JSONArray result) {
// TODO Auto-generated method stub
try {
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String tabLabel = c.getString("tablabel");
String tabStatus = c.getString("tabstatus");
HashMap<String, String> map = new HashMap<String, String>();
map.put("table_name", tabLabel);
map.put("table_status", tabStatus);
tableList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
The Adapter class to fill grid view is as below
public class OpenTableAdapter extends BaseAdapter {
private Context mContext;
String orderNumber;
OpenTableActivity openInstance;
String tableLabel;
String tableStatus;
LayoutInflater mInflater;
ArrayList<HashMap<String, String>> tablist = null;
public OpenTableAdapter(Context c, ArrayList<HashMap<String, String>> tablelist ) {
// TODO Auto-generated constructor stub
mContext = c;
mInflater = LayoutInflater.from(c);
tablist = tablelist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
openInstance = new OpenTableActivity();
return openInstance.tableList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.button,
parent, false);
holder = new ViewHolder();
holder.btn = (Button) convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Button btn = (Button) view.findViewById(R.id.button);
HashMap<String, String> map = tablist.get(position);
for (java.util.Map.Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
holder.btn.setText(key);
return convertView;
}
static class ViewHolder
{
Button btn;
}
}
the interface class defined is as below:
public interface AsyncResponse {
public void WriteJsonArray(JSONArray tableList);
}
The Async task class is as below
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
AsyncResponse listener;
public WebServiceAsyncTask(){}
public WebServiceAsyncTask(Context appcontext)
{
this.context=appcontext;
listener = (AsyncResponse) this.context;
}
String serviceUrl;
OpenTableActivity openInstance=new OpenTableActivity();
CategoryActivity catAct;
private static JSONArray json = null;
private Context context = null;
private static JSONObject jsonObject = null;
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
serviceUrl = (String) params[0];
String method = (String) params[1];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
json = httph.fetch();
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
// TODO Auto-generated method stub
// dismiss progress dialog
// update ui here
super.onPostExecute(result);
if (listener != null){
listener.WriteJsonArray(result);
}
}
On running this I am getting Stackoverflow error as soon as activity class is called. I tried many different options but still same error. Not sure what I am missing as unable to debug too as its giving error even before entering the activity class. Please advise. Thanks.
Posting solution. From the discussion
You need to move the below to WriteJsonArray. Once you get the data you need to pass the same to the adapter class
gridview.setAdapter(new OpenTableAdapter(this,tableList));
Replace your getCount by
#Override
public int getCount() {
return tablist.size();
}
In getview remove your for loop
HashMap<String,String> map = tablist.get(position);
String value = map.get("key");
// make sure the key i right. "key" here is only an example. replace with right key
holder.btn.setText("value");
remove this
WebServiceAsyncTask webTask = new WebServiceAsyncTask(this); // at the beginnning
remove this from asynctask
OpenTableActivity openInstance=new OpenTableActivity();
AsyncTask<Void, Void, Boolean> waitForCompletion = new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Void... params) {
}
#Override
protected void onPostExecute(Boolean result) {
}
}

Categories

Resources