how use two getIntent in activity? - android

I need to get data from two activity by get intent but is not work.
this activiy1:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ShowDat.class);
modify_intent.putExtra("title1", title);
modify_intent.putExtra("desc1", desc);
modify_intent.putExtra("id1", id);
startActivity(modify_intent);
}
});
and this activity2:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ShowDat.class);
modify_intent.putExtra("title2", title);
modify_intent.putExtra("desc2", desc);
modify_intent.putExtra("id2", id);
startActivity(modify_intent);
}
});
and this activity than receive data:
TextView idTextView = (TextView) findViewById(R.id.id);
TextView titleTextView = (TextView) findViewById(R.id.title);
TextView descTextView = (TextView) findViewById(R.id.desc);
Intent intent = getIntent();
if(intent != null) {
intent = getIntent();
String id = intent.getStringExtra("id1");
String name = intent.getStringExtra("title1");
String desc = intent.getStringExtra("desc1");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
else {
intent = getIntent();
String id = intent.getStringExtra("id2");
String name = intent.getStringExtra("title2");
String desc = intent.getStringExtra("desc2");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
i try to use this code but like above code, just on put extra receive and other not work:
TextView idTextView = (TextView) findViewById(R.id.id);
TextView titleTextView = (TextView) findViewById(R.id.title);
TextView descTextView = (TextView) findViewById(R.id.desc);
Intent intent = getIntent();
if(getIntent() !=null) {
String id = intent.getStringExtra("id1");
String name = intent.getStringExtra("title1");
String desc = intent.getStringExtra("desc1");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
else {
String id = intent.getStringExtra("id2");
String name = intent.getStringExtra("title2");
String desc = intent.getStringExtra("desc2");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
please help.

first you need to check like this
if(getIntent().hasExtra("key_1"))
{
String data = getIntent().getString("key_1");
}
else if(getIntent().hasExtra("key_2"))
{
String msg = getIntent().getString("key_2");
}
......

You can do that with two way.
1)if(getIntent().hasExtra("your_key")) and
2) use same key in two activities for passing data
like modify_intent.putExtra("same_key", title);

Related

how to add fast data in view inflate with layout

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

TextView update not happening when selected item from ListView

Hi I have Listview in that when I select an item I display another page where I am setting the text views with appropriate informations but when i select an item and go back and select another item the textviews are not getting updated ?BTW there are 10 text views can somebody provide me the solution for this? Thanks.
super.onCreate(savedInstanceState);
setContentView(R.layout.lastl);
Intent i = getIntent();
ACK = i.getStringExtra("ack-no");
NAME = i.getExtras().getString("appl name");
TRADE = i.getExtras().getString("trade");
PIN = i.getExtras().getString("pin");
MOBILE = i.getExtras().getString("mobile");
EMAIL = i.getExtras().getString("email");
LVO1 = i.getExtras().getString("LVO1");
LVO2 = i.getExtras().getString("LVO2");
tv1 = (TextView) findViewById(R.id.set_ack);
tv1.setText(ACK);
tv2 = (TextView) findViewById(R.id.set_apl);
tv2.setText(NAME);
tv3 = (TextView) findViewById(R.id.set_trd);
tv3.setText(TRADE);
tv4 = (TextView) findViewById(R.id.set_dr);
tv4.setText(ArrayAdapter.ar.get(0));
tv5 = (TextView) findViewById(R.id.set_flr);
tv5.setText(ArrayAdapter.ar.get(1));
tv6 = (TextView) findViewById(R.id.set_bdg);
tv6.setText(ArrayAdapter.ar.get(2));
tv7 = (TextView) findViewById(R.id.set_str);
tv7.setText(ArrayAdapter.ar.get(3));
tv8 = (TextView) findViewById(R.id.set_area);
tv8.setText(ArrayAdapter.ar.get(4));
tv9 = (TextView) findViewById(R.id.set_dis);
//tv9.setText(ArrayAdapter.ar.get(5));
tv10 = (TextView) findViewById(R.id.set_pin);
tv10.setText(PIN);
tv11 = (TextView) findViewById(R.id.set_mb);
tv11.setText(MOBILE);
tv12 = (TextView) findViewById(R.id.set_email);
tv12.setText(EMAIL);
tv13 = (TextView) findViewById(R.id.set_pn);
tv14 = (TextView) findViewById(R.id.set_bdgg);
tv15 = (TextView) findViewById(R.id.set_dt);
tv16 = (TextView) findViewById(R.id.set_lvo);
tv16.setText(LVO1);
String lvo2 = LVO2.substring(0, LVO2.length() - 1);
Log.d("sssssss", lvo2);
tv17 = (TextView) findViewById(R.id.set_lvo2);
tv17.setText(lvo2);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
break;
case R.id.button2:
break;
}
}
this is my listView code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listmain);
pv = getIntent().getStringArrayListExtra("Array_list");
System.out.println("ARRAYLIST---->" + pv);
final ListView list = (ListView) findViewById(R.id.listView1);
mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[]{"col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8"};
int[] columnIds = new int[]{R.id.col1, R.id.col2, R.id.col3, R.id.col4, R.id.col5, R.id.col6, R.id.col7, R.id.col8};
int k = 0;
for (int i = 0; i <= 9; i++) {
HashMap<String, String> map = new HashMap<String, String>();
//initialize row data
for (int j = 0; j <= 7/*pv.size()-1*/; j++) {
map.put(columnTags[j], pv.get(k));
put(columnTags[j], "row" + i + "col" + j);
k++;
}
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(this, mylistData, R.layout.rowmain, columnTags, columnIds);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet, android.view.View view, int position, long id) {
new LongOperation().execute();
String text = list.getItemAtPosition(position).toString();
String g = text.replace("{col5=", "");
String g1 = g.replace(" col4=", "");
String g2 = g1.replace(" col7=", "");
String g3 = g2.replace(" col6=", "");
String g4 = g3.replace(" col1=", "");
String g5 = g4.replace(" col3=", "");
String g6 = g5.replace(" col2=", "");
String g7 = g6.replace(" col8=", "");
String val[] = g7.split(",");
for (int m = 0; m < val.length; m++) {
Log.d("VALUE", val[m]);
ar1.add(val[m]);
}
System.out.println(ar1);
Log.d("VALUES-------->", text);
mob = ar1.get(0);
Log.d("VALUE1", mob);
pin = ar1.get(1);
Log.d("VALUE2", pin);
lvo = ar1.get(2);
Log.d("VALUE3", lvo);
email = ar1.get(3);
Log.d("VALUE4", email);
ack = ar1.get(4);
Log.d("VALUE5", ack);
trade = ar1.get(5);
Log.d("VALUE6", trade);
name = ar1.get(6);
Log.d("VALUE7", name);
lvo2 = ar1.get(7);
Log.d("VALUE8", lvo2);
}
});
}
From your code: ar1.add(val[m]);
I guess that ar1 is a List<String> variable of your listview activity?
If that's true, maybe add a call to clear() may work:
ar1.clear();
for(int m =0 ; m< val.length ; m++)
{
Log.d("VALUE",val[m]);
ar1.add(val[m]);
}

In Android how to prevent updating existing items on notifyDataSetChanged()

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();
}

Change two textViews inside a listview

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");

Calling url to open by text string

Ok so im making an app that involve a qr scanner on result i have text showing with the url of the code is there any way in an onclick listener to call the text from the result and open it in the browser if so how can I do it
Java Snippet
Button browser = (Button) findViewById(R.id.ulibutton);
browser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Intent.ACTION_VIEW, url = new URL(
getString(R.string.contents_text)));
startActivity(i);
}
});
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.icon));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT);
String formattedTime = formatter.format(new Date(rawResult
.getTimestamp()));
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formattedTime);
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType, Object> metadata = rawResult
.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType, Object> entry : metadata
.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
contentsTextView.setMovementMethod(LinkMovementMethod.getInstance());
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale betweeen 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
}
}
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(YourUrl)));
startActivity(i);

Categories

Resources