I am trying to pass the data from this main activity to another activity
I am successful in sending data between activities .... Like the data from Edit-text to next activity through putExtra and GetExtra methods and passing as intents
But i am facing challenge in this particular task where it involves
sending data from listview to an ordinary activity
data is populated in the list view from JSON so when on click of a
row how can i send the data from that row to a new activity
Any Ideas,
ativity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7002/";
List<Item> yourData = new ArrayList<Item>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} 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);
progressDialog.dismiss();
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this,CopperChimneyDesc.class);
startActivity(myIntent);
}else if(position == 1)
{
//Intent myIntent = new Intent(MainActivity.this,AroyDesc.class);
//startActivity(myIntent);
}
}
});
}
}
}
item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
Thanks,
Ok so you would do
String item = yourData.get(position).getName();
Then you can add the string to intent using:
intent.putExtra("restaurent", item);
On the other end if its textview you would do
textView.setText(getIntent().getExtras().getString("restaurent"));
intent.putExtra("City Name", String.valueOf(lvCity.getSelectedItem()));
try this one to cast.
you can parcle data and send it to other activity with putxtera method.please see How to store values in onSaveInstanceState() and retrive?
Since you have the index of the item in the listview the user has clicked you can get the item value from the adapter:
String value = (String)customAdapter.getItem(position);
Intent myIntent = new Intent(MainActivity.this,CopperChimneyDesc.class);
intent.putExtra("restaurant_name", value);
startActivity(myIntent);
You can save the data in sharedPreferences and can access it from other activity. Just an idea :)
Related
I'm using AsyncTask with Viewpager and so far everything is working properly. When I run my application everything works fine and displays the data by sliding from one column to another. But when you start the app the data in that first column does not appear. I have tried in the onCreate insert the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "1";
layout = R.id.lista;
empty = R.id.empty;
DownloadJSON newTask = new DownloadJSON(url,layout,empty);
newTask.execute();
...
It does not work. The app is closed. How do I can load this data when the app starts?
My code:
public class MainActivity extends Activity {
ViewPager vp;
private vpAdapter myAdapter;
ListViewAdapter adapter;
ListView listview;
String url;
int layout;
int empty;
ArrayList<HashMap<String, String>> arraylist;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
vp = (ViewPager) findViewById(R.id.pager);
myAdapter = new vpAdapter();
vp.setAdapter(myAdapter);
vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
//CASE 0 = FIRST PAGE
switch (i) {
case 0:
url = "1";
layout = R.id.lista;
empty = R.id.empty;
DownloadJSON newTask = new DownloadJSON(url,layout,empty);
newTask.execute();
break;
default:
break;
case 1:
url = "2";
layout = R.id.lista2;
empty = R.id.empty2;
DownloadJSON newTask2 = new DownloadJSON(url,layout,empty);
newTask2.execute();
break;
case 2:
url = "3";
layout = R.id.lista3;
empty = R.id.empty3;
DownloadJSON newTask3 = new DownloadJSON(url,layout,empty);
newTask3.execute();
break;
case 3:
url = "4";
layout = R.id.lista4;
empty = R.id.empty4;
DownloadJSON newTask4 = new DownloadJSON(url,layout,empty);
newTask4.execute();
break;
case 4:
url = "5";
layout = R.id.lista5;
empty = R.id.empty5;
DownloadJSON newTask5 = new DownloadJSON(url,layout,empty);
newTask5.execute();
break;
case 5:
url = "6";
layout = R.id.lista6;
empty = R.id.empty6;
DownloadJSON newTask6 = new DownloadJSON(url,layout,empty);
newTask6.execute();
break;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String givemeurl;
int givemelayout;
int givemeempty;
public DownloadJSON(String url, int layout, int empty) {
this.givemeurl = url;
this.givemelayout = layout;
this.givemeempty = empty;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ListView listview = (ListView) findViewById(layout);
if(listview.getCount()==0){
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Cargando...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}else{
cancel(true);
Log.e("CANCELADO","CANCELADO");
}
}
#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("URL");
if(jsonobject != null){
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("productos");
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("imagen", jsonobject.getString("imagen"));
map.put("nombre", jsonobject.getString("nombre"));
map.put("total", jsonobject.getString("total"));
map.put("empresa", jsonobject.getString("empresa"));
map.put("unidades", jsonobject.getString("unidades"));
map.put("precionuevo", jsonobject.getString("precionuevo")+" €");
map.put("precioantiguo", jsonobject.getString("precioantiguo")+" €");
map.put("descripcion", jsonobject.getString("descripcion"));
map.put("direccion", jsonobject.getString("direccion"));
map.put("telefono", jsonobject.getString("telefono"));
map.put("latitud", jsonobject.getString("latitud"));
map.put("longitud", jsonobject.getString("longitud"));
map.put("codeqr", jsonobject.getString("codeqr"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
//e.printStackTrace();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
}else{
//Log.e("Response","No data");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(givemelayout);
listview.setEmptyView(findViewById(givemeempty));
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
//Log.e("",""+listview.getCount());
}
}
For a better performance, You should download all of the data, before showing the view pager. Currently you're downloading the same data again and again, whenever the user swipes the view pager. And not seeing any data on the first page initially is an expected result, because you download data only in onPageChangeListener. My suggestion is:
Create a dummy activity and make it launcher. It will be for downloading data. You can also do some configurations initially.
In onCreate method of that activity, download all of the necessary data your app needs using an AsyncTask.
In onPostExecute method of that AsyncTask start your main intent.
And finish the dummy activity to remove it from the stack so that when the user clicks back, your dummy activity won't be seen.
You can either pass the data you got to your main intent with:
Setting them as extras to your intent, using putExtra
Or you can store them in Application class, this is the only class that won't be destroyed by Android OS, so it's safe to store data there.
in my app im using gridview
when in portrait mode it shows one column.
in landscape mode new layout defined to show 2 column.
this is how the app works..
when app is launched, progress dialog is called to load website name from sqlite database and async is used to load website from sqlite db. the progress dialog is dismissed after the gridview is inflated.
now after loading the website name into gridview the screen orientation changes, it restarts the progress dialog.
i know that on screen orientation change the ondestroy() and then oncreate() are called.
this is my app's src code.
public class RSSReaderActivity extends Activity {
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> rssFeedList;
RSSParser rssParser = new RSSParser();
RSSFeed rssFeed;
Button add_rss;
// array to trace sqlite ids
String[] sqliteIds;
public static String TAG_ID = "id";
public static String TAG_TITLE = "title";
public static String TAG_LINK = "link";
GridView gridview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.site_list);
add_rss = (Button) findViewById(R.id.add_rss);
gridview = (GridView) findViewById(R.id.gridview);
rssFeedList = new ArrayList<HashMap<String, String>>();
new loadStoreSites().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
...
...
);
add_rss.setOnClickListener(new View.OnClickListener() {
...
...
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class loadStoreSites extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
...
...
}
#Override
protected String doInBackground(String... args) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
RSSDatabaseHandler rssDb = new RSSDatabaseHandler(getApplicationContext());
// listing all websites from SQLite
List<WebSite> siteList = rssDb.getAllSites();
sqliteIds = new String[siteList.size()];
// loop through each website
for (int i = 0; i < siteList.size(); i++) {
WebSite s = siteList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, s.getId().toString());
map.put(TAG_TITLE, s.getTitle());
map.put(TAG_LINK, s.getLink());
// adding HashList to ArrayList
rssFeedList.add(map);
// add sqlite id to array
// used when deleting a website from sqlite
sqliteIds[i] = s.getId().toString();
}
gridview.setAdapter(new SimpleAdapter(RSSReaderActivity.this,rssFeedList, R.layout.site_list_row,new String[] { TAG_ID, TAG_TITLE, TAG_LINK },new int[] { R.id.sqlite_id, R.id.title, R.id.link }));
registerForContextMenu(gridview);
}
});
return null;
}
protected void onPostExecute(String args) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
}
}
SO how do we use onsavedinstance() over here.. please can anyone guide me.
add this in menifest file
android:configChanges="keyboardHidden|orientation|screenSize"
Trying to parse an html pages like http://www.ts.kg/serials/ on android. Tried to do it with htmlcleaner, but it didnot work. Trying to do it with jsoup. In the begining was my code to complex. Here is the shortest code. The same thing works on java Please help. My Logs http://smartpics.kz/imgs/1361209668WW5O.JPG
Here is my class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] names= {};
String url = "http://www.ts.kg/mults/";
try {
Document doc = Jsoup.connect(url).get();
Element e = doc.body();
Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
for (int i =0;i<ggg.size();i++) {
Element linkk = ggg.get(i);
if(linkk.getElementsByTag("a")!=null){
Element atom = linkk.getElementsByTag("a").first();
String n = atom.getElementsByTag("span").first().text();
names[i] = n;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView lvMain = (ListView) findViewById(R.id.listViewData);
// создаем адаптер
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names);
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
posted 20.feb.2013:
tryed to do it as it was proposed by Shoshy (thanks for your answer), but it didn't work (perhaps because of my not-from-right-place-growing hands). Here is my modified code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "http://www.ts.kg/mults/";
pd = ProgressDialog.show(MainActivity.this, "Working...", "request to server", true, false);
//Запускаем парсинг
new AsyncExecution().execute();
}
private ProgressDialog pd;
String url;;
String names[];
private class AsyncExecution extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// here your task will be done in seperate thread from UI thread
// and if you want to use the variables (that will be modifed here)
// from anywhere in MainActivity, then you should declare them as global
// variable in MainActivity. remember you cannot update UI from here , like
// Toast message. if you want to do that you can use OnPostExecute
// method bellow .
try {
ArrayList<String> array = new ArrayList<String>();
Document doc = Jsoup.connect(url).get();
Element e = doc.body();
Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
for (int i =0;i<ggg.size();i++) {
Element linkk = ggg.get(i);
if(linkk.getElementsByTag("a")!=null){
Element atom = linkk.getElementsByTag("a").first();
String n = atom.getElementsByTag("span").first().text();
array.add(n);
}
}
for (int i = 0;i<array.size();i++){
names[i]=array.get(i);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//Убираем диалог загрузки
pd.dismiss();
//Находим ListView
ListView listview = (ListView) findViewById(R.id.listViewData);
//Загружаем в него результат работы doInBackground
listview.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, names));
}
}
}
you have to make the request for getting the page in another thread from UI thread. you can use AsyncTask. i am giving some example by editing your code :
the link about AsyncTask is : about AsynckTask
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the class is defined bellow
new AsyncExecution().execute();
//other codes.....
.......................
}
/// your other codes .....
// you need to add this class
private class AsyncExecution extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// here your task will be done in seperate thread from UI thread
// and if you want to use the variables (that will be modifed here)
// from anywhere in MainActivity, then you should declare them as global
// variable in MainActivity. remember you cannot update UI from here , like
// Toast message. if you want to do that you can use OnPostExecute
// method bellow .
try {
Document doc = Jsoup.connect(url).get();
Element e = doc.body();
Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
for (int i =0;i<ggg.size();i++) {
Element linkk = ggg.get(i);
if(linkk.getElementsByTag("a")!=null){
Element atom = linkk.getElementsByTag("a").first();
String n = atom.getElementsByTag("span").first().text();
names[i] = n;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
}
}
In my application I have 2 fragment, Fragment A and Fragment B.On both these fragments Iam doing some XML parsing and populating listviews.I want to implement a splash screen for my app.So that it display during parsing and population of listviews and finishes when its done. For this, I have created an activity SplashActivity.I have Implemented asyntask on FragmentA and called the SplashActivity on preexecute section.Now, when the app launches SplashActivity get started.But I cant finish this acitivity on postexecute of FragmentA. getActivity().finishActivity() is not working.Please some one help me to solve this issue or suggest me another method to implement Splash screen on Fragment Activity. Thanks in advance....
here is my FragmentA=>
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating layout
View v = inflater
.inflate(R.layout.headlines_fragment, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("Tag", "onCreateView");
// We set clear listener
loading = (ProgressBar) getActivity().findViewById(R.id.progressBar1);
if (Headlines.headflag == "malayalam") {
urls = "http://www.abc.com/rssfeeds/19_18_17_25/1/rss.xml";
}
if (Headlines.headflag == "english") {
urls = "http://www.abc.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
}
new ProgressAsyncTask().execute();
MainActivity.refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProgressAsyncTask().execute();
}
});
}
public void populate_listview() {
newsList = new ArrayList<HashMap<String, String>>();
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
newsList.add(map);
MarqueeStr = MarqueeStr + " *** " + Title[i];
}
}
public void StartProgress() {
new ProgressAsyncTask().execute();
}
public class ProgressAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
myProgress = 0;
Intent intent = new Intent(getActivity(), Splash.class);
startActivityForResult(intent, 5); //Here I called Splash Activity
loading.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getActivity().finishActivity(5);// Here I tried to finish flash activity
if (Title == null) {
final AlertDialog.Builder alertbox = new AlertDialog.Builder(
getActivity());
alertbox.setMessage("Error in connection.Do you want to retry");
alertbox.setPositiveButton("retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// getActivity().finish();
// Intent intent = new Intent(getActivity(),
// MainActivity.class);
// startActivityForResult(intent,1);
}
});
alertbox.setNegativeButton("exit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// getActivity().finish();
}
});
alertbox.show();
}
list = (GridView) getActivity().findViewById(R.id.grid);
// Getting adapter by passing xml data ArrayList
adapter = new HeadlinesAdapter(getActivity(), newsList);
list.setAdapter(adapter);
loading.setVisibility(View.INVISIBLE);
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/karthika.TTF");
MainActivity.flashnews.setText(MarqueeStr);
if (Headlines.headflag == "malayalam") {
MainActivity.flashnews.setTypeface(tf);
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myintent = new Intent(
"com.abc.malayalam2headlinespodcast.PODCAST");
Bundle mybundle = new Bundle();
mybundle.putInt("number", position);
myintent.putExtras(mybundle);
startActivity(myintent);
}
});
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parse();
if (Title != null) {
populate_listview();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
}
}
public static void parse() {
//parsing done here
}
}
You should not implement your Splash as an Activity but rather as a DialogFragment. Simply style that dialog fragment so that it appears fullscreen.
Concerning showing:
SplashDialogFragment splashDlg = new SplashDialogFragment();
splashDlg.show(getSupportFragmentManager(), "SplashScreen");
Then closing:
SplashDialogFragment splashDlg = (SplashDialogFragment) getSupportFragmentManager().findByTag("SplashScreen");
splashDlg.dismiss();
just to answer the question which is your title actually "To finish an activity from Fragment", it's always a good way to use interface to interact from Fragment to Activity as per the docs: Communicating with Activity from Fragment. So one must always declare an interface in Fragment which is to be implemented in your activity something like below:
public class SplashActivity extends Activity implements FragmentA.FragmentListenerCallback {
public void onFragmentInteraction() {
//finish your activity or do whatever you like
finish();
}
}
public class FragmentA extends Fragment {
private FragmentListenerCallback fragmentListenerCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentListenerCallback = (FragmentListenerCallback) activity;
}
public interface FragmentListenerCallback {
void onFragmentInteraction();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(fragmentListenerCallback != null){
fragmentListenerCallback.onFragmentInteraction();
}
}
}
Am using Async Task in my application to get response from web service using restful web service. My code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_page);
_mContext = this;
new JSONParserTask().execute();
}
asynctask class
private class JSONParserTask extends AsyncTask<Void, Void, ListAdapter >{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// dialog = new ProgressDialog(_mContext);
// dialog.setMessage("Loading...");
// dialog.show();
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0) {
ListAdapter adapter = null;
itemsList = new ArrayList<HashMap<String, String>>();
jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Constants.JsonURL);
if(json == null){
Log.v(TAG, "----------- null");
return null;
}
try {
// Getting Array of Items
items = json.getJSONArray(TAG_ITEMS);
// looping through All items
for(int i = 0; i < items.length(); i++) {
JSONObject itemsObj = items.getJSONObject(i);
JSONObject products = null;
products = itemsObj.getJSONObject(TAG_PRODUCT);
Log.d(TAG,"product array "+products.toString());
JSONArray images = products.getJSONArray(TAG_IMAGES);
JSONObject imagesObj = images.getJSONObject(0);
Log.d(TAG, "......."+ imagesObj.getString(TAG_LINK));
String imageUrl = imagesObj.getString(TAG_LINK);
// Storing each json item in variable
String kind = itemsObj.getString(TAG_KIND);
String id = itemsObj.getString(TAG_KID);
String selfLink = itemsObj.getString(TAG_SELFLINK);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_KIND, kind);
map.put(TAG_KID, id);
map.put(TAG_SELFLINK, selfLink);
// adding HashList to ArrayList
itemsList.add(map);
}
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
} catch(JSONException e){
e.printStackTrace();
}
return adapter;
}
#Override
protected void onPostExecute(ListAdapter adapter) {
lv.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// some action
}
});
//dialog.dismiss();
}
}
with this code every thing working fine without using progress dialog. If u found, the code related to progress dialog is commented in above class.
If i uncomment progress dialog code, am not getting any response from server. I have tried with debugging also but never get any idea to remove this error.
Can some one tell what wrong am doing here.
ok the reason for that is you are updating you are adapter in your doInBackground() method
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
This code is related to the MAIN THREAD and shouldn't be called here in the background thread, remove it from here, and add it to the onPostExecute() , just pass an array list from the Background thread and do other UI related stuff in the onPostExecute()
Try this
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(mProgressDialog!=null){
mProgressDialog.dismiss();
}
}
Try this one, rather
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0){
//do your stuff here
}
#Override
protected void onPostExecute(Void result) {
if(mProgressDialog!=null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
Try this
#Override
protected void onPreExecute() {
pd=new ProgressDialog(m_context);
pd.setTitle("Authenticating");
pd.show();
}
#Override
protected Void doInBackground(Void... args) {
//your stuff
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
}