getItem(position) Android issue - java

I created a custom adapter for a ListView with a CheckBox in each row. Each time I check a Checkbox, I want to trigger an action on the selected item in my ListView, but the getItem(position) always return the last item in the ListView.
Set the adapter:
public void onPostExecuteSearchRequestedCars(JSONArray array){
List<JSONObject> list = new ArrayList<>(array.length());
try {
for(int i = 0 ; i < array.length() ; i++){
JSONObject temp = array.getJSONObject(i);
list.add(temp);
}
} catch (JSONException e) {
Log.e(e.getClass().getName(),"There is no JSONObject in the JSONArray", e);
}
// Create and set the custom listView.
adapter = new CustomSpecificCar(this, list, this);
lv = (ListView) findViewById(R.id.lvCars);
lv.setAdapter(adapter);
}
Custom Adapter:
public class CustomSpecificCar extends ArrayAdapter<JSONObject>{
ListSpecificCars caller;
private JSONObject currentJson;
private CheckBox cbSelectedCar;
private List<JSONObject> list;
public CustomSpecificCar(Context ctxt, List<JSONObject> list, ListSpecificCars caller){
super(ctxt, R.layout.custom_specific_car_row, list);
this.caller = caller;
this.list = list;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final View customView = inflater.inflate(R.layout.custom_specific_car_row, parent, false);
// Set the reference of the layout
currentJson = caller.getItem(position);
cbSelectedCar = (CheckBox)customView.findViewById(R.id.cbSelectedCar);
TextView tvBrand = (TextView)customView.findViewById(R.id.tvBrand);
TextView tvModel = (TextView)customView.findViewById(R.id.tvModel);
TextView tvOwnerEditable = (TextView)customView.findViewById(R.id.tvOwnerEditable);
TextView tvPriceEditable = (TextView)customView.findViewById(R.id.tvEstimatedPriceEditable);
try {
tvBrand.setText(currentJson.getString("brand"));
tvModel.setText(currentJson.getString("model"));
tvOwnerEditable.setText(currentJson.getString("owner"));
} catch (JSONException e) {
Log.e(e.getClass().getName(), "JSONException", e);
}
cbSelectedCar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
caller.updateClickedUsername(currentJson, true); // Add to the List
try {
Log.d("Has been checked ", currentJson.getString("brand"));
} catch (JSONException e) {
e.printStackTrace();
}
}
else
caller.updateClickedUsername(currentJson, false); // Delete from the List
}
});
return customView;
}
#Override
public int getCount() {
return list.size();
}
}
EDIT
I added a getItem in my caller class:
public JSONObject getItem(int position){
return list.get(position);
}
I suspect the error is this one: I call getView() each time a JSONObject is added to the list and set the value of this object in the global variables. (private JSONObject currentJson).
Can you put me on the right way?
EDIT 2
Finally achieved it, by using each and every time getItem(position) instead of currentJson.

Please try using
caller.getItem(position)
and override getCount.
#Override
public int getCount() {
return (caller== null) ? 0 : caller.size();
}

Related

How do I replace a String[ ] with a ArrayList?

I'm trying to populate my gridview with images using picasso. I'm using jsoup to collect the image links and placing them into a ArrayList. I have something wrong with my ImageAdapter cause none of my images load when I start the app. My log shows the links being collected so that works. Any help will be appreciated. I'm posting the entire code for the Activity.
public class MainActivity extends Activity
{GridView grid;
String url="http://dstreet.site/";
String link,title,src;
ArrayList list= new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Scrapper();
grid = (GridView)findViewById(R.id.grid);
grid.setAdapter(new ImageAdapter(this, list));
}
public class ImageAdapter extends BaseAdapter {
ArrayList list;
private LayoutInflater inflater;
Context c;
int mCount;
ImageAdapter(Context context, ArrayList list) {
inflater = LayoutInflater.from(context);
c = context;
mCount = list.size();
this.list=list;
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(int position) {
return true;
}
#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 = inflater.inflate(R.layout.img, parent,
false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView)
view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Picasso.get()
.load(list.get(position))
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.fit()
.into(holder.imageView, new Callback() {
#Override
public void onError(Exception p1)
{holder.imageView.setVisibility(View.INVISIBLE);
// TODO: Implement this method
}
#Override
public void onSuccess() {
holder.imageView.setVisibility(View.VISIBLE);
}
});
return view;
}
}
static class ViewHolder {
ImageView imageView;
}
public void Scrapper()
{
Content content= new Content();
content.execute();
}
public class Content extends
AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void[] p1)
{
// TODO: Implement this method
try
{
Document doc = Jsoup.connect(url).get();
// Identify Table Class "worldpopulation"
for (Element table :
doc.select("div[class=poster]")) {
Elements imgSrc =
table.select("img[src]");
// Get only src from img src
src = imgSrc.attr("src");
list.add(src);
}
Log.d("image links",list.toString());
}
catch (IOException e)
{e.printStackTrace();
}
return null;
}
}}
If you want to replace String[] with ArrayList then you need to use ArrayList.get(position) instead of IMAGE_URLS [position].
It looks like you're not iterating over the elements after you queried the table for images:
for (Element table : doc.select("div[class=poster]")) {
Elements imgSrc = table.select("img[src]");
src = imgSrc.attr("src");
list.add(src);
}
Something like this should do it:
doc.select("div[class=poster]") // get list of div
.stream() // for each div
.map(table -> table.select("img[src]")) // find all images
.flatmap(Elements::stream) // collapse images into 1 list
.map(imgSrc -> imgSrc.attr("src")) // for each image
.forEach(list::add); // add to Collection

How do I stop SimpleDateFormat from updating the time

I saw that this was asked once at How to get current timestamp in Android without it updating like a clock, but it wasn't marked as answered and I don't understand the few suggestions that were given.
Anyway, I'm beyond new to Java and was following a tutorial on making a simple todo app (https://guides.codepath.com/android/Basic-Todo-App-Tutorial) and I decided to try to add a timestamp to each list item. I got as far as that it adds the current time, but its not static. The time keeps updating anytime I try and add a new item or if I close and reopen the app. I can't figure out/find the answer anywhere.
This is what I'm getting:
This is what I want:
Here's the code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> TodoAdapter;
private ListView lvItems;
private void readItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new ArrayList<String>();
readItems();
TodoAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, android.R.id.text1, items);
lvItems = (ListView) findViewById(R.id.lvItems);
lvItems.setAdapter(TodoAdapter);
// Setup remove listener method call
setupListViewListener();
}
// Attaches a long click listener to the listview
// Removes item on long press
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
TodoAdapter.notifyDataSetChanged();
writeItems();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void onAddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
TodoAdapter.add(itemText); // Add items to new Adapter type
etNewItem.setText("");
writeItems();
}
}
TodoAdapter.java
public class TodoAdapter extends ArrayAdapter<Todo> {
public TodoAdapter(Context context, ArrayList<Todo> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Todo item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
}
TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
text1.setText(item.itemText);
text2.setText(item.getCreationTimeString());
text2.setTextSize(10);
return convertView;
}
}
Todo.java
public class Todo {
String itemText;
private Date creationTime;
public Todo(String text) {
this.itemText = text;
this.creationTime = new Date();
}
public String getCreationTimeString() {
return new SimpleDateFormat("h:mm a").format(creationTime);
}
}
Any help provided would be extremely appreciated. Also please keep in mind that I have literally almost no understanding of what I'm doing. :)
The time keeps updating anytime I try and add a new item
Right, that is because the Adapter is recalling new Date(), which will always get the current time that the View is created for an Adapter item.
It would appear that you want items to be associated with a time at which they are created. If that is the case, then you can make a class
public class Todo {
String itemText;
private Date creationTime;
public Todo(String text) {
this.itemText = text;
this.creationTime = new Date();
}
public String getCreationTimeString() {
return new SimpleDateFormat("h:mm a").format(creationTime);
}
}
Then, you should probably make an ArrayAdapter<Todo> to display these items and display something like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Todo item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
}
TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
text1.setText(item.itemText);
text2.setText(item.getCreationTimeString());
text2.setTextSize(10);
return convertView;
}
And update the add method
public void onAddItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
itemsAdapter.add(new Todo(itemText)); // Add items to new Adapter type
etNewItem.setText("");
writeItems();
}

How to show chats by collecting messages in the custom list view adapter itself?

So, What I want to do is display chats in my activity using a custom list view adapter.
I have a HTTPTask Activity handling the server side interaction and responding with a JSONObject. So, every server side interaction is working fine.
What I want to do is keep updating the messages in the chat by keep checking with the API at a set interval to populate messages in the chat if there are any.
My question is, should this population process done in the adapter or the activity and how?
And, how does viewHolder help in the adapter?
This is my Activity
public class ChatActivity extends Activity {
TextView toUsername;
EditText replyText;
JSONObject resultObject;
StringBuilder reply,from_user_id,c_id;
MessageListViewAdapter myAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
toUsername = (TextView) findViewById(R.id.toUsername);
replyText = (EditText) findViewById(R.id.replyText);
reply = new StringBuilder("");
listView = (ListView) findViewById(R.id.messages);
}
#Override
public void onResume(){
super.onResume();
Bundle bundle = getIntent().getExtras();
if(bundle != null){
toUsername.setText("" + bundle.get("ToUsername").toString());
c_id = new StringBuilder(bundle.get("c_id").toString());
from_user_id = new StringBuilder(bundle.get("FromUserId").toString());
}
myAdapter = new MessageListViewAdapter(getBaseContext(),c_id.toString(),from_user_id.toString());
listView.setAdapter(myAdapter);
}
public void sendTextMsg(View view){
reply.delete(0,reply.length());
reply.append(replyText.getText().toString());
if(!reply.toString().equals("")){
Log.d("Values: ","c_id: " + c_id.toString() + " FromUserId: " + from_user_id.toString() + "ReplyText: " + reply.toString());
try{
resultObject = new HttpTask(getBaseContext()).doInBackground("replyInChat",c_id.toString(),replyText.getText().toString(),from_user_id.toString());
if(resultObject.get("status").toString().equals("true")) {
Toast.makeText(getBaseContext(), "Sent.", Toast.LENGTH_SHORT).show();
replyText.setText("");
}
else {
Toast.makeText(getBaseContext(), "Try Again.", Toast.LENGTH_SHORT).show();
}
}
catch(JSONException e){ }
}
}
}
My Adapter doesn't seem to work.
public class MessageListViewAdapter extends BaseAdapter implements ListAdapter{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
private StringBuilder conversation_id, user_id;
private static int cr_id;
private JSONArray messages;
private JSONObject resultObject;
private ViewHolder viewHolder;
private View rowView;
public MessageListViewAdapter(Context context, String conversation_id, String user_id) {
this.context = context;
this.conversation_id = new StringBuilder(conversation_id.toString());
this.user_id = new StringBuilder(user_id.toString());
cr_id=0;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
//return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
return 0;
}
#Override
public boolean isEnabled(int position){
return false;
}
static class ViewHolder{
public TextView ItemText;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.message_list_layout, null);
//configure view holder
viewHolder = new ViewHolder();
viewHolder.ItemText = (TextView) rowView.findViewById(R.id.list_item_text);
rowView.setTag(viewHolder);
}
else {
//fill data
viewHolder = (ViewHolder) rowView.getTag();
}
try{
Log.d("cr_id: ",String.valueOf(cr_id).toString());
//This is where the population should've taken place but didn't.
resultObject = new HttpTask(context).doInBackground("sendMessages",conversation_id.toString(),String.valueOf(cr_id));
if(resultObject.get("status").toString().equals("true")) {
messages = resultObject.getJSONArray("messages");
Log.d("Messages: ",messages.toString());
for(int i=0;i<=messages.length();i++){
list.add(messages.getJSONObject(i).get("reply_text").toString());
}
}
}
catch(JSONException e){ }
//Handle TextView and display string from your list
//final TextView listItemText = (TextView)rowView.findViewById(R.id.list_item_text);
//listItemText.setText(list.get(position));
viewHolder.ItemText.setText(list.get(position));
return rowView;
}
}
If every thing is working fine and you have problem in showing latest chat message in adapter just change your code like this:
try{
Log.d("cr_id: ",String.valueOf(cr_id).toString());
//This is where the population should've taken place but didn't.
resultObject = new HttpTask(context).doInBackground("sendMessages",conversation_id.toString(),String.valueOf(cr_id));
if(resultObject.get("status").toString().equals("true")) {
messages = resultObject.getJSONArray("messages");
Log.d("Messages: ",messages.toString());
for(int i=0;i<=messages.length();i++){
list.add(messages.getJSONObject(i).get("reply_text").toString());
this.notifyDataSetChanged(); // add this line
}
}
}
catch(JSONException e){ }
Comment below for any further information
Personally i would do the network calls outside of the adapter. With the code currently if the user was to scroll up and down the list the network call would call multiple times which is something im sure you dont want.
What may be a better solution is having a method inside the activity that does the call, then have a timer set up that calls that method say every 2 - 3 minutes to save on the network calls, you could also add a refresh button for the user which gives them the choice of refreshing the data themselves which would just call the same method.
The View Holder design pattern can help speed up a listview and keep it smooth, Think of it this way, when the page first loads, getView will be called a number of times to fill up the list view. In the getView method you instantiate your UI widgets i.e textview = (TextView)findviewbyid. Now what the view holder does is keep a reference to these ui elements which means you wont have to keep calling findViewById.
Here is an article that explains it a bit better and go into some examples.
http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html
So lets say you do the network code in the activity. When you get a response you can simply add the message to the list then notifyDataSetChanged();
So, Finally I got it working with some experimentation. Many thanks to Manikanta and Andy Joyce for their valuable answers. If it weren't for them i wouldn't have gone any further from where I was stuck.
This is what I changed in my custom adapter.
public void add(ArrayList<String> list){
this.list.clear();
this.list.addAll(list);
Log.d("List: ",this.list.toString());
this.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.message_list_layout, null);
//configure view holder
viewHolder = new ViewHolder();
viewHolder.ItemText = (TextView) rowView.findViewById(R.id.list_item_text);
rowView.setTag(viewHolder);
}
else {
//fill data
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.ItemText.setText(list.get(position));
return rowView;
}
This is what I added to my activity
#Override
public void onResume(){
super.onResume();
Bundle bundle = getIntent().getExtras();
if(bundle != null){
toUsername.setText("" + bundle.get("ToUsername").toString());
c_id = new StringBuilder(bundle.get("c_id").toString());
from_user_id = new StringBuilder(bundle.get("FromUserId").toString());
//list.add(c_id.toString());
//list.add(from_user_id.toString());
}
myAdapter = new MessageListViewAdapter(getBaseContext(),c_id.toString(),from_user_id.toString());
listView.setAdapter(myAdapter);
callAsynchronousTask();
//myAdapter.add(list);
}
#Override
public void onPause(){
super.onPause();
timer.cancel();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//list.clear();
try{
resultChatObject = new HttpTask(getBaseContext()).doInBackground("sendMessages",c_id.toString(),String.valueOf(cr_id));
if(resultChatObject.get("status").toString().equals("true")) {
//list.clear();
messages = resultChatObject.getJSONArray("messages");
Log.d("Messages: ",messages.toString());
for (int i = 0; i <= messages.length(); i++) {
list.add(messages.getJSONObject(i).get("reply_text").toString());
if (cr_id < Integer.parseInt(messages.getJSONObject(i).get("cr_id").toString()))
cr_id = Integer.parseInt(messages.getJSONObject(i).get("cr_id").toString());
}
}
}
catch (JSONException e) { }
myAdapter.add(list);
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 10000 ms
}
Cheers everyone!!!

Custom Adapter not working for the listview from Parse.com

I am trying to create an android application using a database from Parse.com. I am using a custom adapter to create a listview. I don't find any errors with the code and yet the listeview is not showing up. Nothing there in the logcat as well. Just the listview does not show up.
lv = (ListView)findViewById(R.id.listView);
mProgress = (ProgressBar)findViewById(R.id.check_progress);
mProgress.setVisibility(View.VISIBLE);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Sellers");
query.orderByAscending("Name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
studentsList = new ArrayList<Sellers>();
for (ParseObject ob : parseObjects) {
s = new Sellers();
s.setName(ob.getString("Name").toString());
s.setAddress1(ob.getString("Address1").toString());
s.setAddress2(ob.getString("Address2").toString());
s.setShopName(ob.getString("ShopName").toString());
s.setEmail(ob.getString("Email").toString());
s.setPhone(ob.getString("Phone").toString());
s.setZipcode(ob.getString("Zipcode").toString());
studentsList.add(s);
}
adapter = new ListviewAdapter(CheckStatus.this, studentsList);
lv.setAdapter(adapter);
mProgress.setVisibility(View.GONE);
} else {
mProgress.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is the activity where I am invoking the listview.
public class ListviewAdapter extends BaseAdapter{
private final static String TAG = ListviewAdapter.class.getSimpleName();
private Context activity;
private LayoutInflater inflater = null;
private List<Sellers> sellers;
int layout;
public ListviewAdapter(Context activity, List<Sellers> sellers) {
this.activity = activity;
this.sellers = sellers;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView name ;
TextView shop ;
TextView address1 ;
TextView address2;
TextView phone;
TextView email;
RelativeLayout rl;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v =view;
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater li = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.list_item_layout,null);
holder.name = (TextView)v.findViewById(R.id.seller_name);
holder.shop = (TextView)v.findViewById(R.id.shop_name);
holder.address1 = (TextView)v.findViewById(R.id.address1);
holder.address2 = (TextView)v.findViewById(R.id.address2);
holder.phone = (TextView)v.findViewById(R.id.phone);
holder.email = (TextView)v.findViewById(R.id.emailID);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Sellers s = sellers.get(position);
// String a = s.Name;
// Log.d(TAG, a);
holder.name.setText(s.getName());
holder.shop.setText(s.getShopName());
holder.address1.setText(s.getAddress1());
holder.address2.setText(s.getAddress2());
holder.phone.setText(s.getPhone());
holder.email.setText(s.getEmail());
Log.d("CustomAdapter.class", "CustomAdapter");
// imageView.setImageDrawable(s.getPic());
return v;
}
}
And this is the custom adapter. There are no null pointer exceptions showing up in the logcat. I can't determine why the listview is not getting populated.
Try this;
#Override
public int getCount() {
return sellers.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position:
}
You have to implement your code on getCount() by return number of item listview will be created.

AsyncTask onPostExecute TextView not updating

My situation is like this:
My main activity has 3 fragments. The first fragment requests data from the server and tries to render it. I use an AsyncTask inner class to get the data and render in onPostExecute. I render using a SimpleCursorAdapter with a ListView. Rendering works fine. After this is done, I try to manipulate the UI (set value of a TextView) but it is not working. getViewById does not return null or any errors but I still cannot change the value for some reason. Any suggestions are highly appreciated. Here is the Fragment Class that I use:
public class FeedFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
Activity activity = getActivity();
try {
new getFeedData(activity,rootView).execute();
}
finally{
return rootView;
}
}
private class getFeedData extends AsyncTask<Void, Void, String> {
private Context activity;
private View rootView;
public getFeedData(Context context, View main){
this.activity=context;
this.rootView=main;
}
#Override
protected String doInBackground(Void... params) {
try {
HttpRequest request = HttpRequest.get("http://upinion.us/test/feed_sample/");
String response = "";
if (request.ok()) {
response = request.body();
}
return response;
} catch (HttpRequestException exception) {
return null;
}
}
#Override
protected void onPostExecute(String response) {
String[] columns = new String[] {"_id","title","description"};
int[] viewIds = new int[] {R.id.postId,R.id.title,R.id.description};
JSONArray finalResponse;
try {
finalResponse = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
finalResponse = null;
}
MatrixCursor mc = new MatrixCursor(new String[] {"_id","title","description"}); // properties from the JSONObjects
for (int i = 0; i < finalResponse.length(); i++) {
JSONObject jsonObject;
try {
jsonObject = finalResponse.getJSONObject(i);
mc.addRow(new Object[] {jsonObject.get("_id"),jsonObject.get("title"),jsonObject.get("description")});
} catch (JSONException e) {
jsonObject=null;
}
}
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.post, mc, columns, viewIds,0);
ListView list = (ListView) this.rootView.findViewById(R.id.feed_feed);
list.setAdapter(mAdapter);
View v;
for (int i = 0; i < list.getCount(); i++) {
v = list.getAdapter().getView(i, null, null);
TextView text = (TextView) v.findViewById(R.id.title);
text.setText("HELLO MOTO");
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
Integer convId = parent.getId();
}
});
}
}
}
As you can see, I pass the activity and the inflated root view to the asynctask, but still no luck. I have spent nearly two days trying to find a solution with no success.
for (int i = 0; i < list.getCount(); i++) {
v = list.getAdapter().getView(i, null, null);
TextView text = (TextView) v.findViewById(R.id.title);
text.setText("HELLO MOTO");
}
this is your problem:
you are NOT supposed to call getView yourself
to update your listview, you need to call adapter.notifyDataSetChanged
and the system will call the updates for you
so remove this piece of code entirely and just replace it with adapter.notifyDataSetChanged

Categories

Resources