How to Dynamically add the text into listview - android

This question is asked many times but I don't get my actual solution because the ArrayList is in HashMap , so
I am not able to add text in the ListView. I had made a chat , where I got the result of all the chat messages, but when I send text message , it came on top , but when I went back and came again , it came in right way . So my problem is that when I add any text it does not come last or in text view.
//Here is my class
public class ChatScreenActivity extends Activity{
static ArrayList messages = new ArrayList<messageArray>();
ListView list;
Button sendmsg;
EditText usertext;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private static String sendmsgurl = "http://www.get2love.webitexperts.com/sendmessage";
private static String msgdetailurl = "http://www.get2love.webitexperts.com/getChatDetails";
JSONParser jsonParser = new JSONParser();
ChatMessageListAdapter adapter;
ActionBar actionBar;
/*ArrayList<String> al=new ArrayList<String>();
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,al);
*/
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
arraylist=new ArrayList<HashMap<String,String>>();
new messagedetaillist().execute();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatscreenctivity);
Intent intent= getIntent();
String sender_username=intent.getExtras().getString("User_Name");
list = (ListView) findViewById(R.id.listview1);
list.setCacheColorHint(Color.TRANSPARENT);
list.setDivider(null);
usertext=(EditText)findViewById(R.id.et_sent_msg);
sendmsg=(Button)findViewById(R.id.bt_sent_msg);
actionBar=getActionBar();
actionBar.show();
actionBar.setTitle(sender_username);
actionBar.setSubtitle("messages");
sendmsg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new sendmessage().execute();
}
});
}
class sendmessage extends AsyncTask<Void, Void, Void> {
int flag;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(ChatScreenActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args0) {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
HashMap<String, String> map = new HashMap<String, String>();
UserModel user=(UserModel)getIntent().getSerializableExtra("User");
String User_id=String.valueOf(user.getUser_Id());
String message=usertext.getText().toString();
Intent intent= getIntent();
String sender_id=intent.getExtras().getString("Sender_id");
params.add(new BasicNameValuePair("SenderUserID",User_id));
params.add(new BasicNameValuePair("ChatText",message));
params.add(new BasicNameValuePair("ReceiverID",sender_id));
ServiceHandler sh = new ServiceHandler();
JSONObject json = jsonParser.makeHttpRequest(sendmsgurl,"POST", params);
Log.d("Create Response", json.toString());
try
{
if(json!=null)
{
if(json.has("status"))
{
String status=json.getString("status");
if(status.equals("Success"))
{
flag=1;
map.put("Chat_Text",message);
map.put("Receiver_User_Id", sender_id);
map.put("User_Id", User_id);
arraylist.add(map);
}
}
else
{
flag=0;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
if(flag==1)
{
Toast.makeText(getApplicationContext(), "Succesfully send", Toast.LENGTH_SHORT).show();
ChatMessageListAdapter adapter = new ChatMessageListAdapter(ChatScreenActivity.this, arraylist);
list.setAdapter(adapter);
mProgressDialog.dismiss();
}
else
{
Toast.makeText(getApplicationContext(), "Failed registered ", Toast.LENGTH_SHORT).show();
}
}
}
class messagedetaillist extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(ChatScreenActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args0)
{
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
UserModel user=(UserModel)getIntent().getSerializableExtra("User");
String User_id=String.valueOf(user.getUser_Id());
Intent intent= getIntent();
String sender_id=intent.getExtras().getString("Sender_id");
params.add(new BasicNameValuePair("SenderUserID",sender_id));
params.add(new BasicNameValuePair("ReceiverID",User_id));
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(msgdetailurl, ServiceHandler.POST, params);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr.length()>0) {
try {
// Locate the array name in JSON
JSONArray contacts = new JSONArray(jsonStr);
for (int i = 0; i < contacts.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = contacts.getJSONObject(i);
String messages=c.getString("Chat_Text");
String SenderId=c.getString("Receiver_User_Id");
map.put("Chat_Text",messages);
map.put("Receiver_User_Id", SenderId);
map.put("User_Id", User_id);
// map.put("TempUser_Image", USer_Image);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
adapter = new ChatMessageListAdapter(ChatScreenActivity.this, arraylist);
list.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
Here is my Adapter class
public class ChatMessageListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
ChatMessageListAdapter adapter;
public ChatMessageListAdapter(Activity a, ArrayList<HashMap<String, String>> arraylist) {
activity = a;
data = arraylist;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
// items for main crowd list
public TextView txt_message;
public RelativeLayout layout_align;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.message_chat_row, null);
holder.txt_message = (TextView) view.findViewById(R.id.txt_message);
holder.layout_align = (RelativeLayout) view.findViewById(R.id.layout_align);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
resultp=data.get(position);
String type = resultp.get("Receiver_User_Id");
String message =resultp.get("Chat_Text");
String User_id=resultp.get("User_Id");// data.get(position).message;
if (!type.equalsIgnoreCase(User_id)) {
holder.layout_align.setGravity(Gravity.RIGHT);
holder.txt_message.setText(message);
holder.txt_message.setBackgroundResource(R.drawable.bubble_green);
}
else {
holder.layout_align.setGravity(Gravity.LEFT);
holder.txt_message.setText(message);
holder.txt_message.setBackgroundResource(R.drawable.bubble_yellow);
}
} catch (Exception e) {
// TODO: handle exception
}
return view;
}
}

Try this within getView
SearchViewHolder orderViewHolder = null;
if (convertView == null) {
orderViewHolder = new SearchViewHolder();
convertView = inflater.inflate(R.layout.order_list_row, null);
orderViewHolder.setproe((TextView) convertView
.findViewById(R.id.tet1));
orderViewHolder.setbaumber((TextView) convertView
.findViewById(R.id.tet2));
convertView.setTag(orderViewHolder);
//orderViewHolder.getproductname().setTextSize(12);
} else {
orderViewHolder = (SearchViewHolder)convertView.getTag();
}
orderViewHolder.getproductname().setText(""+partProductQTY.ownerPartyId);
orderViewHolder.getbatchnumber().setText(""+partProductQTY.availableToPromiseTotal);
return convertView;
Here partProductQTY is my plain POJO class , inpite of this you need use ArrayList

Related

onPostExecute AysncTask Cancel and remain on same activity

In this i want to cancel the asynctask i called aysnc task in listview onclickitem...
so if there is no data in particular row's then it will stop execution and remain on same activity.
I called the class in click and if condition if false as file_path is null then it will remain on same activity will not proceed further in another activity.
but in my case it will move to another activity i tried lot many things on this like oncancelled(), cancel(), etc methods but they are not working i put all in loop as well as switch case to break.
public class EAdFragment extends Fragment {
ListView lvAdSurvey;
JSONObject json = null;
public static final String FIRST_COLUMN = "Upl_ID";
public static final String SECOND_COLUMN = "File_Description";
JSONArray jarray = null;
JSONObject jsonObj = null;
String upload_type;
String upl_id;
File f;
String imgurl;
ProgressDialog pDialog;
String upl_ID, type_of_upload, file_description, amount;
String file_path = null;
String file_type, related_to, country, state, city, Number_of_user,
type_illegal;
GetData task;
ViewHolder holder;
public ListAdapter adapter;
String text;
public List<EAdvertActivityData> listData = new ArrayList<EAdvertActivityData>();
public void onViewCreated(View view, Bundle savedInstanceState) {
lvAdSurvey = (ListView) view.findViewById(R.id.lvAdSurvey);
new GetList().execute();
lvAdSurvey.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// String text =
// lvAdSurvey.getItemAtPosition(position).toString();
holder = (ViewHolder) view.getTag();
text = holder.txtFirstColumn.getText().toString();
Log.d("text:", text);
task = new GetData();
task.execute();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ead, container,
false);
return rootView;
}
private class GetList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected JSONObject doInBackground(String... args) {
String url = "url";
JSONParser jParser = new JSONParser();
jsonObj = jParser.getJSONFromUrl(url);
try {
jarray = jsonObj.getJSONArray("result");
Log.d("lengtharray:", String.valueOf(jarray.length()));
for (int i = 0; i < jarray.length(); i++) {
EAdvertActivityData data = new EAdvertActivityData();
JSONObject jobject = new JSONObject(jarray.get(i)
.toString());
upload_type = jobject.optString("Upl_ID").toString();
String description = jobject.optString("File_description")
.toString();
/*
* Log.d("upload_type",upload_type);
* Log.d("description",description);
*/data.setUpl_ID(upload_type);
data.setFile_description(description);
listData.add(data);
Log.d("data:", listData.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObject) {
EAdListViewAdapter adapter = new EAdListViewAdapter(getActivity(),
listData);
lvAdSurvey.setAdapter(adapter);
}
}
private class GetData extends AsyncTask<String, String, String> {
int flag=0;
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
SharedPreferences pref = getActivity().getSharedPreferences(
"SoundSettings", Context.MODE_PRIVATE);
String user_id = pref.getString("user_id", LoginActivity.userid);
String url = "url"
+ text;
JSONParser jParser = new JSONParser();
try {
json = jParser.getJSONFromUrl(url);
Log.d("jsonadvert:", json.toString());
String status = json.getString("fetchdata");
if (status.equals("Success")) {
type_of_upload = json.getString("Type_of_Upload");
file_description = json.getString("File_description");
amount = json.getString("Amount");
file_path = json.getString("file_path");
file_type = json.getString("File_type");
related_to = json.getString("Related_to");
country = json.getString("Country");
// state = json.getString("state");
Number_of_user = json.getString("Number_of_usr");
type_illegal = json.getString("Type_llegal");
Log.d("type_illegal:", type_illegal);
Log.d("file_path:", file_path);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
pDialog.dismiss();
if(file_path==null){
Toast.makeText(getActivity(), "Image does not exists", Toast.LENGTH_LONG).show();
pDialog.cancel();
task.cancel(true);
}else{
imgurl = "http://sharpersofttech.com/sign_up/" + file_path;
Intent in = new Intent(getActivity(), AdvertActivity.class);
in.putExtra("upl_id", text);
in.putExtra("file_description", file_description);
in.putExtra("imgurl", imgurl);
startActivity(in);
((Activity) getActivity()).overridePendingTransition(0, 0);
}
}
}
}

Cannot display/send data and image from Custom Listview to Detail activity

I'm new in android developer, I've problem in my custom Listview, the condition is when I click on my listview it should be go to detail activity. and yes, it works!
but the detail data and image isn't appear. only detail.xml without data and image.
Ymainactivity.java
private class GetData extends AsyncTask<String, Void, String> {
JSONArray str_json = null;
JSONObject json = null;
JSONParser jParser = new JSONParser();
ListView listx;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> data_map = new ArrayList<HashMap<String, String>>();
ProgressDialog dialog = new ProgressDialog(YmainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Memuat Item..");
this.dialog.show();
}
protected String doInBackground(String... param) {
json = jParser.AmbilJson(link_url);
try {
str_json = json.getJSONArray("berita");
for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);
String kodebrg = "kode barang : "+ar.getString("kodebrg");
String gambar = ar.getString("gambar2");
String nama = ar.getString("nama");
String stok = "Stok : "+ar.getString("stok")+" "+ar.getString("satauan");
String harga = "Rp. "+ar.getString("harga")+" per "+ar.getString("satauan");
String info = ar.getString("info");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_nama, nama);
map.put(in_stok, stok);
map.put(in_kodebrg, kodebrg);
map.put(in_gambar, gambar);
map.put(in_harga, harga);
map.put(in_info, info);
data_map.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
dialog.dismiss();
listx = (ListView)findViewById(R.id.listos);
adapter = new LazyAdapter(YmainActivity.this, data_map);
listx.setAdapter(adapter);
if (adapter.getCount()==0) {
Toast.makeText(YmainActivity.this,"data tidak ditemukan",Toast.LENGTH_SHORT).show();
}
listx.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
HashMap<String, String> map = (HashMap<String, String>) adapter.getItem(position);
String kodebrgs = ((TextView) view.findViewById(R.id.kodebrgs)).getText().toString();
Intent inx = new Intent(YmainActivity.this, DetailActivity.class);
inx.putExtra(kodebrgs, map2.get(in_kodebrg));
startActivity(inx);
}
DetailActivity.java
private class GetData extends AsyncTask<String, Void, String> {
JSONArray artikel = null;
JSONObject json = null;
JSONParser jParser = new JSONParser();
Intent ins = getIntent();
String kode1s = ins.getStringExtra(in_kodebrg);
String link_url = "http:// my php file that call all data using primary id from table in my database mySQL"+kode1s;
ProgressDialog dialog = new ProgressDialog(DetailActivity.this);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Memuat Detail Produk..");
this.dialog.show();
}
protected String doInBackground(String... params) {
json = jParser.AmbilJson(link_url);
return null;
}
protected void onPostExecute(String result) {
dialog.dismiss();
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
TextView judul1 = (TextView) findViewById(R.id.judul2);
TextView detail1 = (TextView) findViewById(R.id.detail2);
TextView isi1 = (TextView) findViewById(R.id.isi2);
TextView info1 = (TextView) findViewById(R.id.infobarang2);
TextView kodebarang1 = (TextView) findViewById(R.id.kodenyabrg2);
String judul_1 = ar.getString("nama");
String detail_1 = "harga Rp. "+ ar.getString("harga");
String isi_1 = "Stok Barang : "+ ar.getString("stok")+" "+ar.getString("satauan");
String info_1 = "Info : "+ar.getString("info");
String kodebarang_1 = "Kode Barang : "+ar.getString(in_kodebrg);
judul1.setText(judul_1);
detail1.setText(detail_1);
isi1.setText(isi_1);
info1.setText(info_1);
kodebarang1.setText(kodebarang_1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listimage_item, null);
TextView nama = (TextView)vi.findViewById(R.id.namas);
TextView stok = (TextView)vi.findViewById(R.id.stoks);
TextView kodebrg = (TextView)vi.findViewById(R.id.kodebrgs);
TextView harga = (TextView)vi.findViewById(R.id.hargas);
TextView info = (TextView)vi.findViewById(R.id.infos);
ImageView gambar=(ImageView)vi.findViewById(R.id.gambars);
HashMap<String, String> berita = new HashMap<String, String>();
berita = data.get(position);
nama.setText(berita.get(YmainActivity.in_nama));
stok.setText(berita.get(YmainActivity.in_stok));
kodebrg.setText(berita.get(YmainActivity.in_kodebrg));
harga.setText(berita.get(YmainActivity.in_harga));
info.setText(berita.get(YmainActivity.in_info));
imageLoader.DisplayImage(berita.get(YmainActivity.in_gambar), gambar);
return vi;
}
}
this is my custom listiview pict
http://cdn.gudangimages.com/v1/2015/06/05/gambarlistview.png
and this is detail xml when I clicked one of the list in my custom listview the result is blank, no data and image.
http://cdn.gudangimages.com/v1/2015/06/05/gambardetail.png
I don't know what's wrong with the code, because when I run the program it didn't force close.
first ,you need to debug on the detailActivity to find out whether getIntent() has got the data you desire , if you have got ,then use the view to contain these data ,if not , you need to think about whether the onitemclicklistener is ok
I think the problem is with inx.putExtra(kodebrgs, map2.get(in_kodebrg));
you should use key which doesn't change...
Intent i = new Intent(<currentActivity>.this,
<newactivity>.class);
i.putExtra("ticket", ticket);
i.putExtra("ticketid", tid);
startActivity(i);
and in other intent:
String ticketid = getIntent().getStringExtra("ticketid").toString();
String ticket = getIntent().getStringExtra("ticket").toString();
you can also send each string with different key and get them in detail page with help of key.

RSS with SAX parser

I want to put AsyncTask instead thread in this simple code of SAX RSS parser
in ListFragment , and what is better Asynctask or multi thread.
this is my code
public class ListItem extends ListFragment {
public ArrayList<NewsItem> getValues() {
return values;
}
public void setValues(ArrayList<NewsItem> values) {
this.values = values;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_news_layout, container, false);
return view;
}
enter code here
public void onStart() {
super.onStart();
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
refresh();
listAdapter = new ListAdapter(getActivity(), R.layout.listitem,
getValues());
setListAdapter(listAdapter);
}
enter code here
public void refresh() {
Thread th = new Thread(new Runnable() {
public void run() {
ListHandler listHandler = new ListHandler();
try {
listHandler.processFeed();
setValues(listHandler.getNewsItemList());
listAdapter.setNewsItemList(getValues());
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
Actually Asynctask is also using thread but it is better for onpostexecute and onprexecute()
method callback if you use thread you dont get this by default .
Like this
private class HttpAsyncDealsTask extends
AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {
protected ArrayList<HashMap<String, String>> doInBackground(
String... dealslist) {
ArrayList<HashMap<String, String>> chekinRsp = new ArrayList<HashMap<String, String>>();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// mem_id
String mem_id = user.get(SessionManager.KEY_ID);
String rest_id = getArguments().getString("getid");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("rest_id", rest_id));
nameValuePairs.add(new BasicNameValuePair("mem_id", mem_id));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL, ServiceHandler.POST,
nameValuePairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jresponse = new JSONObject(jsonStr);
JSONObject msg = jresponse.getJSONObject(KEY_MSG);
//String error = jresponse.getString(KEY_ERROR);
String msgss = msg.getString(KEY_MSGSS);
String error = msg.getString(KEY_ERROR);
if(error.equalsIgnoreCase("0"))
{
String getid = getArguments().getString("getid");
String getname = getArguments().getString("getname");
String getpoints = getArguments().getString("getpoints");
String getcomp = getArguments().getString("getcomp");
String getmemberpoint = getArguments().getString("getmemberpoint");
System.out.println(getid + getname + getpoints + getcomp + getmemberpoint);
CheckinPref checkin = new CheckinPref(getActivity());
checkin.Prefernce_save(getid
,getname, getpoints
,getcomp, getmemberpoint);
}
map.put(KEY_MSGSS, msgss);
chekinRsp.add(map);
// Log.d("OUT", msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.d("Response", e.getLocalizedMessage());
}
return chekinRsp; // return result
}
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> chekinRsp) {
System.out.println(chekinRsp.get(0).get(KEY_MSGSS));
TextView chekinResp = (TextView) getActivity().findViewById(
R.id.chekinResp);
chekinResp.setText(chekinRsp.get(0).get(KEY_MSGSS));
Button backButton = (Button) getActivity().findViewById(
R.id.btn_restback);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
fm.popBackStack();
}
});
}
}
and start this using
new HttpAsyncDealsTask().execute();

android -BaseAdapter doesn't add new items to listView

I don't know why my listView doesn't add new items .
this is the code :
ListAdapter ladap;
private class GetContacts AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected Void doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url + page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8");
String dates = new String(c.getString("dates").getBytes("ISO-8859-1"), "UTF-8");
String price = new String(c.getString("gheymat").getBytes("ISO-8859-1"), "UTF-8");
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", id);
contact.put("dates", dates);
contact.put("price", price);
dataC.add(contact);
}
}
} catch (JSONException e) {
goterr = true;
} catch (UnsupportedEncodingException e) {
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (!isCancelled() && goterr == false) {
if(ladap==null){
ladap=new ListAdapter(MainActivity.this,result);
lv.setAdapter(ladap);
}else{
ladap.addAll(result);
ladap.notifyDataSetChanged();
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String, String>> list;
public ListAdapter(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity = (Activity) activity;
this.list = list;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
public int getCount() {
return contactList.size();
}
public Object getItem(int position) {
return contactList.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView title,price;
ImageView img ;
//RelativeLayout rl;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.price = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = contactList.get(position);
holder.price.setText(item.get("price"));
return convertView;
}
}
with help of friends ,I solve my last problem , the new problem is this , The adapter doesn't update so it doesn't add new rows to ListView. I logged and I've 30 new items in the baseAdapter here :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
but it's not adding to listView.
could you help me to solve this problem ?
Thanks
You have used contactList ArrayList to showing ListView item and you will update data to contactList in doinBackground() which run another thread not in ui thread so you can not update ui data from out ui therad hence you have to take local ArrayList for doInBackground() and pass new or updated data to onPostExecute() which update this data to ui thread.
private class GetContacts extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url + page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8");
String dates = new String(c.getString("dates").getBytes("ISO-8859-1"), "UTF-8");
String price = new String(c.getString("gheymat").getBytes("ISO-8859-1"), "UTF-8");
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", id);
contact.put("dates", dates);
contact.put("price", price);
data.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return data;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(ladap==null){
ladap=new ListAdapter(MainActivity.this,result);
lv.setAdapter(ladap);
}else{
ladap.addAll(result);
ladap.notifyDataSetChanged();
}
}
}
This is wrong
public void updateList(ArrayList<HashMap<String, String>> list) {
this.list = list;
notifyDataSetChanged();
}
this is wrong too
if (!isCancelled() && goterr == false) {
ListAdapter ladap=new ListAdapter(MainActivity.this, contactList);
lv.setAdapter(ladap);
ladap.notifyDataSetChanged();
//ladap.updateList(contactList);
}
What you can do is instead of creating a new Adapter, add data to your previous adapter that you have created above
ListAdapter ladap
OK, so if you want to create an adapter ONLY once then fine, do it when the asyc task ends, otherwise make it a member and initiate it in an onCreate or something like that.
Technically if you replace all the content of the list, then your approach is fine, replace the ArrayList, but don't forget to call adapter.notifyDataSetChanged().
BUT if you only change some of the content of the list e.g. you add new elements or remove elements, then you should perform these changes on the original ArrayList, and then call the adapter.notifyDataSetChanged().
NOTE, all calls to adapter.notifyDataSetChanged() should be done on UI Thread.
Also, from what I see, if this is the exact code you are running you should not get this error, it seemed like the error is generated from another place.
if (!isCancelled() && goterr == false) {
ListAdapter ladap=new ListAdapter(MainActivity.this, contactList);
lv.setAdapter(ladap);
ladap.notifyDataSetChanged();
//ladap.updateList(contactList);
}
is wrong.
It should be
if (!isCancelled() && goterr == false) {
ladap.addAll(contactList);
ladap.notifyDataSetChanged();
}
You should define your adapter only once and update the values in it accordingly. You can use various constructors to suit your requirements.
---------------------EDITED---------------------
if (!isCancelled() && goterr == false) {
if(ladap==null){
ladap=new ListAdapter(MainActivity.this, contactList);
lv.setAdapter(ladap);
ladap.addAll(contactList);
}else{
ladap.addAll(contactList);
}
}
public void addAll(ArrayList<HashMap<String, String>> contactList) {
thislist.clear();
this.list = contactList;
notifyDataSetChanged();
}

Can't get the string value in Hash Map on List view adapter in Android

I already getting the string value from JSON but it seems to have the problem in Hash map or something, im getting null value on my List adapter. Can anyone help me or tell me if i did something wrong in my code. Thanks in advance.
Here is my code.
The Activity -
public class TestJSON extends Activity{
public static ListView lv;
public static ProgressDialog pDialog;
public static LazyAdapter adapter;
static final String KEY_ITEMS = "items";
static final String KEY_TITLE = "title";
static final String KEY_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_json_view);
new AsyncInitial().execute();
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
lv = (ListView)findViewById(R.id.list);
//lv.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));
}
private class AsyncInitial extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
menuItems = new ArrayList<HashMap<String, String>>();
try {
//if (vid_num <= 0) {
// Get a httpclient to talk to the internet
HttpClient client = new DefaultHttpClient();
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
//https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc
HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/SP86E04995E07F6BA8?v=2&start-index=1&max-results=50&alt=jsonc");
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into a readable string
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
// Create a JSON object that we can use from the String
JSONObject json = new JSONObject(jsonString);
// For further information about the syntax of this request and JSON-C
// see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
// Get are search result items
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(KEY_ITEMS);
// Get the total number of video
//String vid_num = json.getJSONObject("data").getString("totalItems");
//System.out.println("vid_num-------->"+ vid_num);
// Loop round our JSON list of videos creating Video objects to use within our app
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
// The title of the video
String title = jsonObject.getJSONObject("video").getString(KEY_TITLE);
System.out.println("Title-------->"+ title);
// A url to the thumbnail image of the video
// We will use this later to get an image using a Custom ImageView
//String TAG_thumbUrl = jsonObject.getJSONObject("video").getJSONObject("thumbnail").getString("sqDefault");
//System.out.println("thumbUrl-------->"+ thumbUrl);
String id = jsonObject.getJSONObject("video").getString(KEY_ID);
System.out.println("video_id-------->"+ id);
map.put(title, KEY_TITLE);
map.put(id, KEY_ID);
menuItems.add(map);
}
} catch (ClientProtocolException e) {
//Log.e("Feck", e);
} catch (IOException e) {
//Log.e("Feck", e);
} catch (JSONException e) {
//Log.e("Feck", e);
}
return menuItems;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
adapter = new LazyAdapter(TestJSON.this,menuItems);
lv.setAdapter(adapter);
pDialog.dismiss();
}
}
}
And The adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
public LazyAdapter(TestJSON testJSON, ArrayList<HashMap<String, String>> menuItems) {
activity = testJSON;
data = menuItems;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title);
TextView id = (TextView)vi.findViewById(R.id.artist);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(TestJSON.KEY_TITLE));
id.setText(item.get(TestJSON.KEY_ID));
return vi;
}
}

Categories

Resources