Setonitemclicklistener with AsyncTask gives NullPointerException - android

Need your help!!!
I have activity, where I get some data in JSON format and put it ListView. Everything works fine. But I want to define what item was clicked in list with Setonitemclicklistener. I tried to use it in onPostExecuted() method of my inner Connection class,which extends AsyncTask, but I've got NullPoinerException
public class ConnectionActivity extends ListActivity{
JsonParser jsonParser = new JsonParser();
private ListView listView;
JSONArray inbox = null;
private ProgressDialog pDialog;
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Date";
private static final String TAG_DATE = "Name";
private static final String TAG_PRICE = "Price";
ArrayList<HashMap<String,String>> resultList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resultList = new ArrayList<HashMap<String,String>> ();
new Connection().execute();
new ListHandler().execute();
}
class Connection extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectionActivity.this);
pDialog.setMessage("Не базарь и жди пока загрузиться!!!!");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest();
Log.d("Outbox JSON",json.toString());
try{
JSONArray jArray = new JSONArray(json);
for (int i=0;i<jArray.length();i++) {
JSONObject c = jArray.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name= c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
String price = c.getString(TAG_PRICE);
// creating new HashMap
HashMap<String, String> hashmap = new HashMap<String, String>();
// adding each child node to HashMap key => value
hashmap.put(TAG_ID, id);
hashmap.put(TAG_NAME, name);
hashmap.put(TAG_DATE, date);
hashmap.put(TAG_PRICE, price);
// adding HashList to ArrayList
resultList.add(hashmap);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ConnectionActivity.this, resultList,
R.layout.connect_item, new String[] { TAG_ID, TAG_NAME, TAG_DATE, TAG_PRICE },
new int[] { R.id.order_id, R.id.order_date, R.id.order_name, R.id.order_price });
// updating listview
setListAdapter(adapter);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new ListClickListener());
}
});
}
}
I think that problem is with using of one thread, so I created one more inner class in my ConnectionActivity like this^
class ListHandler extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute ()
{
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute()
{
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Log.d("Click on the item","!!!!!!!!!!!!!!!!!!!!!");
Toast toast = Toast.makeText(getApplicationContext(),
"Пора покормить кота!", Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
But it doesn't work. I mean that I cannot get the Toast when I clicked on the item , but there's no exception. I tried to handle setonitemclicklistener in void onResume() method of the Activity, but I've got NullPointerException. Also I handled this in OnPreExecute() method of the ListHandler class - same result...
Help please with it...

where is setContentView(R.layout.yourxml) ? i think you forgot it in oncreate Method.
So your listView is null and gives NPE.
AND
onPostExecute method have runonUiThread,Remove it no need it.Its already run in UI Thread.

Problem solved with extending from Activity instead of ListActivity and using setContentView().

Related

Changing image in ListView (with Simple Adapter)

I'm following tutorial from this link to create a listview containing data from database. It consists of a picture (by default - switched off light bulb) and two texts - name (room) and status (on/off) of the database record. At the end of AsyncTask which loads data from database I want to scan through the list and change the picture for every position where status equals "1" to switched on light bulb.
But the image doesn't change. As if the listview wasn't refreshing.
Every help would be appreciated.
public class LightingActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray status = null;
ArrayList<HashMap<String, String>> statusList;
private static String address_getall = "http://192.168.2.112/db_lighting_getall.php";
private static String address_update = "http://192.168.2.112/db_lighting_change.php";
private static final String SID_SUCCESS = "success";
private static final String SID_ARRAY = "Lighting";
private static final String SID_ID = "light_id";
private static final String SID_NAME = "name";
private static final String SID_STATUS = "value";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.lighting_activity);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
statusList = new ArrayList<HashMap<String, String>>();
new LoadData().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ...Listener...
}
});
}
class LoadData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LightingActivity.this);
pDialog.setMessage("Downloading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(address_getall, "GET", params);
try {
int success = json.getInt(SID_SUCCESS);
if (success == 1) {
status = json.getJSONArray(SID_ARRAY);
for (int i = 0; i < status.length(); i++) {
JSONObject data = status.getJSONObject(i);
String light_id = data.getString(SID_ID);
String light_name = data.getString(SID_NAME);
String light_status = data.getString(SID_STATUS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(SID_ID, light_id);
map.put(SID_NAME, light_name);
map.put(SID_STATUS, light_status);
statusList.add(map);
}
} else {
// Error
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
LightingActivity.this, statusList,
R.layout.lighting_list, new String[]{SID_ID, SID_STATUS, SID_NAME},
new int[]{R.id.light_id, R.id.light_status, R.id.light_name});
setListAdapter(adapter);
// I tried doing it like this:
ListView lv = getListView();
for (int i = 0; i < lv.getCount(); i++) {
View v = lv.getAdapter().getView(i, null, null);
TextView light_status = (TextView) v.findViewById(R.id.light_status);
String status = light_status.getText().toString();
if (status.equals("1")) {
// Everything works till here - I checked with Toasts
ImageView img = (ImageView) v.findViewById(R.id.light_icon);
img.setImageResource(R.drawable.light_on);
lv.invalidateViews();
lv.refreshDrawableState();
}
}
}
});
}
}
Please be tolerant, I'm new to java :)
There are so many things wrong in your code that it's beyond saving! I suggest you google about how to load data to a ListView using AsyncTask. There are many examples. With a quick search this looks close to your needs.
http://android-er.blogspot.gr/2010/07/load-listview-in-background-asynctask.html
just a few pointers
1) onPostExecute, onProgressUpdate and onPreExceute of AsyncTask are executed
in the UI thread so the runOnUiThread(new Runnable() {}) is not necessary.
Only the doInBackground method is executed in another thread;
2) Put all the logic about what each rows shows like inside the getView method
of the adapter.
3) To update the views of a listView you change the data in the ArrayList and then
call notifyDataSetChanged() on the ListView 's adapter. This causes all of the views
to be re-drawn. And because all the logic is in the getView method your views
are showing what the data contains.

How to Show JSON DATA in LISTVIEW

I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.

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

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = 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
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} 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(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

Pull to refresh example, Eclipse don't find setOnRefreshListener command

iam dealing with well known pull to refresh example from Git-hub
I loaded library and everything is working as it should but when i want to call method setOnRereshListener, Eclipse don't find it. What could be a problem?
This is code from example:
PullToRefreshListView pullToRefreshView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
And this is my code:
public class MainActivity extends Activity {
private static final String URL = "http://192.168.1.103/php-android/testphp.php";
private static final String TAG_DATA = "data";
private static final String TAG_ID = "name";
private static final String TAG_DATE = "date";
public PullToRefreshListView listView;
JSONArray data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
getDataInArray();
PullToRefreshListView pullToRefreshView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
}
Not sure, but I believe that is due to the method signature OnRefresh (PullToRefreshBase refreshView), try removing PullToRefreshBase refreshView, like this:
pullToRefreshView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
I use this same structure without signing method OnRefresh () and it works normally.
Here is the code for those who will face with the same problem as i did.Thanks to Taynã Bonaldo i made it through problems.
public class MainActivity extends ListActivity {
private static final String URL = "http://192.168.1.103/php-android/testphp.php";
private static final String TAG_DATA = "data";
private static final String TAG_ID = "name";
private static final String TAG_DATE = "date";
public PullToRefreshListView listView;
public JSONArray data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
listView = (PullToRefreshListView) getListView();
listView.scrollTo(0, 60);
// Set a listener to be invoked when the list should be refreshed.
((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
GetArrayData();
}
private void GetArrayData() {
// TODO Auto-generated method stub// Hashmap for listView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
// creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array data
data = json.getJSONArray(TAG_DATA);
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each jason item in variable
String name = c.getString(TAG_ID);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// Adding each child node to HASMap key => value
map.put(TAG_ID, name);
map.put(TAG_DATE, date);
// adding HashList to Array list
dataList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
// Updating parsed JASON data in to ListView
ListAdapter adapter = new SimpleAdapter(this, dataList, R.layout.list_item,
new String[]{TAG_ID, TAG_DATE}, new int[]{
R.id.name, R.id.date});
// Set view to listView
listView.setAdapter(adapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]>{
#Override
protected String[] doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
;
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
//
listView.scrollTo(0,0);
GetArrayData();
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) getListView()).onRefreshComplete();
super.onPostExecute(result);
}
}
}

Categories

Resources