Android ListView Pull Down and Pull Up - android

I am new on Android Applications development. I want to know how to implement Pull down refresh and Pull up get more item from server in Listview.
How can I do it?
My Code get items from server is below.
private class DownloadJSONItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressbar
if (!prefs) {
progressBar.setVisibility(View.VISIBLE);
}
}
#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("Server URL",latitude, longitude);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("places");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
double convertString = Double.parseDouble(jsonobject.getString("distance"));
double convertKMToMile = convertString * 0.6124;
String convertedValue = String.format("%.2f",convertKMToMile);
// Retrive JSON Objects
map.put("places_name", jsonobject.getString("places_name"));
map.put("distance", convertedValue);
map.put("places_icon", jsonobject.getString("places_icon"));
// 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) {
//Toast.makeText(getActivity(), getString(jsonarray.length()), 6000).show();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressbar
progressBar.setVisibility(View.GONE);
if (prefs) {
prefs = false;
}
}
}
Thank you.

There is a nice library for that https://github.com/Maxwin-z/XListView-Android
For Refresh:
#Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
start = ++refreshCnt;
items.clear();
geneItems();
// mAdapter.notifyDataSetChanged();
mAdapter = new ArrayAdapter<String>(XListViewActivity.this, R.layout.list_item, items);
mListView.setAdapter(mAdapter);
onLoad();
}
}, 2000);
}
For load more:
#Override
public void onLoadMore() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
geneItems();
mAdapter.notifyDataSetChanged();
onLoad();
}
}, 2000);
}

Related

Swipte to Refresh keeps adding TextViews

I'm working on an Android app that uses information form an API and displays it in a list view. It works, but I can't figure out how to implement Swipe to Refresh properly. Right now when it refreshes it doesnt update the data in the lists TextView fields, but adds more of them underneath. I'm very new to this and would appreciate help figuring it out.
Here is the code I have so far.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.list);
lView.setAdapter(adp);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "URL";
String url2 = "URL";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try { /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try { /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lv.setAdapter(adapter);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Hope this makes some sense and would really apreciate any help! If I can get that working, I will probably have more questions, but right now one thing at a time. :P
Thanks! :)
In your swipe refresh listener when you call your async task, your are creating a new adapter every time. simply call notifyDataChanged on your data.
In your on background task first check if the data is already present in your priceList then don't add the item in your list.
Or you can first clear the list and then add all the result from json in to price list.
Here is the code which clears list on swipe refresh:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lView.setAdapter(adapter);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "https://miningpoolhub.com/index.php?page=api&action=getuserallbalances&api_key=MyApiKey";
String url2 = "https://api.coinmarketcap.com/v1/ticker/";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try {
coinList.clear(); /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
Coin coinObj= new Coin(/*pass the arguments*/);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try {
priceList.clear(); /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
// ListAdapter adapter = new SimpleAdapter(
// MainActivity.this, coinList,
// R.layout.list_item, new String[]{"coin", "confirmed",
// "exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
// R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
adapter.notifyDataSetChanged();
}
}
}

Android - json list view

I'm using volley for web services. So, when I run the app each time it doesn't show anything in the list. But when I use debug, sometimes I got the list correctly. So here is the code.
It's like it insert the listItem on Listview before getting the data from json , i tried to put a wait() before the adapter but android studio don't accept it .
Is there anyone who had similar problem ?
public class listedeal_res extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listedeal_res);
Button ajouter=(Button) findViewById(R.id.ajouetres);
Intent i =getIntent();
final ListView maListView = (ListView) findViewById(R.id.liste_deal_res);
final int idres=i.getIntExtra("idres",0);
final boolean b =true;
ajouter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(listedeal_res.this,AjouterDeal.class);
intent.putExtra("idres",idres);
listedeal_res.this.startActivity(intent);
}
});
final ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
final HashMap<String, String> map;
map = new HashMap<String, String>();
Response.Listener<String> resp=new Response.Listener<String>()
{
#Override
public void onResponse (String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
int i=0;
while (jsonResponse.getJSONArray(i)!=null)
{
while (jsonResponse.getJSONArray(i)!=null)
{
map.put("Nom",jsonResponse.getJSONArray(i).getString(2));
map.put("Restraurant",jsonResponse.getJSONArray(i).getString(0));
map.put("description",jsonResponse.getJSONArray(i).getString(1));
listItem.add(map);
i++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
drinkeat.drinkandeat.javas.liste_deal_res_req liste_deal_res_req= new liste_deal_res_req(idres+"",resp);
RequestQueue queue= Volley.newRequestQueue(listedeal_res.this);
queue.add(liste_deal_res_req );
SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.row_deal_user,
new String[] {"Nom", "Restraurant", "description"}, new int[] {R.id.titlerow, R.id.resteaurantnaamerow, R.id.descriptionrow});
maListView.setAdapter(mSchedule);
}
}
Add notifydatasetchange method to your adapter like below
public void onResponse (String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
int i=0;
while (jsonResponse.getJSONArray(i)!=null)
{
while (jsonResponse.getJSONArray(i)!=null)
{
map.put("Nom",jsonResponse.getJSONArray(i).getString(2));
map.put("Restraurant",jsonResponse.getJSONArray(i).getString(0));
map.put("description",jsonResponse.getJSONArray(i).getString(1));
listItem.add(map);
i++;
}
}
mSchedule.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}

notifyDataSetChanged not work

I have problem with notifyDataSetChanged,i read some another post but can't help me and i have problem yet, i call that after my listview setadapter but mylist hasn't any change! this is my code, please help me, Thanks
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
// this will post our text data
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... strings) {
try {
postTextandGetRespons("http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php");
JSONObject JsonOb = new JSONObject(responseString);
JSONArray messages = JsonOb.getJSONArray("Users");
for ( int i=0; i<= f;i++){
JSONObject c = messages.getJSONObject(i);
firstname = c.getString("firstname");
lastname = c.getString("lastname");
username = c.getString("username");
items.add(new item(firstname,lastname,username));
}
adapter.notifyDataSetChanged();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String responseStr) {
if ( setAdapter == true) {
lv = (ListView) findViewById(R.id.listView_asabani);
adapter = new adapter_common(getBaseContext(), items);
lv.setAdapter(adapter);
setAdapter = false;
}
}
}
Move adapter.notifyDataSetChanged(); to onPostExecute() that's where UI code should run.

Unable to create a adapter in fragment. Want to show data from JSON

I want to show the array list using JSON in fragment. The code works fine in activity but not in fragment. And the code is. I just want to display a list of data using JSON, if the user clicks the code the data must shown in another fragment.
package com.example.everwinvidhyashram;
public class PrincipalSpeechFragment extends Fragment implements OnClickListener {
private ProgressDialog pDialog;
private static String url =
"http://imaginetventures.net/sample/everwin_vidhyashram/webservice/rest/?module=speech&from=1-9-
2014&to=30-9-2014";
// JSON Node names
private static final String TAG_PRINCIPAL_SPEECH ="Principal Speech";
private static final String TAG_SPEECH= "speech";
private static final String TAG_DESC = "desc";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> speechlist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_principal_speech, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
speechlist = new ArrayList<HashMap<String, String>>();
// ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
/*Dialog = new ProgressDialog(PrincipalSpeechFragment.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();*/
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_PRINCIPAL_SPEECH);
// looping through All Contacts
for (int i = 0; i < 1; i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_SPEECH);
// tmp hashmap for single contact
HashMap<String, String> speech = new HashMap<String, String>();
// adding each child node to HashMap key => value
speech.put(TAG_SPEECH, id);
// speech.put(TAG_DESC, name);
// adding contact to contact list
speechlist.add(speech);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(PrincipalSpeechFragment.this, speechlist,
R.layout.principal_speech_items, new String[] { TAG_SPEECH,
}, new int[] { R.id.principal,
});
setListAdapter(adapter);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The problem occurs in
ListAdapter adapter = new SimpleAdapter(PrincipalSpeechFragment.this, speechlist,
R.layout.principal_speech_items, new String[] { TAG_SPEECH,
}, new int[] { R.id.principal,
});
setListAdapter(adapter);
I have used this list adapter in the fragment. May be help.
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter =new SimpleAdapter(
getActivity(), speechlist,
R.layout.principal_speech_items, new String[] { TAG_SPEECH },
new int[] { R.id.principal });
// updating listview
setListAdapter(adapter);
}//run
});//runOnUiThread
}//onpostexecute

preference activity from dynamic array

getting data from webservices but values not getting out of async class,
public class Settings extends PreferenceActivity{
ListPreference lst1;
public static String[] batcharr;
public static String[] streamarr;
public Settings(){
// TPGetListone getlist = new TPGetListone();
// getlist.execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.settings);
lst1 = (ListPreference) findPreference("prefStream");
TPGetListone getlist = new TPGetListone();
getlist.execute();
lst1.setEntries(batcharr);
lst1.setEntryValues(batcharr);
}
public class TPGetListone extends AsyncTask<String, Void, Void> {
String datax = "";
JSONArray array;
List<String> lstbatch;
List<String> lststream;
private String LogStr = "Panchratna";
#Override
protected Void doInBackground(String... params) {
DataHelper gd = new DataHelper("http://xxxx.com/EventGetter","http://xxxx.com/EventGetter.asmx?wsdl","http://xxxx.com/EventGetter/GetCourseList","GetCourseList");
datax = gd.GetData("query","SELECT batch, stream FROM batch");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.i(LogStr, "onPostExecuteCATALOG");
try {
array = new JSONArray(datax);
} catch (JSONException e) {
e.printStackTrace();
}
lstbatch = new ArrayList<String>();
lststream = new ArrayList<String>();
for(int i = 0; i < array.length(); i++){
try {
lstbatch.add(array.getJSONObject(i).getString("batch"));
lststream.add(array.getJSONObject(i).getString("stream"));
} catch (JSONException e) {
e.printStackTrace();
}
}
batcharr = new String[lstbatch.size()];
streamarr = new String[lststream.size()];
for (int i=0;i<lststream.size();i++){
lststream.toArray(batcharr);
lstbatch.toArray(streamarr);
}
}
#Override
protected void onCancelled(Void aVoid) {
super.onCancelled(aVoid);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
i know this is not a proper way,
i m using webservices to fetch json values and convert it to list<>
by debugging, values do come in List which is lstbatch and lststream,
and array batcharr and streamarr ,
but when the task executes , in on create method , batcharr and streamarr is showing error,
same method worked last time on an Activity
Please help ,
Thank You
Move this code above the Async and it will be accessible
List<String> lstbatch;
List<String> lststream;
public class TPGetListone extends AsyncTask<String, Void, Void> {
String datax = "";
JSONArray array;
//--> Remove to Up -->List<String> lstbatch;
//--> Remove to Up -->List<String> lststream;
private String LogStr = "Panchratna";
EDIT
for (int i=0;i<lststream.size();i++){
batcharr[i]=lststream.get(i);
streamarr[i]=lstbatch.get(i);
}
put this code
lst1.setEntries(batcharr);
lst1.setEntryValues(batcharr);
in
PostExecute method
protected void onPostExecute(Void aVoid) {
Log.i(LogStr, "onPostExecuteCATALOG");
try {
array = new JSONArray(datax);
} catch (JSONException e) {
e.printStackTrace();
}
lstbatch = new ArrayList<String>();
lststream = new ArrayList<String>();
for(int i = 0; i < array.length(); i++){
try {
lstbatch.add(array.getJSONObject(i).getString("batch"));
lststream.add(array.getJSONObject(i).getString("stream"));
} catch (JSONException e) {
e.printStackTrace();
}
}
batcharr = new String[lstbatch.size()];
streamarr = new String[lststream.size()];
for (int i=0;i<lststream.size();i++){
lststream.toArray(batcharr);
lstbatch.toArray(streamarr);
}
===> lst1.setEntries(batcharr);
===> lst1.setEntryValues(batcharr);
}

Categories

Resources