I'm working on a chat app. I want to create a cool design for my listview. My code is working but I want to add some design similar to the design of Facebook, but I have a problem.
I can't do this: i.e one user has an ID=52 and the other has=5293. If the user has Id=52, the textarea gravity in the left and the other in the right, and here my code it doesn't see my if statement every time print the else statement I don't know why really I put my ID in an array but really this is the same result.
public void LoadMessage() {
// TODO Auto-generated method stub
DatabseHandler d = new DatabseHandler(EchangingMessage.this);
String me = d.getData();
TextView you_id = (TextView) findViewById(R.id.you_id);
String you = you_id.getText().toString().trim();
Log.i("ID :", me + " : " + you);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("me", me));
params.add(new BasicNameValuePair("you", you));
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "POST",
params);
try {
int success = json.getInt(TAG_SUCCESS);
Log.i("success :", "" + success);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = "http://10.0.2.2/www/Android_Login_Secure/Images/upload/big/"
+ c.getString(TAG_LINK_IMAGE_RS);
String message_rs = c.getString(TAG_MESSAGE_RS);
String time_rs = c.getString(TAG_TIME_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_MESSAGE_RS, message_rs);
map.put(TAG_TIME_RS, time_rs);
DaftarRS.add(map);
}
} else {
finish();
}
} catch (Exception e) {
Log.e("Error", "COnnection:" + e.toString());
}
runOnUiThread(new Runnable() {
public void run() {
// updating listview
SetListViewAdapter(DaftarRS);
}
});
}
public class ListAdapterSendMessage extends BaseAdapter {
public String POST_TEXT;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public final static String you_id = null;
int count = 0;
public ListAdapterSendMessage(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() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int position) {
return 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.item_list_send, null);
}
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
String me = daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS);
if (me == "52") {
vi = inflater.inflate(R.layout.list_row_even, null);
TextView name_rs = (TextView) vi.findViewById(R.id.senderMessage);
TextView Des_rs = (TextView) vi.findViewById(R.id.message);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.imageSender);
TextView Time_rs = (TextView) vi.findViewById(R.id.senderTime);
name_rs.setText(daftar_rs.get(MyMessages.TAG_NAMA_RS));
// link_image_rs.setText(daftar_rs.get(MainActivity.TAG_LINK_IMAGE_RS));
// alamat_rs.setText(daftar_rs.get(MainActivity.TAG_ALAMAT_RS));
Des_rs.setText(daftar_rs.get(MyMessages.TAG_MESSAGE_RS));
Time_rs.setText(daftar_rs.get(MyMessages.TAG_TIME_RS));
imageLoader.DisplayImage(
daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS), thumb_image);
} else {
vi = inflater.inflate(R.layout.list_row_odd, null);
TextView name_rs = (TextView) vi.findViewById(R.id.senderMessage);
TextView Des_rs = (TextView) vi.findViewById(R.id.message);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.imageSender);
TextView Time_rs = (TextView) vi.findViewById(R.id.senderTime);
name_rs.setText(daftar_rs.get(MyMessages.TAG_NAMA_RS));
// link_image_rs.setText(daftar_rs.get(MainActivity.TAG_LINK_IMAGE_RS));
// alamat_rs.setText(daftar_rs.get(MainActivity.TAG_ALAMAT_RS));
Des_rs.setText(daftar_rs.get(MyMessages.TAG_MESSAGE_RS));
Time_rs.setText(daftar_rs.get(MyMessages.TAG_TIME_RS));
imageLoader.DisplayImage(
daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS), thumb_image);
}
return vi;
}
}
for this question we assume that my id =1 and you id =2
if (id==1) {
inflater.inflate(R.layout.item_list_right, parent, false);
else
{
inflater.inflate(R.layout.item_list_left, parent, false);
}
here you have to different layout one of them item_list_right and the other one is item_list_left
I solved this problem like this
Related
I am using custom layout listview with custom adapter. I am also using Pull to refresh listview library
When I pull to refresh the UI changes are notifiable,but actual update in the listview is not happening
HomeFragment.java
public class HomeFragment extends Fragment implements OnClickListener{
private ListView listView;
PullToRefreshListView refreshable_listView;
private MyCustomAdapter mAdapter;
ArrayList<HashMap<String, String>> newsList;
String index_th="0";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_layout, container,false);
//karthik
refreshable_listView = (PullToRefreshListView) rootView.findViewById(R.id.listView);
refreshable_listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
new GetList().execute(index_th);
}
});
listView=refreshable_listView.getRefreshableView();
}
private class GetList extends AsyncTask<String, Void, Void> {
Dialog dialog = new Dialog(getActivity());
String jsonStr;
ArrayList<HashMap<String, String>> Local_newsList;
#Override
protected void onPreExecute() {
super.onPreExecute();
Local_newsList=new ArrayList<HashMap<String,String>>();
// Showing progress dialog
/*dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout._wait_dialog);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();*/
}
#Override
protected Void doInBackground(String... params) {
if (NetworkCheck.isNetworkAvailable(getActivity()) == true) {
//Log.d("index count for array", params[0]);
if(Integer.parseInt(params[0])==0){
//Log.d("index count for array","Rweached");
newsList = new ArrayList<HashMap<String, String>>();
}
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(All_link.HOME_DATA_URL + "/"+params[0]+"/"+ icount,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
news = jsonObj.getJSONArray(All_link.TAG_NEWS);
err = jsonObj.getString(All_link.TAG_ERROR);
String more = jsonObj.getString(All_link.TAG_MORE);
Log.e("------>Error",String.valueOf(err));
Log.e("------>More",String.valueOf(more));
if(more.equals("0")){
load_more = 0;
}else{
load_more = 1;
}
// looping through All Contacts
for (int i = 0; i < news.length(); i++) {
//karthik
JSONObject segments_list = news.getJSONObject(i);
for (int plates_count = 0; plates_count < segments_list
.length(); plates_count++) {
String plates = "";
if (plates_count == 3) {
plates = String.valueOf("banner_image");
JSONObject segments_plates = segments_list
.getJSONObject(plates);
//String flag = "banner_image";
String id = segments_plates
.getString(All_link.TAG_BANNER_ID);
String banner_no = segments_plates
.getString(All_link.TAG_BANNER_NO);
String banner_image;
if(segments_plates.getString(All_link.TAG_BANNER_THUMB_URL)==""){
banner_image = All_link.TAG_NO_IMAGE;
}else{
banner_image = segments_plates.getString(All_link.TAG_BANNER_THUMB_URL);
}
String banner_status = segments_plates
.getString(All_link.TAG_BANNER_STATUS);
// tmp hashmap for single news
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_BANNER_ID, id);
news_hashmap.put(All_link.TAG_BANNER_NO,
banner_no);
news_hashmap.put(All_link.TAG_BANNER_THUMB_URL,
banner_image);
news_hashmap.put(All_link.TAG_BANNER_STATUS,
banner_status);
/*news_hashmap
.put(All_link.TAG_BANNER_FLAG, flag);*/
// adding contact to contact list
newsList.add(news_hashmap);
//karthik newsList
//Local_newsList.add(news_hashmap);
addSeparatorItem();
} else {
plates = String.valueOf(plates_count + 1);
JSONObject segments_plates = segments_list
.getJSONObject(plates);
if(segments_plates.getString(All_link.TAG_NEWS_TYPE).equals("2")){
//type_of_news = segments_plates.getString(All_link.TAG_NEWS_TYPE);
addSeparatorItem_for_live();
}
String id = segments_plates.getString(All_link.TAG_ID);
String news_title = segments_plates.getString(All_link.TAG_NEWS_TITLE);
String news_desc = segments_plates.getString(All_link.TAG_DESC);
String segment = segments_plates.getString(All_link.TAG_SEGMENT);
String plate = segments_plates.getString(All_link.TAG_PLATE);
String img ="";
if(segments_plates.getString(All_link.TAG_THUMB_URL).equals("")){
img = All_link.TAG_NO_IMAGE;
}else{
img = segments_plates.getString(All_link.TAG_THUMB_URL);
}
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_ID, id);
news_hashmap.put(All_link.TAG_NEWS_TITLE, news_title);
news_hashmap.put(All_link.TAG_DESC, news_desc);
news_hashmap.put(All_link.TAG_SEGMENT, segment);
news_hashmap.put(All_link.TAG_PLATE, plate);
news_hashmap.put(All_link.TAG_THUMB_URL, img);
//news_hashmap.put(All_link.TAG_BANNER_FLAG, flag);
// adding contact to contact list
newsList.add(news_hashmap);
//karthik newsList
//Local_newsList.add(news_hashmap);
int val = 0;
int val2 = 1;
val = (Integer.parseInt(segment)%2)==0 ? val:val2;
if((Integer.parseInt(segment)%2)!=0){
Log.e("--->CHECKING ODD EVEN", String.valueOf(val));
addSeparatorItem();
addSeparatorItem_for_alternate();
}
}
}
}
} catch (JSONException e) {
Local_newsList=null;
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
Log.e("Network Error", "Internet Connection Error");
error_flag = 1;
// error = "Internet Connection Error";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mAdapter = new MyCustomAdapter(getActivity(), newsList);
mAdapter.notifyDataSetChanged();
refreshable_listView.onRefreshComplete();
}
});
super.onPostExecute(result);
}
MyCustomAdapter.java
private class MyCustomAdapter extends BaseAdapter {
private Activity activity;
Boolean result;
private final LayoutInflater inflater = null;
public ImageLoader imageLoader;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_SEPARATOR_ALTERNATE = 2;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 3;
private int live_type = 0;
private LayoutInflater mInflater;
public MyCustomAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
mInflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = a;
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getItemViewType(int position) {
int separtorValue;
int pos = mSeparatorsSet.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
live_type = mSeparatorsSet_live_layout.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
if(pos==1){
//Log.e("--->if called- position->", String.valueOf(position));
if(mSeparatorsSet_alternate_layout.contains(position)){
//Log.e("--->if called-->", String.valueOf(position));
separtorValue = 2;
}else{
separtorValue = 1;
}
}else{
separtorValue = 0;
}
return separtorValue;
}
#Override
public int getViewTypeCount() {
Log.e("--->TYPE_MAX_COUNT called-->", String.valueOf(TYPE_MAX_COUNT));
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return newsList.size();
}
#Override
public HashMap<String, String> getItem(int position) {
return newsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NewsViewHolder holder = null;
int type = getItemViewType(position);
Log.e("--->SHISHIR-->", String.valueOf(live_type));
/*System.out.println("getView " + position + " " + convertView
+ " type = " + type);
**/
//Log.e("--->SHISHIR-->", String.valueOf(position) + " -->live"+String.valueOf(mSeparatorsSet_live_layout.first()));
if (convertView == null) {
holder = new NewsViewHolder();
//Log.e("--itempostion", String.valueOf(getItem(type)));
switch (type) {
case TYPE_ITEM:
if (CURRENT_THEME==1) {
convertView = mInflater.inflate(
R.layout.theme_one_row_small, null);
}
else{
convertView = mInflater.inflate(
R.layout.theme_one_row_small_new, null);
}
holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.live = (TextView) convertView.findViewById(R.id.live);
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
imageLoader
.DisplayImage(
com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(
All_link.TAG_THUMB_URL),
holder.img);
break;
case TYPE_SEPARATOR_ALTERNATE:
if (CURRENT_THEME==1) {
convertView = mInflater
.inflate(R.layout.theme_one_row_big, null);
}
else{
convertView = mInflater
.inflate(R.layout.theme_one_row_big_new, null);
}
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.live = (TextView) convertView.findViewById(R.id.live);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
break;
case TYPE_SEPARATOR:
convertView = mInflater
.inflate(R.layout.theme_banner, null);
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
break;
}
convertView.setTag(holder);
} else {
holder = (NewsViewHolder) convertView.getTag();
}
switch (type) {
case TYPE_ITEM:
if(live_type == 1){
holder.img_flag.setVisibility(0);
holder.live.setText("live");
}else{
holder.live.setText("not_live");
holder.img_flag.setVisibility(8);
}
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_ID)));
holder.flag.setText("normal");
break;
case TYPE_SEPARATOR_ALTERNATE:
if(live_type == 1){
holder.img_flag.setVisibility(0);
holder.live.setText("live");
//Log.e("--itempostion Live", "live");
}else{
holder.live.setText("not_live");
holder.img_flag.setVisibility(8);
}
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_ID)));
holder.flag.setText("normal");
Log.e("karthik", "karthik "+com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL));
break;
case TYPE_SEPARATOR:
Log.e("--banner Images", com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_BANNER_ID)));
holder.flag.setText(newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
break;
}
holder.name.setText(String.valueOf(newsList.get(position).get(All_link.TAG_NEWS_TITLE)));
return convertView;
}
}
You forgot to setAdapter :
mAdapter = new MyCustomAdapter(getActivity(), newsList);
refreshable_listView.setAdapter(mAdapter);
I am successful in implementing Pull to refresh listview with already available library.NoW the problem is while refreshing, the already displayed data in listview disappears (blank while page) , and when done with refreshing the data gets displayed with updated data , which is not a expected result
public class HomeFragment extends Fragment implements OnClickListener{
private ListView listView;
PullToRefreshListView refreshable_listView;
private MyCustomAdapter mAdapter;
ArrayList<HashMap<String, String>> newsList;
String index_th="0";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_layout, container,false);
//karthik
refreshable_listView = (PullToRefreshListView) rootView.findViewById(R.id.listView);
refreshable_listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
new GetList().execute(index_th);
}
});
listView=refreshable_listView.getRefreshableView();
}
private class GetList extends AsyncTask<String, Void, Void> {
Dialog dialog = new Dialog(getActivity());
String jsonStr;
ArrayList<HashMap<String, String>> Local_newsList;
#Override
protected void onPreExecute() {
super.onPreExecute();
Local_newsList=new ArrayList<HashMap<String,String>>();
// Showing progress dialog
/*dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout._wait_dialog);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();*/
}
#Override
protected Void doInBackground(String... params) {
if (NetworkCheck.isNetworkAvailable(getActivity()) == true) {
//Log.d("index count for array", params[0]);
if(Integer.parseInt(params[0])==0){
//Log.d("index count for array","Rweached");
newsList = new ArrayList<HashMap<String, String>>();
}
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(All_link.HOME_DATA_URL + "/"+params[0]+"/"+ icount,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
news = jsonObj.getJSONArray(All_link.TAG_NEWS);
err = jsonObj.getString(All_link.TAG_ERROR);
String more = jsonObj.getString(All_link.TAG_MORE);
Log.e("------>Error",String.valueOf(err));
Log.e("------>More",String.valueOf(more));
if(more.equals("0")){
load_more = 0;
}else{
load_more = 1;
}
// looping through All Contacts
for (int i = 0; i < news.length(); i++) {
//karthik
JSONObject segments_list = news.getJSONObject(i);
for (int plates_count = 0; plates_count < segments_list
.length(); plates_count++) {
String plates = "";
if (plates_count == 3) {
plates = String.valueOf("banner_image");
JSONObject segments_plates = segments_list
.getJSONObject(plates);
//String flag = "banner_image";
String id = segments_plates
.getString(All_link.TAG_BANNER_ID);
String banner_no = segments_plates
.getString(All_link.TAG_BANNER_NO);
String banner_image;
if(segments_plates.getString(All_link.TAG_BANNER_THUMB_URL)==""){
banner_image = All_link.TAG_NO_IMAGE;
}else{
banner_image = segments_plates.getString(All_link.TAG_BANNER_THUMB_URL);
}
String banner_status = segments_plates
.getString(All_link.TAG_BANNER_STATUS);
// tmp hashmap for single news
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_BANNER_ID, id);
news_hashmap.put(All_link.TAG_BANNER_NO,
banner_no);
news_hashmap.put(All_link.TAG_BANNER_THUMB_URL,
banner_image);
news_hashmap.put(All_link.TAG_BANNER_STATUS,
banner_status);
/*news_hashmap
.put(All_link.TAG_BANNER_FLAG, flag);*/
// adding contact to contact list
newsList.add(news_hashmap);
//karthik newsList
//Local_newsList.add(news_hashmap);
addSeparatorItem();
} else {
plates = String.valueOf(plates_count + 1);
JSONObject segments_plates = segments_list
.getJSONObject(plates);
if(segments_plates.getString(All_link.TAG_NEWS_TYPE).equals("2")){
//type_of_news = segments_plates.getString(All_link.TAG_NEWS_TYPE);
addSeparatorItem_for_live();
}
String id = segments_plates.getString(All_link.TAG_ID);
String news_title = segments_plates.getString(All_link.TAG_NEWS_TITLE);
String news_desc = segments_plates.getString(All_link.TAG_DESC);
String segment = segments_plates.getString(All_link.TAG_SEGMENT);
String plate = segments_plates.getString(All_link.TAG_PLATE);
String img ="";
if(segments_plates.getString(All_link.TAG_THUMB_URL).equals("")){
img = All_link.TAG_NO_IMAGE;
}else{
img = segments_plates.getString(All_link.TAG_THUMB_URL);
}
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_ID, id);
news_hashmap.put(All_link.TAG_NEWS_TITLE, news_title);
news_hashmap.put(All_link.TAG_DESC, news_desc);
news_hashmap.put(All_link.TAG_SEGMENT, segment);
news_hashmap.put(All_link.TAG_PLATE, plate);
news_hashmap.put(All_link.TAG_THUMB_URL, img);
//news_hashmap.put(All_link.TAG_BANNER_FLAG, flag);
// adding contact to contact list
newsList.add(news_hashmap);
//karthik newsList
//Local_newsList.add(news_hashmap);
int val = 0;
int val2 = 1;
val = (Integer.parseInt(segment)%2)==0 ? val:val2;
if((Integer.parseInt(segment)%2)!=0){
Log.e("--->CHECKING ODD EVEN", String.valueOf(val));
addSeparatorItem();
addSeparatorItem_for_alternate();
}
}
}
}
} catch (JSONException e) {
Local_newsList=null;
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
Log.e("Network Error", "Internet Connection Error");
error_flag = 1;
// error = "Internet Connection Error";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mAdapter = new MyCustomAdapter(getActivity(), newsList);
mAdapter.notifyDataSetChanged();
refreshable_listView.setAdapter(mAdapter);
refreshable_listView.onRefreshComplete();
}
});
super.onPostExecute(result);
}
MyCustomAdapter.java
private class MyCustomAdapter extends BaseAdapter {
private Activity activity;
Boolean result;
private final LayoutInflater inflater = null;
public ImageLoader imageLoader;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_SEPARATOR_ALTERNATE = 2;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 3;
private int live_type = 0;
private LayoutInflater mInflater;
public MyCustomAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
mInflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = a;
newsList=d;
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getItemViewType(int position) {
int separtorValue;
int pos = mSeparatorsSet.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
live_type = mSeparatorsSet_live_layout.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
if(pos==1){
//Log.e("--->if called- position->", String.valueOf(position));
if(mSeparatorsSet_alternate_layout.contains(position)){
//Log.e("--->if called-->", String.valueOf(position));
separtorValue = 2;
}else{
separtorValue = 1;
}
}else{
separtorValue = 0;
}
return separtorValue;
}
#Override
public int getViewTypeCount() {
Log.e("--->TYPE_MAX_COUNT called-->", String.valueOf(TYPE_MAX_COUNT));
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return newsList.size();
}
#Override
public HashMap<String, String> getItem(int position) {
return newsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NewsViewHolder holder = null;
int type = getItemViewType(position);
Log.e("--->SHISHIR-->", String.valueOf(live_type));
/*System.out.println("getView " + position + " " + convertView
+ " type = " + type);
**/
//Log.e("--->SHISHIR-->", String.valueOf(position) + " -->live"+String.valueOf(mSeparatorsSet_live_layout.first()));
if (convertView == null) {
holder = new NewsViewHolder();
//Log.e("--itempostion", String.valueOf(getItem(type)));
switch (type) {
case TYPE_ITEM:
if (CURRENT_THEME==1) {
convertView = mInflater.inflate(
R.layout.theme_one_row_small, null);
}
else{
convertView = mInflater.inflate(
R.layout.theme_one_row_small_new, null);
}
holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.live = (TextView) convertView.findViewById(R.id.live);
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
imageLoader
.DisplayImage(
com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(
All_link.TAG_THUMB_URL),
holder.img);
break;
case TYPE_SEPARATOR_ALTERNATE:
if (CURRENT_THEME==1) {
convertView = mInflater
.inflate(R.layout.theme_one_row_big, null);
}
else{
convertView = mInflater
.inflate(R.layout.theme_one_row_big_new, null);
}
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.live = (TextView) convertView.findViewById(R.id.live);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
break;
case TYPE_SEPARATOR:
convertView = mInflater
.inflate(R.layout.theme_banner, null);
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
break;
}
convertView.setTag(holder);
} else {
holder = (NewsViewHolder) convertView.getTag();
}
switch (type) {
case TYPE_ITEM:
if(live_type == 1){
holder.img_flag.setVisibility(0);
holder.live.setText("live");
}else{
holder.live.setText("not_live");
holder.img_flag.setVisibility(8);
}
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_ID)));
holder.flag.setText("normal");
break;
case TYPE_SEPARATOR_ALTERNATE:
if(live_type == 1){
holder.img_flag.setVisibility(0);
holder.live.setText("live");
//Log.e("--itempostion Live", "live");
}else{
holder.live.setText("not_live");
holder.img_flag.setVisibility(8);
}
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_ID)));
holder.flag.setText("normal");
Log.e("karthik", "karthik "+com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL));
break;
case TYPE_SEPARATOR:
Log.e("--banner Images", com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_BANNER_ID)));
holder.flag.setText(newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
break;
}
holder.name.setText(String.valueOf(newsList.get(position).get(All_link.TAG_NEWS_TITLE)));
return convertView;
}
}
My guess is because you call setAdapter everytime you pull to refresh, in onPostExecute :
mAdapter = new MyCustomAdapter(getActivity(), newsList);
mAdapter.notifyDataSetChanged();
refreshable_listView.setAdapter(mAdapter);
refreshable_listView.onRefreshComplete();
Try to move :
mAdapter = new MyCustomAdapter(getActivity(), newsList);
refreshable_listView.setAdapter(mAdapter);
To your onCreateView because you only need to initialize and set the adapter once.
You just need to call those in your onPostExecute, because you called newsList.add in the onBackground :
mAdapter.notifyDataSetChanged();
refreshable_listView.onRefreshComplete();
The above's code will only change the data on your ListView, without re-initializing anything.
I have a Custom ArrayAdapter that has a getview method, the thing is that method is being called for different views if i scroll down and up, and this make this views load again (e.g. downloading an image).
In my ListActivity class, i only call adapter = new Adapter... and list.setAdapter() , after i download and parse a json (im using AQuery library).
public class AdapterPostagem extends ArrayAdapter<Postagem>{
Context context;
LayoutInflater inflater;
boolean memCache = false;
boolean fileCache = true;
String BASE_URL = "https://graph.facebook.com/";
public AdapterPostagem(Context context, int textViewResourceId,
List<Postagem> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
inflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public class ViewHolder{
TextView postagem;
TextView likes;
ImageView foto;
View view;
TextView like;
TextView share;
ProgressBar pb;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
Postagem p = new Postagem();
p = getItem(position);
AQuery aq;
UrlImageViewHelper uHelper = new UrlImageViewHelper();
uHelper.setUseBitmapScaling(false);
if (convertView == null){
convertView = inflater.inflate(R.layout.postagem, parent, false);
Log.d("conv", "convertView_null");
Postagens posts = new Postagens();
Postagens.EndlessScrollListener end = posts.new EndlessScrollListener();
aq = new AQuery(convertView);
aq.scrolled(end);
holder = new ViewHolder();
holder.foto = (ImageView)convertView.findViewById(R.id.foto);
holder.postagem = (TextView)convertView.findViewById(R.id.postagem);
holder.like = (TextView)convertView.findViewById(R.id.likes);
holder.share = (TextView)convertView.findViewById(R.id.shares);
//holder.pb = (ProgressBar)convertView.findViewById(R.id.progress);
if (!p.getUrl_foto().equals("")){
getUrlPhoto(holder.foto, uHelper,p.getId(), aq, R.id.foto);
}else{
holder.foto.setVisibility(View.GONE);
}
holder.postagem.setText(p.getPostagem());
convertView.setTag(holder);
}else{
Log.d("conv", "convertView");
holder = (ViewHolder)convertView.getTag();
Postagens posts = new Postagens();
Postagens.EndlessScrollListener end = posts.new EndlessScrollListener();
aq = new AQuery(convertView);
aq.scrolled(end);
holder.foto = (ImageView)convertView.findViewById(R.id.foto);
holder.postagem = (TextView)convertView.findViewById(R.id.postagem);
if (!p.getId().equals("")){
getUrlPhoto(holder.foto, uHelper,p.getId(), aq, R.id.foto);
}else{
holder.foto.setVisibility(View.GONE);
}
//uHelper.setUrlDrawable(holder.foto, p.getUrl_foto());
setTextWithURL(holder.postagem, p.getPostagem());
//holder.postagem.setText(p.getPostagem());
//holder.likes.setText(Integer.toString(p.getLikes()));
}
return convertView;
}
public void setTextWithURL(TextView t, String s){
String [] parts = s.split("\\s");
String finals = "";
for( String item : parts ) try {
URL url = new URL(item);
// If possible then replace with anchor...
finals = finals + (""+ url + " " );
} catch (MalformedURLException e) {
// If there was an URL that was not it!...
finals = finals + item + " ";
System.out.print( item + " " );
}
t.setClickable(true);
t.setPaintFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
t.setMovementMethod(LinkMovementMethod.getInstance());
t.setText(Html.fromHtml(finals));
}
public void setPhoto(ImageView img, UrlImageViewHelper uHelper, AQuery aq, JSONObject json, int id){
String URL = "";
try {
URL = json.getJSONArray("images").getJSONObject(1).getString("source");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//uHelper.setUrlDrawable(img, URL);
// File file = aq.getCachedFile(URL);
// Bitmap bp = BitmapFactory.decodeFile(file.getPath());
// if (bp != null){
//
// img.setImageBitmap(bp);
//
// }else{
aq.id(img).image(URL, memCache, fileCache, 0, 0, null, 0, AQuery.RATIO_PRESERVE);
//
// }
}
public void getUrlPhoto(final ImageView img, final UrlImageViewHelper uHelper, String id, final AQuery aq, final int id_photo){
aq.ajax(BASE_URL + id, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
Log.d("url", url);
if(json != null){
setPhoto( img, uHelper, aq, json, id_photo);
}else{
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
}
}
I want to the change the text of the button which was clicked in a getView function. The text is changed but when the view is scrolled the text of other buttons which the same id is also changed. I don't want that. I want only the text of the button which was clicked to be changed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int i=position;
List dialog = DialogList.get(i);
final Object memid = dialog.get(2).toString();
final String dialogid = dialog.get(3).toString();
final String dialogtype = dialog.get(4).toString();
ImageView imageViews;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(getContext());
convertView = layoutInflator.inflate(R.layout.invite_friends_list, null);
holder = new ViewHolder();
holder.friendsname = (TextView) convertView.findViewById(R.id.friendsname);
holder.profimage = (ImageView) convertView.findViewById(R.id.member_image);
holder.assign = (Button) convertView.findViewById(R.id.btnInvite);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
holder.friendsname.setText(user_name);
holder.assign.setTag(holder);
holder.assign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("assigntext", holder.assign.getText().toString());
SharedPreferences prfs = _context.getSharedPreferences("MyPref",
Context.MODE_PRIVATE);
String token = prfs.getString("apptoken", "");
String url = null;
if(dialogtype.equals("V"))
{
url = "http://www.jjhjjkh.com/index.php?/alkjlkjlk/dialog/invjlkjlkjklialogmember?apptoken="
+ token + "&dialogid=" + dialogid+"&mid="+memid.toString();
}
if(dialogtype.equals("P"))
{
url = "http://www.ckjhuihiuhiu.com/index.php?/kjij/dialog/inviuhuihuihuimember?apptoken="
+ token + "&dialogid=" + dialogid+"&mid="+memid.toString();
}
List<String> urlList = new ArrayList<String>();
Log.d("cat",url.toString());
// JSON Node names
String TAG_DETAILS = "invitemembers";
String TAG_MSG = "msg";
// contacts JSONArray
JSONArray dialogpublish = null;
JSONArray dialogs = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
// Log.d("cat",json.toString());
try {
dialogpublish = json.getJSONArray(TAG_DETAILS);
// Log.d("apptoken",login.toString());
for (int i = 0; i < dialogpublish.length(); i++) {
JSONObject d = dialogpublish.getJSONObject(i);
String msg = d.getString(TAG_MSG);
//dialogs = d.getJSONArray("updatedialog");
if (msg.equals("success")) {
// ViewHolder mH = (ViewHolder)view.getTag();
//Integer currentPos = view.getTag();
String mem_id= view.getTag().toString();
if(mem_id.equals(memid))
{
Toast.makeText(_context, "Member invited Succesfully",Toast.LENGTH_LONG).show();
ViewHolder mH = (ViewHolder)view.getTag();
mH.assign.setText("Invited");
}
//view.setText("Invited");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess that is happenning because you are using the viewholder pattern. The viewholder pattern tends to cache views for performance optimization. try to write the adapter without using viewholder. If the list view items arent large in numbers.
Create a new HashMap in Adapter :
private HashMap<Integer, String> buttonTitleMap=new HashMap<Integer, String>();
Create a function getButtonTitle as below in Adapter :
private String getButtonTitle(int position){
if(buttonTitleMap.containsKey(position)){
return buttonTitleMap.get(position);
}else{
return "Your Normal Button text";
}
}
Then in getView() of Adapter, befor returning convertView, call :
....
holder.assign.setText(getButtonTitle(position));
holder.friendsname.setTag(position);
return convertView;
}
When the Button is clicked, you can get the list item position of the button. So what you need to do is to change the button title as you do before and also update the hashmap with the same value :
holder.assign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
mH.assign.setText("Invited");
int position = (int)mH.friendsname.getTag();
buttonTitleMap.put(position,"Invited");
....
}
}
You are done.
Try
String mem_id= view.getTag().toString();
if(mem_id.equals(memid))
{
Toast.makeText(_context, "Member invited Succesfully",Toast.LENGTH_LONG).show();
((Button)view).setText("Invited");
}
I am newer to the fragments. In oncreate method i pass this value to Appetizerlist. but it shows an error. How to clear the error? Please help me.
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.applistviewfragment, null);
list = (ListView) view.findViewById(R.id.list);
return view;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(this, json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
i Given whole code i want custom listview using listfragments
In the above code in this line, I'm getting an error at adapter = new Appetizerlist(this, json); Please tell me how to solve the problem. Help me.
as onCreate called before onCreateView so list will null there in onCreate ...........
http://developer.android.com/guide/topics/fundamentals/fragments.html
in oncreate
list.setAdapter(adapter);
in onCreateView you initlized that
list = (ListView) view.findViewById(R.id.list);
......
so move this line list.setAdapter(adapter); in onCreateView
You have error in following line.
adapter = new Appetizerlist(this, json);
Change it to
adapter = new Appetizerlist(getActivity().getApplicationContext(), json);