I have had a good look at CWAC Endless adapter and a couple of others that do the same thing, but I cannot work out how to apply them to my current method of retrieving data, which populates 2 rows and a listview. Currently the data is retrieved via httpget in an ASync background task. The url is altered slightly to get each subsequent page (page=1.html, page=2.html etc).
I would like page 2 to load and append to the end of page 1 when the end is reached - I guess it is possible using CWACs method but I cannot work out how. Below is my code, help much appreciated.
My current system works absolutely fine for displaying a single page - but I would like the endless list loading.
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
{progressDialog = ProgressDialog.show(TwitterPage.this,
"", "Loading. Please wait...", true);}
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences myPrefs = getPreferences(MODE_PRIVATE);
try {
String twitPlayers = getString(R.string.twit_players);
String twitClub = getString(R.string.twit_club);
String twitAndr = getString(R.string.twit_andr);
String twitMentions = getString(R.string.twit_mentions);
HttpClient hc;
HttpGet get;
HttpResponse rp;
if (myPrefs.getInt("FILTER_INT", 1) == 1){
hc = new DefaultHttpClient();
get = new
//All
HttpGet("http://search.twitter.com/search.json?q=" + twitMentions + "+OR+" + twitAndr + "+OR+from" + twitPlayers + "+OR+from" + twitClub + "&result_type=recent&rpp=15&page="+currentpage);
rp = hc.execute(get);}
else if (myPrefs.getInt("FILTER_INT", 1) == 2){
hc = new DefaultHttpClient();
get = new
........LOADS MORE IF STATEMENTS REMOVED AS NOT RELEVANT............
rp = hc.execute(get);}
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.content = session.getString("text");
tweet.author = session.getString("from_user");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
{ progressDialog.dismiss();}
//setadapter
setListAdapter(new TweetListAdaptor(
TwitterPage.this, R.layout.list_item, tweets));
}
}
private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context,
int textViewResourceId,
ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.author);
return v;
}
}
Related
Hi I'm trying to retrieve public tweets from twitter but it seems like there is no explanation for it. I have the below code but it's not working. Any idea if this is an outdated code and if you have any sample examples that I could have a look at would be much appreciated.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Loading. Please wait...", true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new
HttpGet("http://search.twitter.com/search.json?q=android");
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.content = session.getString("text");
tweet.author = session.getString("from_user");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new TweetListAdaptor(
MainActivity.this, R.layout.list_item, tweets));
}
}
private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context,
int textViewResourceId,
ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.author);
return v;
}
}
}
If you visit http://search.twitter.com/search.json?q=android in a Web browser, you will see:
{"errors":[{"message":"The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.","code":64}]}
Any idea if this is an outdated code
Yes, it is, as the above error message indicates.
You can read the Twitter REST API documentation, such as the documentation on their search API.
hi i am developing one android app,where i am showing comment releated to that ticket.but on server side database all comment are stored in html format.when i send request for it i get all html code.But i managed to convert HTML code in proper format by using
comm.setText(Html.fromHtml(cmnt[position]));
But the problem is that if there is image tag in comment then it will show small box instead of image.i want to display that image proprely.
please help me
Single_Ticket.java
private class showcomment extends AsyncTask<String,String,String>
{
ProgressDialog pdialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("TAG", "In onPreExecute of the loading comnt.");
}
protected String doInBackground(String... args) {
Log.v("TAG", "In doInBackground of the loading comment. ");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("tktid", id));
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(URL_COMMENT, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try {
contacts = new JSONArray(jsonStr);
int a=contacts.length();
Log.v(TAG, ".................." + a);
if(a > 0 ) {
cmnt = new String[contacts.length()];
cmnt_time = new String[contacts.length()];
cmnt_by = new String[contacts.length()];
for (int i = (a-1),j=0; i >= 0&& j < contacts.length(); i--,j++) {
JSONObject c = contacts.getJSONObject(j);
Log.v(TAG, "" + i);
String aa = c.getString("cmnt");
String bb = c.getString("cmnt_time");
String cc = c.getString("cmnt_by");
Log.v(TAG,""+aa);
cmnt[i] = aa;
cmnt_time[i]=bb;
cmnt_by[i]=cc;
Log.v(TAG,""+cmnt[i]);
}
}
} catch (JSONException e) {
System.out.print("hiiiiiiiiiiii" );
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(cmnt!=null && cmnt.length > 0 ) {
C_adapter adapter = new C_adapter(Single_Ticket.this, cmnt,cmnt_by,cmnt_time);
cmntview.setAdapter(adapter);
}
}
}
C_adapter.java
public class C_adapter extends ArrayAdapter {
Context context;
String[] cmnt;
String[] cmnt_by;
String[] cmnt_time;
LayoutInflater inflater;
public C_adapter(Single_Ticket context, String[] cmnt,String[] cmnt_by,String[] cmnt_time) {
super(context, R.id.cmnt_list,cmnt);
this.context=context;
this.cmnt=cmnt;
this.cmnt_by=cmnt_by;
this.cmnt_time=cmnt_time;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cmnt_list, null);
}
TextView comm = (TextView) convertView.findViewById(R.id.cmnt);
TextView cmntby = (TextView) convertView.findViewById(R.id.cmntby);
comm.setText(Html.fromHtml(cmnt[position]));
if(cmnt_by[position].equalsIgnoreCase("Lalit Patil")|| cmnt_by[position].equalsIgnoreCase("Sarvesh Sonawane"))
{
//cmntby.setBackgroundResource(R.color.orange_red);
cmntby.setText(cmnt_time[position]+" - "+cmnt_by[position]);
}
cmntby.setText(cmnt_time[position]+" - "+cmnt_by[position]);
return convertView;
}
}
I got response from server like this
{"cmnt":"<img src=\"http:\/\/i.imgur.com\/JHcdBVj.jpg\" width=\"448\"><br>","cmnt_time":"Wed,07 Oct 2015 05:41pm","cmnt_by":"test test"}
Place ImageView and TextView on the same position in your layout.xml file.
Then check the content of your data which you get from server and if the data have img tag then set visible to image view and set the Bitmap to image view otherwise set visible to text view.
I have made a function for you. I am using Picasso to set the image in image view, using Picasso we can set image in image view with just 1 line.
public void setImage() {
try {
String response = "{\"cmnt\":\"<img src=\\\"http:\\/\\/i.imgur.com\\/JHcdBVj.jpg\\\" width=\\\"448\\\"><br>\",\"cmnt_time\":\"Wed,07 Oct 2015 05:41pm\",\"cmnt_by\":\"test test\"}";
JSONObject jsonresponse = new JSONObject(response);
String cmnt = jsonresponse.getString("cmnt");
if (cmnt.contains("<img")) {
textView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
Matcher m = p.matcher(cmnt);
if (m.find()) {
cmnt = m.group(1);
}
Picasso.with(this)
.load(cmnt)
.into(imageView);
} else {
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I Know this Question has been asked many many times before but mine problem is bit different.
I am working on a project in which I am getting JSON data from Webservice. In this app We can vote to different type of food items and list view will sort according the votes (Max Votes to Min Votes). On Vote Click on any list item the listview refresh and show the new sorted items list.
The JSON I am getting also provide me the index position of the item I vote in latest sort.
so Now I am getting the position of the voted item and I want to scroll it to that specific position after listview reload. I tried all methods provide over the internet but its not working for me.
Please Any Help Here is My code.
Here is My RemoteDataTask Async Class Code
public class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(ItemRankActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading All Awesomeness of " + title);
// Set progressdialog message
mProgressDialog
.setMessage("Wait.. While we Generating the Best Dishes for you.");
// Show progressdialog
mProgressDialog.show();
}
protected Void doInBackground(Void... params) {
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
DishesArray = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < DishesArray.length(); i++) {
JSONObject c = DishesArray.getJSONObject(i);
arrayList.add(new ItemRankData(c.getString(TAG_PIC), c
.getString(TAG_TITLE), c
.getString(TAG_RESTAURANT), c
.getString(TAG_VOTES), c.getString(TAG_DISHID),
c.getString(TAG_FBID),
c.getString(TAG_IsVOTED), c
.getString(TAG_IsTOP), c
.getString(TAG_TopImage), c
.getString(TAG_Position)));
if (c.getString(TAG_IsTOP).equalsIgnoreCase("yes")) {
isTop = "yes";
Log.e("Is it on TOP", isTop);
if (c.getString(TAG_TopImage) != "") {
TopImageURL = c.getString(TAG_TopImage);
Log.e("Top image URL", TopImageURL);
VotedPosition = c.getString("position");
}
}
}
} 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) {
Log.v("post", "After query post");
Picasso.with(mContext).load(TopImageURL).into(img_item_image);
PositionOfVote = Integer.parseInt(VotedPosition);
lv_items_lists.smoothScrollToPosition(PositionOfVote);
adapter.notifyDataSetChanged();
ClassDataManager.setListViewHeightBasedOnChildren(lv_items_lists);
Log.e("POST Execute Hit", "True");
mProgressDialog.dismiss();
}
}
My Custom Adapter Class Code
public class ItemRankAdapter extends BaseAdapter {
String URL;
JSONArray BestCatogryArray = null;
private LayoutInflater inflater = null;
private ArrayList<ItemRankData> mlist;
private Context context;
ProgressDialog mProgressDialog;
private static String TAG_DATA = "data";
private static String TAG_VOTES = "votes";
JSONArray DishesArray = null;
String VOTES;
ViewHolder holder;
VOTING voting = new VOTING();
int POS;
public ItemRankAdapter(Context c, ArrayList<ItemRankData> mlist) {
this.context = c;
this.mlist = mlist;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("DefaultLocale")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageLoader imageLoader;
imageLoader = ImageLoader.getInstance();
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_item_rank, parent,
false);
holder = new ViewHolder();
holder.tv_item_serialNo = (TextView) convertView
.findViewById(R.id.tv_item_serialNo);
holder.tv_item_name = (TextView) convertView
.findViewById(R.id.tv_item_name);
holder.tv_item_restaurant = (TextView) convertView
.findViewById(R.id.tv_item_restaurant);
holder.tv_item_like_count = (TextView) convertView
.findViewById(R.id.tv_item_like_count);
holder.img_logo = (ImageView) convertView
.findViewById(R.id.img_logo);
holder.img_top_position = (ImageView) convertView
.findViewById(R.id.img_top_position);
holder.ll_likes = (LinearLayout) convertView
.findViewById(R.id.ll_likes);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ItemRankData rankData = mlist.get(position);
holder.tv_item_name.setText(rankData.itemName);
holder.tv_item_restaurant.setText(rankData.itemRestaurantName);
holder.tv_item_like_count.setText(rankData.itemLikes);
Log.e("Position Value is " + position,
" And The Name of Item Along with it is " + rankData.itemName);
String imageUrl = rankData.itemRetaurantLogo;
// imageLoader.displayImage(imageUrl, holder.img_logo);
Picasso.with(context).load(imageUrl).into(holder.img_logo);
if (position == 0) {
holder.tv_item_serialNo.setVisibility(View.GONE);
holder.img_top_position.setVisibility(View.VISIBLE);
} else {
holder.tv_item_serialNo.setVisibility(View.VISIBLE);
holder.img_top_position.setVisibility(View.GONE);
String s1 = String.format("%02d", (position + 1));
holder.tv_item_serialNo.setText(s1);
}
if (rankData.isVoted.equalsIgnoreCase("yes")) {
holder.ll_likes
.setBackgroundResource(R.drawable.top_selected_border);
holder.tv_item_like_count.setTextColor(context.getResources()
.getColor(R.color.text_selected));
} else {
holder.ll_likes.setBackgroundResource(R.drawable.normal_border);
holder.tv_item_like_count.setTextColor(context.getResources()
.getColor(R.color.text_normal));
}
holder.ll_likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String dishId = rankData.dishId;
URL = "http://Here I Write My URL?"
+ "dishid="
+ dishId
+ "&"
+ "fbid="
+ PrefrencesClass.getStringPreference(context,
Constants.APPSPREF, Constants.USER_ID);
new DataTask().execute();
((ItemRankActivity) context).UpdateRemoteDataRankActivity();
}
});
return convertView;
}
static class ViewHolder {
TextView tv_item_serialNo;
TextView tv_item_name;
TextView tv_item_restaurant;
TextView tv_item_like_count;
ImageView img_logo;
LinearLayout ll_add;
ImageView img_top_position;
LinearLayout ll_likes;
ImageView img_item_image;
}
//The Class to Send VOTE update URL to Server
private class DataTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
return null;
}
}}
Please Help me With it I am trying really hard from how and where can I solve this problem
Any Help will be Great :)
lv_items_lists.setSelection(PositionOfVote);
try this after
adapter.notifyDataSetChanged();
I hope it will help you
Try this.
lv_items_lists.setSelection(PositionOfVote);
instead of
lv_items_lists.smoothScrollToPosition(PositionOfVote);
I hope it helps!
I need to delete a list item from listview on clicking a delete button in android eclipse. The list values are populated from mysql database(JSON), so on deleting, I need to delete the same from database also.
Here is my main Activity; I need to delete a listitem from a listview on clicking a delete button on each item in the listview:
public class MainActivity extends Activity implements AsyncResponse2 {
private ProgressDialog dialog;
ListView l1;
//for getting count
TextView count;
private static final String TAG_COUNT = "cnt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //to hide title bar
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.deleteid);
initView();
//str for getting count
count=(TextView)findViewById(R.id.countid);
//to display count while loading(so outside buttonclick)
String key1 = "saasvaap123";
String signupid1 = "8";
String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
//http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?key=saasvaap123&signup_id=8
//put the below lines outside button onclick since we load the values into edittext when opening the app
CustomHttpClient2 task2 = new CustomHttpClient2();
task2.execute(url2,key1,signupid1);
task2.delegate = MainActivity.this;
//end
}
//str getting count
//str customhttp2
private class CustomHttpClient2 extends AsyncTask<String, String, String>{
public AsyncResponse2 delegate=null;
private String msg;
#Override
protected void onPostExecute(String result2) {
// TODO Auto-generated method stub
super.onPostExecute(result2);
delegate.processFinish2(result2);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url2 = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url2);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
public void processFinish2 (String output2){
Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show();
try{
//str
JSONObject jsonResponse = new JSONObject(output2);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
// create apps list
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
//end
//str
String strCount = json.getString(TAG_COUNT);
count.setText(strCount);//setting name to original name text
//end
}
}catch (JSONException e) {
Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show();
}
}
//end getting count
private void initView() {
// show progress dialog
// dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String signup_id="8";
String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
FetchDataTask task = new FetchDataTask();
task.execute(url,key,signup_id);
}
public class FetchDataTask extends AsyncTask<String, Void, String>{
// private final FetchDataListener listener;
private String msg;
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
//str
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
//end
//
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject jsonResponse = new JSONObject(sJson);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
Toast.makeText(MainActivity.this, aJson.toString(),Toast.LENGTH_SHORT).show();
// create apps list
List<SavedOffers> apps = new ArrayList<SavedOffers>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
SavedOffers app = new SavedOffers();
app.setTitle(json.getString("title"));
app.setOriginalRate(json.getString("price"));
app.setOfferRate(json.getString("off_price"));
app.setPercentage(json.getString("percent"));
app.setSavings(json.getString("savings"));
app.setUrl(json.getString("image"));
// add the app to apps list
apps.add(app);
}
SavedOffersAdapter adapter = new SavedOffersAdapter(MainActivity.this, apps);
// set the adapter to list
l1.setAdapter(adapter);
//for delete
// adapter.notifyDataSetChanged();
/** Defining a click event listener for the button "Delete" */
Button btnDel = (Button) findViewById(R.id.deleteid);
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = l1.getCheckedItemPositions();
int itemCount = l1.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(l1.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
l1.setAdapter(adapter); //end delete
//notify the activity that fetch data has been complete
// if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
// msg = "Invalid response";
// if(listener != null) listener.onFetchFailure(msg);
// return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
}
// this is my adapter class , I think change is only needed in main activity
// , I need to delete a specific list item from listview on clicking the delete button
public class SavedOffersAdapter extends ArrayAdapter<SavedOffers>{
private List<SavedOffers> items;
Bitmap bitmap;
ImageView image;
public SavedOffersAdapter(Context context, List<SavedOffers> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
private class ViewHolder {
//TextView laptopTxt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder holder;//added
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
SavedOffers app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.nameid);
TextView originalRate = (TextView)v.findViewById(R.id.originalid);
originalRate.setPaintFlags(originalRate.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offerRate = (TextView)v.findViewById(R.id.offerid);
TextView percentage = (TextView)v.findViewById(R.id.discountid);
TextView savings = (TextView)v.findViewById(R.id.savingsid);
image =(ImageView)v.findViewById(R.id.prctimgid);
if(productName != null) productName.setText(app.getTitle());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app. getOfferRate());
if(percentage != null) percentage.setText(app. getPercentage());
if(savings != null) savings.setText(app. getSavings());
if(image!=null){
new DownloadImageTask(image).execute(app.getUrl());
}
}
return v;
}
In your listviews adapter's getView method you link to the button on the layout your inflating and just attach a setOnClickListener... to the button and have it remove that item from your list or array that your adapter uses and then notifyDataHasChanged.
Delete that item from items in that position.
So 1. you want to delete the item from the ListView
2. you want to delete the item from the SQL DB.
The first one is very easy, but you kind of need to know the underlining adapter and how it serves data to your ListView. When you instantiate a BaseAdapter for the ListView you pass in a List or an array. This array will be the data your BaseAdapter serves to your ListView, each view in the listview will be showing an element from the array (done in getView()). If you dynamically delete one of those items, then adjust your array (or just use a List and it's .remove(), and finally notifyDataSetChanged(); your BaseAdapter will refresh your list without that View (or rather that View will be replaced with the new one). So for instance below I pass in a List<WeatherLocation> (WeatherLocation is a containing class that has weather stuff for a particular area (city, zipcode, degree"Biddeford", 04005, 72) to my BaseAdapter.
// Instantiate ListView
ListView lvLocations = (ListView) findViewById(R.id.lvLocations);
// Instantiate our BaseAdapter (pass in the List<WeatherLocation>)
WeatherLocationAdapter mWeatherLocationAdapter = new WeatherLocationAdapter(savedList, this, R.layout.view_weather_location);
lvLocations.setAdapter(mWeatherLocationAdapter);
This is an example of a regular ListView setting an Adapter to a custom BaseAdapter.
The BaseAdapter is so simple, that really the only method you care about (majorly) is the getView() method.
R.layout.view_weather_location is just a `LinearLayout` I made, it has 3 TextViews in it that I tie (show) my data with, by attaching data to those TextViews in the `getView()` method of the `BaseAdapter`. You would put a `Button there and tie it to what you want (to delete the data item)`.
public class WeatherLocationAdapter extends BaseAdapter{
private List <WeatherLocation> mLocations;
private Context mContext;
private int rowForLocationToInflate;
private LayoutInflater inflater;
public WeatherLocationAdapter(List<WeatherLocation> mLocations, Context mContext, int rowForLocationToInflate) {
this.mLocations = mLocations;
this.mContext = mContext;
this.rowForLocationToInflate = rowForLocationToInflate;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//TODO just built up layout now must tie to it.
private void addLocation(WeatherLocation newLocation){
mLocations.add(newLocation);
//TODO maybe invalidate after adding new item.
}
#Override
public int getCount() {
return mLocations.size();
}
#Override
public WeatherLocation getItem(int position) {
return mLocations.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO build a viewholder
View rowView = inflater.inflate(rowForLocationToInflate, parent, false);
TextView tvZipcode = (TextView) rowView.findViewById(R.id.tvZipCode);
TextView tvCity = (TextView) rowView.findViewById(R.id.tvCity);
TextView tvTemp = (TextView) rowView.findViewById(R.id.tvDegree);
tvZipcode.setText(mLocations.get(position).getZipcode());
tvCity.setText(mLocations.get(position).getCity());
tvTemp.setText(String.valueOf(mLocations.get(position).getTemperature()));
// If you had a Button in your LinearLayout you were attaching to you that you wanted to delete that view/item with, it would look something like this in my case.
Button bDel = (Button) row.findViewById(R.id.bDel);
bDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLocations.remove(position);
}
});
return rowView;
}
}
In the onClick you would also remove the item from the SQL db. I can show that too, but I feel you have some coding to do as it stands.
I'm reading some records from database and loading them in ListView. The ListView consist CheckBox and TextView. Loading is done over AsyncTask. This part of application works fine.
The next step is automatically checking some checkboxes according to some flags from database and here I get problem. I'm trying to check those items inside onPostExecute() and then I get error about NullPointerException. If I do same from, for example, setOnClickListener() of button widget than it works fine.
The question is how to check if ListView is populated, are checkboxes and TextView loaded and visible on screen?
I don't know if it will help the part of code where program breaks looks like:
for (j=0; j<3; j++)
{
LinearLayout itemLayout = (LinearLayout)listView.getChildAt(j); // Find by under LinearLayout
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.ColChk);
for (k=0; k<rbmjere.size(); k++)
{
if (checkbox.getTag().toString() == rbmjere.get(k).toString())
{
checkbox.setChecked(true);
}
}
}
It breaks on that line:
LinearLayout itemLayout = (LinearLayout)listView.getChildAt(j);
I must mention that this works only if I manually press on button which runs code for automatic checking the boxes and this works only when all data is loaded.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spckontrola_update);
listView = (ListView)findViewById(R.id.listView1);
btnPohrani = (Button)findViewById(R.id.btnPohrani);
btnProvjeri = (Button)findViewById(R.id.btnProvjeri);
btnProvjeri.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new loadSPCKontrole().execute("FCN");
}
});
MyArrList = new ArrayList<HashMap<String, String>>();
public void fillData()
{
SimpleAdapter listadapter = new SimpleAdapter(this, MyArrList, R.layout.activity_list_row,
new String[] {"OpisMjere", "RbMjere"}, new int[] {R.id.ColOpis, R.id.ColCode});
listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(listadapter);
}
private class loadSPCKontrole extends AsyncTask<String, Void, Void>
{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SPCUpdate.this);
pDialog.setMessage("Loading in progress ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
HashMap<String, String> map;
String k = params[0].toString();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sIDKategorija", k));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.16.48" + "/spc/get_spcmjere.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+ e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result " + e.toString());
}
int ct_id;
String ct_name;
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("RbMjere");
ct_name=json_data.getString("OpisMjere");
map = new HashMap<String, String>();
map.put("RbMjere", String.valueOf(ct_id));
map.put("OpisMjere", ct_name);
MyArrList.add(map);
}
}
catch(JSONException e1)
{
Log.e("Greška konvertiranja", e1.toString());
}
catch (ParseException e1)
{
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
fillData();
listView.setAdapter(new SPCMjereAdapter(SPCUpdate.this));
pDialog.dismiss();
}
}
public class SPCMjereAdapter extends BaseAdapter
{
private Context context;
public SPCMjereAdapter(Context c)
{
context = c;
}
public int getCount() {
return MyArrList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_list_row, null);
}
// ColID
TextView txtOpis = (TextView) convertView.findViewById(R.id.ColOpis);
txtOpis.setText(MyArrList.get(position).get("OpisMjere") +".");
// ColCode
TextView txtRbMjere = (TextView) convertView.findViewById(R.id.ColCode);
txtRbMjere.setText(MyArrList.get(position).get("RbMjere"));
// ColChk
CheckBox Chk = (CheckBox) convertView.findViewById(R.id.ColChk);
Chk.setTag(MyArrList.get(position).get("RbMjere"));
return convertView;
}
}
And here is code how I get items that should be checked:
DB objDB = new DB();
ArrayList<Integer> rbmjere = objDB.getCheckedSPC(ID);
int k=0;
int j=0;
for (j=0; j<MyArrList.size(); j++)
{
LinearLayout itemLayout = (LinearLayout)listView.getChildAt(j); // Find by under LinearLayout
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.ColChk);
for (k=0; k<rbmjere.size(); k++)
{
if (checkbox.getTag().toString() == rbmjere.get(k).toString())
{
checkbox.setChecked(true);
}
}
}
This code above works only when listview is populated with items and if this code is under OnClickListener() but it doesn't work if I run it from onPostExecute because it seems that all rows in listview are not loaded. So my question is what should I do to get information when is loading of all rows finished and after that check which items should be checked according to data that i get from database?
Because of view recycling, listView.getChildAt() will only return a view for the positions it is displaying, not severals.
you can check this other question here. it has the answer you are looking for:
ListView getChildAt returning null for visible children
In your case I think that piece of code should be inside your adapter's getView implementation.
Here you go with examples on
SimpleCursorAdapters
CustomCursorAdapters
And how to use them with your List.
First of all you know when the list is loaded by reading the number of items in your data set and if the listview's data set is equal to that, then all the data is loaded on the listview.. unfortunately I can't help you more with this as I can't see your data load code here..
Second, you should change:
for (j=0; j<3; j++)
with
int listChildSize = listView.getChildCount();
for (j = 0; j < listChildSize ; j++)
EDIT
jfs is right, you should add:
if (checkbox.getTag().toString() == rbmjere.get(k).toString())
{
checkbox.setChecked(true);
}
In a custom Adapter.
Here is a sample of custom adapter and also ViewHolder pattern.