its is working fine but its taking too much time for arraylist size 7000 . is there any other way to display this report in fast way.to display 1000 row its taking 3 minutes which very huge time .can we use another way to make this report instead of uving view inflate with layout which will work fast.Thank in advance
spinner=(Spinner)findViewById(R.id.searchableSpinnerLedgerReport);
spinner.setAdapter(new ArrayAdapter<>(LedgerReportActivity.this,R.layout.support_simple_spinner_dropdown_item,numberlist));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position==-1){
Toast.makeText(getApplicationContext(), "plz select number", Toast.LENGTH_SHORT).show();
}
else {
String snumber= parent.getItemAtPosition(position).toString();
ArrayList<HashMap<String, String>> myList=ledgerReportDataCon.getSelectedReport(snumber); //size of comming data is 7000
Log.d("size of report list", String.valueOf(myList.size()));
// Log.d("name",snumber);
if(Float.parseFloat (myList.get(0).get(ConstLedgerReport.key_cLOSING))>0)
{
tclosingblnc.setText(myList.get(0).get(ConstLedgerReport.key_cLOSING));
}
else {
tclosingblnc2.setText(myList.get(0).get(ConstLedgerReport.key_cLOSING));
}
if(Float.parseFloat(myList.get(0).get(ConstLedgerReport.key_oPENING))>0)
{
topeningblnc.setText(myList.get(0).get(ConstLedgerReport.key_oPENING));
}
else {
topeningblnc2.setText(myList.get(0).get(ConstLedgerReport.key_oPENING));
}
for(int i=0;i<myList.size();i++) {
String ledgertype=myList.get(i).get(ConstLedgerReport.key_lEDGERTYPE);
String narration=myList.get(i).get(ConstLedgerReport.key_nARRATION);
final View partyView = getLayoutInflater().inflate(R.layout.ledger_report_item, null, false);
LinearLayout headerLayout=(LinearLayout) partyView.findViewById(R.id.headder);
TextView particular = (TextView) partyView.findViewById(R.id.particular);
TextView vchType = (TextView) partyView.findViewById(R.id.vchType);
TextView debit = (TextView) partyView.findViewById(R.id.debit);
TextView credit = (TextView) partyView.findViewById(R.id.credit);
TextView date = (TextView) partyView.findViewById(R.id.date);
TextView vchno = (TextView) partyView.findViewById(R.id.vchno);
particular.setText( myList.get(i).get(ConstLedgerReport.key_pARTICULARS));
vchType.setText( myList.get(i).get(ConstLedgerReport.key_vCHTYPE));
date.setText( myList.get(i).get(ConstLedgerReport.key_vCHDATE));
vchno.setText( myList.get(i).get(ConstLedgerReport.key_vCHNUM));
if (ledgertype.equalsIgnoreCase("Dr"))
{
debit.setText( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
totaldebit=totaldebit+Float.parseFloat( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
}
else if (ledgertype.equalsIgnoreCase("Cr"))
{
credit.setText( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
totalcredit=totalcredit+Float.parseFloat( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
}
listViewLayout.addView(partyView);
String[] itemArr=narration.split("~");
// Log.d("first array is ....: ", Arrays.toString(itemArr));
headerLayout.setVisibility(View.INVISIBLE);
if(!narration.equalsIgnoreCase("Array")) {
for (int j = 0; j < itemArr.length; j++) {
headerLayout.setVisibility(View.VISIBLE);
final View itemListView = getLayoutInflater().inflate(R.layout.ledger_report_itemlist, null, false);
TextView iname = (TextView) itemListView.findViewById(R.id.iname);
TextView iqty = (TextView) itemListView.findViewById(R.id.iqty);
TextView iunit = (TextView) itemListView.findViewById(R.id.iunit);
TextView irate = (TextView) itemListView.findViewById(R.id.irate);
TextView itotal = (TextView) itemListView.findViewById(R.id.itotal);
String temp1 = itemArr[j].replace("]][[", ",");
String temp2 = temp1.replace("[[", "");
String temp3 = temp2.replace("]]", "");
String[] itemArrList = temp3.split(",");
// Log.d("second array is ....: ", Arrays.toString(itemArrList));
iname.setText(itemArrList[0]);
iqty.setText(itemArrList[4]);
iunit.setText(itemArrList[1]);
irate.setText(itemArrList[5]);
itotal.setText(itemArrList[7]);
listViewLayout.addView(itemListView);
// Log.d("created view msz", String.valueOf(j));
}
}
}
tdebit.setText(String.valueOf(totaldebit));
tcredit.setText(String.valueOf(totalcredit));
}
}
enter image description here
Related
I'm using ExpandapbeListView its work perfect all expand and collapse but I just want to update only particular child item here when I click on plus value should be update in EditText and I don't want to use notifyDatasetChanged() Just want to update only particular field and also i should able to update EditText directly. It can have multiple child item.
Ex: Colgate may have multiple child Item like 100gm,200gm,300gm
So when I click on Plus It should able to get Id of EditText and Update Quantity
#Override
public View getChildView(int productPos, int weightPos, boolean b, View plusMinusView, ViewGroup viewGroup) {
if (plusMinusView == null) {
csHolder = new ChildHolder();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
plusMinusView = inflater.inflate(R.layout.orders_products_plus_minus_design, null);
}
csHolder.minQty = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitMinQtyTxt);
csHolder.totalPriceTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitTotalPriceTxt);
csHolder.weightTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitWeightTxt);
csHolder.unitPrice = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitUnitPriceTxt);
csHolder.totalTaxTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitTotalTaxTxt);
csHolder.netPriceTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitNetPriceTxt);
csHolder.orderQtyEdit = (CustomEditText) plusMinusView.findViewById(R.id.orderProducts_orderQtyTxt);
csHolder.plusTxt = (RelativeLayout) plusMinusView.findViewById(R.id.orderProducts_plusTxtLay);
csHolder.minusTxt = (RelativeLayout) plusMinusView.findViewById(R.id.orderProducts_minusTxtLay);
plusMinusView.setTag(productPos + "_" + weightPos);
String tag = "weight_" + productPos + "_" + weightPos;
csHolder.orderQtyEdit.setTag(tag);
csHolder.plusTxt.setTag(tag);
csHolder.minusTxt.setTag(tag);
//csHolder.plusTxt.setOnClickListener(weightClick);
//csHolder.minusTxt.setOnClickListener(weightClick);
final View finalPlusMinusView = plusMinusView;
csHolder.plusTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
csHolder.orderQtyEdit.setText("5");
}
});
if(!csStatus.equalsIgnoreCase("DRAFT")) {
csHolder.plusTxt.setVisibility(View.GONE);
csHolder.minusTxt.setVisibility(View.GONE);
csHolder.orderQtyEdit.setEnabled(false);
}
else
{
csHolder.plusTxt.setVisibility(View.VISIBLE);
csHolder.minusTxt.setVisibility(View.VISIBLE);
csHolder.orderQtyEdit.setEnabled(true);
}
try
{
csHolder.orderQtyEdit.addTextChangedListener(new MyTextWatcher(csHolder.orderQtyEdit));
JSONObject weighObj = csMainArr.getJSONObject(productPos).getJSONArray("weights").getJSONObject(weightPos);
if(weighObj.has("unit"))
{
csHolder.weightTxt.setText(weighObj.getString("unit"));
}
if (weighObj.has("order_qty") == false)
weighObj.put("order_qty", "0");
if (weighObj.has("sell_price") == false)
weighObj.put("sell_price", "0");
if (weighObj.has("order_qty") == false)
{
csHolder.totalPriceTxt.setText("0.00");
csHolder.totalTaxTxt.setText("0.00");
csHolder.netPriceTxt.setText("0.00");
}
else {
int qty = 0;
double sellPrice = 0.00;
float tax = 0f;
double totalPrice = 0.00;
double totalTax = 0.00;
double netPrice = 0.00;
if(csStatus.equals("DRAFT")) {
qty = Integer.parseInt(weighObj.getString("order_qty"));
sellPrice = weighObj.getDouble("sell_price");
}
else
{
qty = Integer.parseInt(weighObj.has("qty") ? weighObj.getString("qty"):"0");
sellPrice = weighObj.getDouble("unit_price");
}
tax = Float.parseFloat(csMainArr.getJSONObject(productPos).has("tax") ? csMainArr.getJSONObject(productPos).getString("tax") : "0");
totalPrice = qty*sellPrice;
totalTax = (totalPrice*tax)/100;
netPrice = totalPrice + totalTax;
csHolder.totalPriceTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",totalPrice));
csHolder.totalTaxTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",totalTax));
csHolder.netPriceTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",netPrice));
}
csHolder.orderQtyEdit.isValueChangeMySelf = true;
if(csStatus.equals("DRAFT"))
csHolder.orderQtyEdit.setText(weighObj.getString("order_qty"));
else
csHolder.orderQtyEdit.setText(weighObj.has("qty")?weighObj.getString("qty"):"0");
/*if(weightPos == iClickedItem) {
csHolder.orderQtyEdit.requestFocus();
}
else {
csHolder.orderQtyEdit.clearFocus();
}*/
if(csStatus.equals("DRAFT"))
csHolder.unitPrice.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",weighObj.has("sell_price")?weighObj.getDouble("sell_price") : 0.00));
else
csHolder.unitPrice.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",weighObj.has("unit_price")?weighObj.getDouble("unit_price") : 0.00));
csHolder.minQty.setText(weighObj.has("min_order_qty")?weighObj.getString("min_order_qty"):"0");
//View line = (View) plusMinusView.findViewById(R.id.orderProducts_submitDividerLine);
//if(isLast)
// line.setVisibility(View.GONE);
}
catch(Exception e)
{
}
return plusMinusView;
}
I have chat app
In custom array adapter. I set random colors to usernames for each message with this code:
String[] array = context.getResources().getStringArray(R.array.username_colors);
randomColor = array[new Random().nextInt(array.length)];
nameTextView.setTextColor(Color.parseColor(randomColor));
When new message arrive I add it to listview, and call adapter.notifyDataSetChanged();
This causes recoloring existing usernames in messages each time.
How can I prevent recoloring existing items in listview when calling adapter.notifyDataSetChanged();
Edit 1
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessageElement el = list.get(position);
ViewHolder holder = null;
NewMessagesLabelHolder labelHolder = null;
if (convertView == null) {
convertView = el.getView(inflater, parent);
if (el.isMessage()) {
holder = new ViewHolder();
holder.messageLayout = (RelativeLayout) convertView.findViewById(R.id.message_container);
holder.messageContent = (LinearLayout) convertView.findViewById(R.id.message_content);
holder.bottomIndicator = (LinearLayout) convertView.findViewById(R.id.bottom_indicators);
holder.dateTextView = (TextView) convertView.findViewById(R.id.message_date);
holder.timeAgo = (TextView) convertView.findViewById(R.id.time_ago);
holder.nameTextView = (TextView) convertView.findViewById(R.id.user_name);
holder.likesCountTextView = (TextView) convertView.findViewById(R.id.likes_count);
holder.likesLabelImageView = (ImageView) convertView.findViewById(R.id.likes_label);
holder.spamCountTextView = (TextView) convertView.findViewById(R.id.spam_count);
holder.spamLabelImageView = (ImageView) convertView.findViewById(R.id.spam_label);
holder.avatarImageView = (ImageView) convertView.findViewById(R.id.avatar);
holder.statusImageView = (ImageView) convertView.findViewById(R.id.delivered_label);
holder.progressBar = (ProgressBar) convertView.findViewById(R.id.progress_bar);
holder.errorSign = (ImageView) convertView.findViewById(R.id.error_sign);
holder.spamSign = (ImageView) convertView.findViewById(R.id.spam_sign);
holder.bookmarkLabel = (ImageView) convertView.findViewById(R.id.bookmark_label);
holder.topIndicators = (LinearLayout) convertView.findViewById(R.id.topIndicators);
convertView.setTag(holder);
}
if (el.isNewMessagesLabel()) {
convertView = inflater.inflate(R.layout.chat_new_messages_label_layout, parent, false);
labelHolder = new NewMessagesLabelHolder();
labelHolder.newMessagesLabel = (TextView) convertView.findViewById(R.id.new_messages_label);
convertView.setTag(labelHolder);
}
} else {
if (el.isMessage()) {
holder = (ViewHolder) convertView.getTag();
}
if (el.isNewMessagesLabel()) {
labelHolder = (NewMessagesLabelHolder) convertView.getTag();
}
}
if (el.isMessage()) {
Message currentMessage = (Message) el;
drawMessage(holder, currentMessage, position);
}
if (el.isNewMessagesLabel()) {
NewMessagesLabel messagesLabel = (NewMessagesLabel) el;
drawNewMessagesLabel(labelHolder, messagesLabel);
}
return convertView;
}
private void drawMessage(ViewHolder holder, Message message, int position) {
String date = message.getCreatedAt();
String formattedDate = DateHelper.getInstance(context).formatDate("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "HH:mm", date);
String userName = message.getUserName();
holder.likesLabelImageView.setVisibility(View.GONE);
holder.likesCountTextView.setVisibility(View.GONE);
holder.spamCountTextView.setVisibility(View.GONE);
holder.spamLabelImageView.setVisibility(View.GONE);
holder.bookmarkLabel.setVisibility(View.GONE);
holder.statusImageView.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.statusImageView.setVisibility(View.GONE);
holder.errorSign.setVisibility(View.GONE);
holder.spamSign.setVisibility(View.GONE);
holder.timeAgo.setVisibility(View.GONE);
holder.timeAgo.setText("");
holder.messageLayout.setAlpha(1f);
holder.topIndicators.setVisibility(View.VISIBLE);
if (message.isNewDay()) {
holder.timeAgo.setVisibility(View.VISIBLE);
String dayDate = DateHelper.getInstance(context).formatDate("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "MMMM d, yyyy", date);
//String dayDate = getTimeAgo(mHelper.millisFromString(message.getCreatedAt()), context);
holder.timeAgo.setText(dayDate);
}else{
holder.timeAgo.setVisibility(View.GONE);
}
holder.avatarImageView.setImageResource(R.drawable.com_facebook_profile_default_icon);
if (GrouviDatabaseManager.getInstance(context).getCurrentUser().getId() == message.getUserId()) {
userName = USERNAME_ME;
if (message.getStatus() != null && message.getStatus().equals(Message.MSG_STATUS_SEND)) {
holder.statusImageView.setBackgroundResource(R.drawable.icon_chat_message_delivered);
holder.statusImageView.setVisibility(View.VISIBLE);
}
if (message.getStatus() != null && message.getStatus().equals(Message.MSG_STATUS_SENDING)) {
holder.progressBar.setVisibility(View.VISIBLE);
}
if (message.getStatus() != null && message.getStatus().equals(Message.MSG_STATUS_LOCAL)) {
holder.statusImageView.setBackgroundResource(R.drawable.icon_chat_message_delivered);
holder.statusImageView.setVisibility(View.VISIBLE);
}
if (message.getStatus() == null || message.getStatus().equals(Message.MSG_STATUS_ERROR)) {
holder.messageLayout.setAlpha(0.4f);
holder.errorSign.setVisibility(View.VISIBLE);
}
}
if (message.getSpamCount() > 0 && currentMode == MODE_NORMAL) {
holder.messageLayout.setAlpha(0.4f);
holder.spamSign.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
holder.messageContent.setLayoutParams(params);
holder.spamCountTextView.setText(Integer.toString(message.getSpamCount()));
holder.spamCountTextView.setVisibility(View.VISIBLE);
holder.spamLabelImageView.setVisibility(View.VISIBLE);
} else {
holder.messageLayout.setAlpha(1f);
holder.spamSign.setVisibility(View.GONE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
holder.messageContent.setLayoutParams(params);
}
if (currentMode == MODE_REPORT) {
String timeAgo = getTimeAgo(mHelper.millisFromString(message.getCreatedAt()));
holder.timeAgo.setText(timeAgo);
holder.timeAgo.setVisibility(View.VISIBLE);
}
if (message.getUserAvatar() != null && !message.getUserAvatar().isEmpty()) {
try {
Picasso
.with(context)
.load(message.getUserAvatar())
.error(R.drawable.com_facebook_profile_default_icon)
.placeholder(R.drawable.com_facebook_profile_default_icon)
.into(holder.avatarImageView);
} catch (Exception e) {
Log.e("Main", e.getMessage(), e);
}
}
colorUsername(holder, message, userName);
holder.nameTextView.setText(userName);
holder.dateTextView.setText(formattedDate);
if (message.getLikesCount()>0) {
holder.likesCountTextView.setText(Integer.toString(message.getLikesCount()));
holder.likesCountTextView.setVisibility(View.VISIBLE);
holder.likesLabelImageView.setVisibility(View.VISIBLE);
}
if (message.isBookmarked()) {
holder.bookmarkLabel.setVisibility(View.VISIBLE);
}
List<MessageComponent> messageComponentList;
messageComponentList = message.getMessageComponents();
drawMessageContent(holder, messageComponentList, message);
holder.nameTextView.setTag(position);
holder.avatarImageView.setTag(position);
holder.nameTextView.setOnClickListener(userClickListener);
holder.avatarImageView.setOnClickListener(userClickListener);
// hang empty onLingClickListener to display context menu when
// long click on whole message
holder.nameTextView.setOnLongClickListener(longClickListener);
holder.avatarImageView.setOnLongClickListener(longClickListener);
}
private void colorUsername(ViewHolder holder, Message message, String userName) {
String randomColor = prevColor;
if (userName.equals(USERNAME_ME)){
randomColor = "#000000";
}else if (message.getUserId()!=prevMsgUserID) {
do {
String[] array = context.getResources().getStringArray(R.array.username_colors);
randomColor = array[new Random().nextInt(array.length)];
}while (prevColor.equals(randomColor));
}
holder.nameTextView.setTextColor(Color.parseColor(randomColor));
prevColor = randomColor;
prevMsgUserID = message.getUserId();
}
You should keep color in the data class, for example in the Message class, or keep Map in the adapter, that maps Message to Color. Then randomly create a color, when it doesn't present in the map. or use the color, if it present in the map. Using a map is good solution than keeping in the data class, when the color doesn't related to message, when it is not a message property, so in that case, a good solution is a keeping it in the adapter class, in the map, for example
private Map<Message, String> colorsMap = new HashMap<Message, String>();
private void colorUsername(ViewHolder holder, Message message, String userName) {
String randomColor;
if(colorsMap.contains(message)) {
randomColor = colorsMap.get(message);
}
else {
if (userName.equals(USERNAME_ME)){
randomColor = "#000000";
}else if (message.getUserId()!=prevMsgUserID) {
do {
String[] array = context.getResources().getStringArray(R.array.username_colors);
randomColor = array[new Random().nextInt(array.length)];
}while (prevColor.equals(randomColor));
}
colorsMap.put(message, randomColor);
}
holder.nameTextView.setTextColor(Color.parseColor(randomColor));
}
Basically you have to create a Collection of user data model.
Like ArrayList<UserModel> arr = new ArrayList<UserModel>();
User Model can contain-> userId,userColor,groupId(if group chat supported) and map this model with you DB.
Means you have to make a column in db and add userBgColor in user table and map it with the model and this model in array list and supply the array list to your custom adapter .
Your can use ORMLite for rational mapping .
Then in getView()
{
UserModel model = arr.get(position);
String color = user.getUserColor();
}
i tried to add two textViews to list item.that data get from list. when the list print, it display correctly. But in list view its not print correctly. Can anyone help me?
This is the custom adapter class.
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
final String text1 = listData.get(0);
final String text2 = listData.get(1);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
This is the activity code.
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
I want to add user name, below of that it's rate.
This is should be the output list.
01-23 11:59:09.102: D/Data(4873): omali 3.5
01-23 11:59:09.102: D/Data(4873): sunil 2
01-23 11:59:09.102: D/Data(4873): kuma#fh.com 1.5
01-23 11:59:09.102: D/Data(4873): fhhhy#ghj.com 0.5
First of all, the way you are building the list, it will never work, since you are deleting it and creating a new one in every iteration, so when you create the adapter, in the listyou only have the last item.
I would do:
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>(); //added
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
//removed listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(new Pair<String,String>(userName,ratOut ));//added
//removed listData.add(userName);
//removed listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
Then, in the custom adapter class, you retrieve that data simply by
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
//only this 3 lines change
Pair<String,String> item= listData.get(arg0);
final String text1 = item.first;
final String text2 = item.second;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
You are always printing the wrong data, regardless of the position of the item
final String text1 = listData.get(0);
final String text2 = listData.get(1);
So Better take the Different lists of the username and ratOut and display the data
final String text1 = userNameListData.get(arg0);
final String text2 = ratOutListData.get(arg0);
Here arg0 is the position
Replace this:
final String text1 = listData.get(0);
final String text2 = listData.get(1);
with:
final String text1 = listData.get(2*arg0);
final String text2 = listData.get((2*arg0)+1);
change to:
final String text1 = listData.get(arg0*2);
final String text2 = listData.get(arg0*2+1);
and override:
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size()/2;
}
As you are adding both the text in one arraylist 0,1 belong to first item and 2,3 belong to 2nd and so on.
Also size of the list view item would be half of the size of arraylist.
Try this.
also change this:
listData = new ArrayList<String>();//<--out side for loop
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
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");
}
Let's say, I have two textviews, TextView A and B.
when I click on A, I need to change both textviews;
When I click on B, I need it to do something else.
I used the setTag(key,A); and setTag(key,B); The textView A changed correctly but the textView B is null. And when I click on B it works.
Here is my code :
public class CustomeAdapterHowComment extends ArrayAdapter<ItemsHowComment> {
Context context;
ItemsHowComment items;
List<LikersComment> likeItems;
List<ItemsHowComment> Items1;
Bitmap bitmap;
String imageUser = "";
String filePath_Image = "/Pictures/jehad/joj/";
String user_id = "1510";
String secret_id = "789654120";
View v;
String onclick = " ";
int x;
String table = "10";
String target = "";
String type = "";
DataBaseHandler dbobj;
public static String server_List_of_Comments = "https://www.ashabe.comt";
public static String server_Comment_like = "https://www.ashabe.com/";
public static String server_Comment_like_remove = "https://www.ashabe.com/";
public static String server_Comment_Delte = "https://www.ashabe.com/";
public static String server_Comment_likers = "https://www.ashabe.com/";
String response;
public CustomeAdapterHowComment(Context context, int textViewResourceId,
List<ItemsHowComment> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("View ", "View>>>>>>>>");
commentholder h = null;
v = convertView;
items = getItem(position);
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
v = vi.inflate(R.layout.how_comment_list, null);
h = new commentholder();
h.img = (ImageView) v.findViewById(R.id.CommentImg);
h.name = (TextView) v.findViewById(R.id.CommentName);
h.commentBody = (TextView) v.findViewById(R.id.CommentBody);
h.like = (TextView) v.findViewById(R.id.CommentLike);
h.numoflike = (TextView) v.findViewById(R.id.CommentNumOfLike);
v.setTag(h);
} else {
h = (commentholder) v.getTag();
}
imageUser = items.getUserId() + items.getRand();
boolean flag_ImagePath = Methods.checkIfImage_DirExists(filePath_Image
+ imageUser);
if (flag_ImagePath == true) {
Log.v("flag_ImagePath", String.valueOf(flag_ImagePath));
bitmap = Methods.displayBitmapImage(imageUser);
h.img.setImageBitmap(bitmap);
}
h.commentBody.setText(items.getCommentBody());
h.name.setText(items.getName());
if (items.getiLike().equals("0")) {
h.like.setText("Like");
}
if (items.getiLike().equals("1")) {
h.like.setText("Unlike");
}
if (items.getNumOfLike().equals("0")) {
h.numoflike.setText("0");
} else {
h.numoflike.setText(items.getNumOfLike());
}
h.name.setOnClickListener(listener);
h.name.setTag(R.id.CommentName, h.name);
h.name.setTag(position);
h.numoflike.setOnClickListener(listener);
h.numoflike.setTag(R.id.CommentNumOfLike, h.numoflike);
h.numoflike.setTag(position);
h.like.setOnClickListener(listener);
h.like.setTag(R.id.CommentLike, h.like);
h.like.setTag(position);
h.img.setOnClickListener(listener);
h.img.setTag(R.id.CommentImg, h.img);
h.img.setTag(position);
return v;
}
private OnClickListener listener = new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View view) {
final int id = view.getId();
type = " ";
CommentEvents t = new CommentEvents();
t.execute();
switch (id) {
case R.id.CommentImg:
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + Items1.get(x).getName());
Toast.makeText(getContext(), Items1.get(x).getName(),
Toast.LENGTH_SHORT).show();
break;
case R.id.CommentName:
// ///profile
try {
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
TextView tv = (TextView) view.getTag(R.id.CommentName);
Log.v("value", x + Items1.get(x).getName());
Toast.makeText(getContext(), Items1.get(x).getName(),
Toast.LENGTH_SHORT).show();
// String user = Items1.get(x).getUserId();
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
break;
case R.id.CommentLike:
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + "");
TextView like = (TextView) view.getTag(R.id.CommentLike);
target = Items1.get(x).getCommentId().toString();
type = "like";
CommentEvents s = new CommentEvents();
s.execute(user_id, secret_id, table, target);
if (Items1.get(x).getiLike().equals("0")) {
like.setText("Unlike");
onclick = "true";
} else if (Items1.get(x).getiLike().equals("1")) {
like.setText("Like");
onclick = "true";
}
case R.id.CommentNumOfLike:
// ////howlike
if (onclick.equals("true")) {
x = (Integer) view.getTag();
TextView numofLike = (TextView) view
.getTag(R.id.CommentNumOfLike);
if (numofLike != null) {
if (Items1.get(x).getiLike().equals("0")) {
Log.e("getNumOfLike____unlike", Items1.get(x)
.getNumOfLike());
int num = Integer.parseInt(Items1.get(x)
.getNumOfLike().toString());
num = num + 1;
Log.e("numberunlike", num + "");
numofLike.setText(num + "");
} else if (Items1.get(x).getiLike().equals("1")) {
Log.e("getNumOfLike_______like", Items1.get(x)
.getNumOfLike());
int num = Integer.parseInt(Items1.get(x)
.getNumOfLike().toString());
num = num - 1;
Log.e("numberlike", num + "");
numofLike.setText(num + "");
}
onclick=" "; }
} else {
try {
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + "");
target = Items1.get(x).getCommentId().toString();
type = "numoflike";
CommentEvents r = new CommentEvents();
r.execute(user_id, secret_id, table, target);
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
}
}
}
};
Use
View view = v.getParent();
and then try to initialize views with view in onClick
You can set Tag
h.name.setOnClickListener(listener);
h.name.setTag(h.numoflike); // use setTag only once
h.numoflike.setOnClickListener(listener);
h.numoflike.setTag(h.name); // use setTag only once
Then in on click
public void onClick(View v) {
switch(v.getId())
{
case R.id.CommentName :
TextView tv1 = (Button) v.getTag();
TextView tv2 = (TextView) v;
tv1.setText("clicked");
tv2.setText("clicked");
break;
case R.id.CommentNumOfLike :
//do something
break;
}
}
Or in onClick Initialize yours views
View view = v.getParent();
TextView tv = view.findVIewById(R.id.CommentName);
TextView tv1 = view.findVIewById(R.id.CommentNumOfLike);
tv.setText("clicked");
tv1.setText("clicked");