Changing image in ListView (with Simple Adapter) - android

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.

Related

android auto-refresh listview items

I'm really new to android programming, I successfully get data from server and then populated into a listview. But how do I auto-refresh the listview items within certain amount of time? There maybe new items coming in from the server when I refresh the new items may appear.
Here's my code of retrieving data from server:
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
String numberr = oslist.get(position).get("phonenumber");
Intent intent = new Intent(getActivity(), ThreeButton.class);
intent.putExtra("key", numberr);
startActivity(intent);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i would recommend you to use handler for refreshing data. i.e
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
this handler refresh data for every minute.
To prevent the adding the same data in list view you should use following things :
Please paste following code inside the onPost() method of the AsyncTask before for loop :
if(oslist!=null && oslist.size()>0)
oslist.clear();

ListView works in emulator, but not in phone

I tried to make a simple application that will take the API from the internet, rearrange them and show as list.
In the emulator it works. The phone shows a white screen. The phone has Android 2.3.7. But when I tried it on the tablet, the app stopped working. The tablet has Android 4.1.
MainActivity
public class MainActivity extends ListActivity implements OnItemClickListener{
private ProgressDialog pDialog;
private String url = "http://www.cscpro.org/secura/market/"; //food-29-5.json;
private String res;
private String ql;
JSONArray market;
final static String RESOURCES = "res";
final static String QUALITY = "q";
private static final String TAG_OFFER = "offer";
private static final String TAG_PRICE = "price";
private static final String TAG_SALLER = "seller";
private static final String TAG_SALLER_NAME = "name";
ArrayList<HashMap<String, String>> listSaller;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listSaller = new ArrayList<HashMap<String, String>>();
Intent in = getIntent();
res = in.getStringExtra(RESOURCES);
ql = in.getStringExtra(QUALITY);
ListView lv = getListView();
lv.setOnItemClickListener(this);
// Calling async task to get json
new GetContacts().execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String rate = ((TextView) view.findViewById(R.id.rate)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_PRICE, rate);
in.putExtra(TAG_SALLER_NAME, name);
startActivity(in);
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#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 Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String myURL = url+res+"-29-"+ql+".json";
String jsonStr = sh.makeServiceCall(myURL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
market = jsonObj.getJSONArray(TAG_OFFER);
// looping through All Contacts
for (int i = 0; i < market.length(); i++) {
JSONObject c = market.getJSONObject(i);
String rate = c.getString(TAG_PRICE);
// Phone node is JSON Object
JSONObject saller = c.getJSONObject(TAG_SALLER);
String name = saller.getString(TAG_SALLER_NAME);
// tmp hashmap for single contact
HashMap<String, String> sallers = new HashMap<String, String>();
// adding each child node to HashMap key => value
sallers.put(TAG_PRICE, rate);
sallers.put(TAG_SALLER_NAME, name);
// adding contact to contact list
listSaller.add(sallers);
}
} 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(
MainActivity.this, listSaller,
R.layout.list_item, new String[] { TAG_PRICE, TAG_SALLER_NAME}, new int[] { R.id.rate,
R.id.name});
setListAdapter(adapter);
}
}
}
SingleContactActivity
public class SingleContactActivity extends Activity {
// JSON node keys
private static final String TAG_PRICE = "price";
private static final String TAG_SALLER_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String rate = in.getStringExtra(TAG_PRICE);
String name = in.getStringExtra(TAG_SALLER_NAME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblRate = (TextView) findViewById(R.id.rate_label);
lblName.setText(name);
lblRate.setText(rate);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_single_contact.xml is a simple LinearLayout with two TextViews.

Adding a image from url to a ListView

I am using a modified version of the contacts project from AndroidHive.
It basically just pulls n list of articles and their contact from a Joomla Site.
I am using a Image Plugin that gets a image from a url. i can successfully use it on the article detail activity view but i don't know how to add it to each List Item on the MainAcitivity file. I am new to Android development so please excuse the confusion.
The script to add the image is:
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
and my MainActivity which generated the ListView:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get articles JSON
private static String url = "http://192.168.12.21/sebastian/broadcast/index.php/blog?format=json";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
// Get the fields
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_SHORTTEXT = "shorttext";
private static final String TAG_FULLTEXT = "fulltext";
private static final String TAG_IMAGE = "image";
private static final String TAG_DATE = "date";
// articles JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> articleList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articleList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String shorttext = ((TextView) view.findViewById(R.id.shorttext)).getText().toString();
String fulltext = ((TextView) view.findViewById(R.id.fulltext)).getText().toString();
String image = ((TextView) view.findViewById(R.id.image)).getText().toString();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
// Starting single article activity
Intent in = new Intent(getApplicationContext(),
SingleArticleActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_SHORTTEXT, shorttext);
in.putExtra(TAG_FULLTEXT, fulltext);
in.putExtra(TAG_IMAGE, image);
in.putExtra(TAG_DATE, date);
startActivity(in);
}
});
// Calling async task to get json
new GetArticles().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetArticles extends AsyncTask<Void, Void, Void> {
#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 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
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All articles
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String shorttext = c.getString(TAG_SHORTTEXT);
String fulltext = c.getString(TAG_FULLTEXT);
String image = c.getString(TAG_IMAGE);
String date = c.getString(TAG_DATE);
// tmp hashmap for single article
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_SHORTTEXT, shorttext);
article.put(TAG_FULLTEXT, fulltext);
article.put(TAG_IMAGE, image);
article.put(TAG_DATE, date);
// adding article to article list
articleList.add(article);
}
} 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(
MainActivity.this, articleList,
R.layout.list_item, new String[] {
TAG_TITLE,
TAG_SHORTTEXT,
TAG_FULLTEXT,
TAG_IMAGE,
TAG_DATE
},
new int[] {
R.id.title,
R.id.shorttext,
R.id.fulltext,
R.id.image,
R.id.date
});
setListAdapter(adapter);
}
}
}
**I don't know where in the MainActivity file do i add the script to add an image to each List Item.
I already got it working on the SingleArticleActivity but cannot get it to work on the List of Items**
Thanks for the help
UPDATE
What im trying to do:
foreach(ListItem in the List) {
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
}
You have to just use this one..
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
CustomAdapter cdp = new CustomAdapter(YourActivityName.this , articleList);
setListAdapter(adapter);
Now make class of CustomAdapter extends with BaseAdapter
public class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> list;
Context ctx;
public CustomAdapter(Context c , ArrayList<HashMap<String, String>> articleList){
this.ctx = c;
this.list = articleList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.list_item,
parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
return view;
}
class ViewHolder {
ImageView imageView;
}
}
I am using this method in the getView method of my ListView adapter which returns a drawable which I later set it to my ImageView.
public Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return default_image;
}
}
Hope this helps.
Try this A powerful image downloading and caching library for Android Picasso
Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application-often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

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);
}
}
}

Setonitemclicklistener with AsyncTask gives NullPointerException

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().

Categories

Resources