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();
}
Related
I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}
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.
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
I want to set the background color for the list which has the different values in an textbox like happy, sad coming from database and i want when in my text box happy comes background color changes to red and when angry it changes to green like this...
Here is my code....
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Feeds.this);
pDialog.setMessage("Loading Feeds. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All moods from url
* */
protected String doInBackground(String... args) {
// Session class instance
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// email
String email = user.get(SessionManage.KEY_EMAIL).toString();
Log.d("seesion", email);
// Building Parameters
List<NameValuePair> para = new ArrayList<NameValuePair>();
para.add(new BasicNameValuePair("email", email));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_get_moods, "GET",
para);
// Check your log cat for JSON reponse
Log.d("All Moods: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
Log.d("yjyth", Integer.toString(success));
if (success == 1) {
String data = null;
// Moods found
// looping through All Products
for (int i = 1; i <= json.length(); i++) {
try {
JSONObject c = json.getJSONObject(Integer
.toString(i));
Log.d("Loop", Integer.toString(i));
Log.d("Value of c", c.toString());
JSONObject dd = c.getJSONObject("data");
Log.d("value of dta", dd.toString());
String type = dd.getString("type");
Log.d("value of type", type);
String because = dd.getString("because");
Log.d("value of type", because);
String created = dd.getString("created");
Log.d("value of type", type);
String description = dd.getString("description");
Log.d("value of des", description);
//String datetime1 = dd.getString("datetime");
img=(ImageView)findViewById(R.id.imageFeeds);
LinearLayout l=(LinearLayout)findViewById(R.id.lisfeeds);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put("type", type);
map.put("because", because);
map.put("description", description);
map.put("created", created);
if(type.equals("Feeling Happy")){
map.put("img", R.drawable.happyhov);
map.put("color", R.drawable.angrygrad);
}
else if(type.equals("Feeling Angry")){
map.put("img", R.drawable.angryhov);
}
else if(type.equals("Feeling Confused")){
map.put("img", R.drawable.confusdhov);
}
else if(type.equals("Feeling Confident")){
map.put("img", R.drawable.confihov);
}
else if(type.equals( "Feeling Frustrated")){
map.put("img",R.drawable.frusthov);
}
else if(type.equals("Feeling Lonely")){
map.put("img", R.drawable.loneyhov);
}
else if(type.equals("Feeling Ecstatic")){
map.put("img", R.drawable.esthov);
}
else if(type.equals("Feeling Sad")){
map.put("img",R.drawable.sadhov);
}
// adding HashList to ArrayList
moodsList.add(map);
} catch (Exception e) {
Log.e(" Parser", "Error data " + e.toString());
}
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(), Home.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
MyAdapter adapter = new MyAdapter(Feeds.this,
moodsList, R.layout.item_list,
new String[] {
"img",TAG_TYPE,TAG_BECAUSE, TAG_DESCRIPTION, TAG_CREATED},
new int[] { R.id.imageFeeds,R.id.type, R.id.texbec, R.id.des,R.id.date });
// updating listview
lv.setAdapter(adapter);
}
});
}
}
class MyAdapter extends SimpleAdapter {
private String[] names;
private Activity c;
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
class ViewHolder {
public TextView texttype,bec,des,date;
public ImageView image;
}
public MyAdapter(Activity c, String[] names) {
super(c, moodsList, R.layout.item_list, names, null);
this.c = c;
this.names = names;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
Context context = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.item_list, null);
holder = new ViewHolder();
holder.texttype = (TextView) vi.findViewById(R.id.type);
holder.image = (ImageView) vi
.findViewById(R.id.imageFeeds);
holder.bec = (TextView) vi.findViewById(R.id.texbec);
holder.des = (TextView) vi.findViewById(R.id.des);
holder.date = (TextView) vi.findViewById(R.id.date);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
Log.d("fchs","dfvhes");
//holder.image.setBackgroundResource(TAG_IMAGE);
holder.texttype.setText(TAG_TYPE);
holder.bec.setText(TAG_TYPE);
holder.des.setText(TAG_TYPE);
if (TAG_TYPE.equals("Happy") ) {
vi.setBackgroundColor(Color.BLUE);
} else {
vi.setBackgroundColor(Color.RED);
}
}catch(Exception e)
{
}
return vi;
}
}
Inside your custom adapter (SimpleAdapter) class --> got to --> public View getView Method make sure that your code is simmiler with this
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.my_group_list_item, null);
holder = new ViewHolder();
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (if sad if happy clause here ) {
vi.setBackgroundColor(Color.parseColor("#a1cc3b"));
} else {
vi.setBackgroundColor(Color.parseColor("#cfd0d1"));
}
hope this could help you.
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;
}
}