Large ram consumption and occasional freezing in android app - android

So my app is taking up 80MB or RAM and occasionally when switching between activities, the screen goes black and it takes over a minute for the proper content to appear. All it does is load listviews in each activity. I made sure to execute all my AsyncTasks in the loading screen when the activity is first started, and I then use shared preferences to store the data and use it across all activities so that I don't have to execute a new Asynctask each time an activity is started. This is why I am puzzled as to why this happens. The only thing I can think of is that the activities don't get killed when I call finish() as this usually occurs when I switch between activities many times.
Sample Activity:
public class AllGameslistActivity extends Activity {
private Bet newBet = new Bet();
private double stake = 0.00;
private String name = "";
private double newwinnings;
private ArrayList<TipDisplayer> alltips = new ArrayList<>();
private String newwinningstoString;
private RecyclerView recyclerview;
private String selection;
private ArrayList<Integer> ids = new ArrayList<>();
private ArrayList<BetParameters> listwriter = new ArrayList<>();
// Progress Dialog
private static String url_all_games = "****";
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> gamesList;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "ID";
private static final String TAG_LEAGUE = "League";
private static final String TAG_TEAMS = "Teams";
private static final String TAG_BET = "Bet";
private static final String TAG_ODDS = "Odds";
private static final String TAG_DATETIMER = "DateTimer";
private static final String TAG_COMMENTS = "Comments";
private static final String TAG_TYPE = "Type";
// products JSONArray
JSONArray allgames = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_bets);
overridePendingTransition(R.anim.push_up_out, R.anim.push_up_in);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
menu menu = (menu) getFragmentManager().findFragmentById(R.id.fragment);
menu.betnowclick();
SessionManager session;
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.USERNAME);
menu.updateinfo(getName());
alltips = session.getalltips();
PopulateList();
// Hashmap for ListView
gamesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
//new LoadAllGames().execute();
// Get listview
}
private void PopulateList() {
ArrayAdapter<TipDisplayer> adapter = new MyListAdapter(alltips);
final ListView list = (ListView) findViewById(R.id.mylist);
list.setAdapter(adapter);
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Games: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
allgames = json.getJSONArray(TAG_GAMELIST);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String league = c.getString(TAG_LEAGUE);
String odds = c.getString(TAG_ODDS);
String comments = c.getString(TAG_COMMENTS);
String type = c.getString(TAG_TYPE);
String bet = c.getString(TAG_BET);
String datetimer = c.getString(TAG_DATETIMER);
String Teams = c.getString(TAG_TEAMS);
Double Odds = Double.parseDouble(odds);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LEAGUE,league);
map.put(TAG_ODDS,odds);
map.put(TAG_COMMENTS,comments);
map.put(TAG_TYPE,type);
map.put(TAG_BET,bet);
map.put(TAG_DATETIMER,datetimer);
map.put(TAG_TEAMS, Teams);
Log.d("id", id);
Log.d("league", league);
Log.d("odds", odds);
Log.d("comments", comments);
Log.d("Type", type);
Log.d("bet", bet);
Log.d("datetimer", datetimer);
Log.d("teams",Teams);
alltips.add(i, new TipDisplayer(id, league, Teams, bet, odds, datetimer, comments, type));
// adding HashList to ArrayList
gamesList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
PopulateList();
}
}
class ViewHolder {
TextView leaguetxt;
TextView datetxt;
TextView teamstxt;
TextView bettxt;
TextView betid;
TextView typetxt;
TextView commentstxt;
Button oddsbtn;
LinearLayout item;
ViewHolder(View v) {
leaguetxt = (TextView) v.findViewById(R.id.leaguetxt);
datetxt = (TextView) v.findViewById(R.id.datetxt);
teamstxt = (TextView) v.findViewById(R.id.teamstxt);
bettxt = (TextView) v.findViewById(R.id.bettxt);
betid = (TextView) v.findViewById(R.id.gid);
typetxt = (TextView) v.findViewById(R.id.difficultytxt);
commentstxt = (TextView) v.findViewById(R.id.commenttxt);
oddsbtn = (Button) v.findViewById(R.id.oddsbutton);
item = (LinearLayout) v.findViewById(R.id.item);
}
}
private class MyListAdapter extends ArrayAdapter<TipDisplayer> {
public MyListAdapter() {
super(AllGameslistActivity.this, R.layout.list_item, alltips);
}
public MyListAdapter(ArrayList<TipDisplayer> alltips) {
super(AllGameslistActivity.this, R.layout.list_item, alltips);
alltips = alltips; // declare tomee in the Adapter, don't use static
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
TipDisplayer currentwriter = alltips.get(position);
ViewHolder holder = null;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.list_item, parent, false);
holder = new ViewHolder(itemView);
itemView.setTag(holder);
Log.d("SETTING","new holder");
}
else {
holder = (ViewHolder) itemView.getTag();
Log.d("plzwork",ids.toString());
if (!ids.contains(Integer.parseInt(holder.betid.getText().toString()))) {
Log.d("doesn't contain", "doesn't contain");
Log.d("betid",holder.betid.getText().toString());
Log.d("bettxt", holder.bettxt.getText().toString());
}
else {
Log.d("recycling contains", "contains");
Log.d("betid", holder.betid.getText().toString());
Log.d("bettxt", holder.bettxt.getText().toString());
}
Log.d("Recycling","recycling");
}
holder.item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout layout = (LinearLayout) v;
Button b = (Button) layout.findViewById(R.id.oddsbutton);
ListView listView = (ListView) layout.getParent();
final int position = listView.getPositionForView(listView);
String buttontext = b.getText().toString();
Button lastchance = (Button) layout.findViewById(R.id.oddsbutton);
TextView betidtextbox = (TextView) layout.findViewById(R.id.gid);
String betid = betidtextbox.getText().toString();
TipDisplayer currentwriter = alltips.get(position + 1);
Log.d("plzworkkkk", newBet.toString());
if (ids.contains(Integer.parseInt(betid))) {
b.setTextColor(Color.parseColor("#000000"));
b.setTextSize(18);
ids.remove(new Integer(Integer.parseInt(betid)));
Log.d("plzworkkkkkkk", newBet.toString());
currentwriter.toggleHighlighted();
//checkhighlight(layout);
Log.d("getodds", buttontext);
selection = "home";
TextView teamss = (TextView) layout.findViewById(R.id.teamstxt);
String teams = teamss.getText().toString();
Log.d("teams", teams);
TextView bet = (TextView) layout.findViewById(R.id.bettxt);
String bettxt = bet.getText().toString();
Log.d("btxttext", bettxt);
newBet.generateoddstesting(betid, buttontext, false, teams, selection, bettxt);
double newodds = newBet.calculateodds();
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
EditText mEdit = (EditText) findViewById(R.id.editText2);
if (mEdit.getText().toString().length() == 0) {
stake = 0.00;
newwinnings = 0.00;
potentialWinnings.setText("0.00");
} else {
mEdit.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
stake = Double.parseDouble(s.toString());
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
} else {
stake = 0.00;
newwinnings = 0.00;
double newodds = newBet.calculateodds();
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
}
public void afterTextChanged(Editable s) {
}
});
//stake = Double.parseDouble(mEdit.getText().toString());
newwinnings = stake * newodds;
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
} else {
ids.add(Integer.parseInt(betid));
//checkhighlight(layout);
b.setTextColor(Color.parseColor("#EB102E"));
b.setTextSize(20);
currentwriter.toggleHighlighted();
selection = "home";
String getodds = lastchance.getText().toString();
Log.d("getoddsss", getodds);
EditText mEdit = (EditText) findViewById(R.id.editText2);
if (mEdit.getText().toString().length() == 0) {
stake = 0.00;
newwinnings = 0.00;
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
potentialWinnings.setText("0.00");
} else {
mEdit.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
stake = Double.parseDouble(s.toString());
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
} else {
stake = 0.00;
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
}
public void afterTextChanged(Editable s) {
}
});
stake = Double.parseDouble(mEdit.getText().toString());
TextView teamms = (TextView) layout.findViewById(R.id.teamstxt);
String teams = teamms.getText().toString();
Log.d("teams", teams);
TextView bet = (TextView) layout.findViewById(R.id.bettxt);
String bettxt = (String) bet.getText().toString();
Log.d("bettxt", bettxt);
newBet.generateoddstesting(betid, buttontext, true, teams, selection, bettxt);
double newodds = newBet.calculateodds();
newwinnings = stake * newodds;
TextView myBetOdds = (TextView) findViewById(R.id.bettingodds);
TextView potentialWinnings = (TextView) findViewById(R.id.potentialwinnings);
myBetOdds.setText("#" + String.format("%.2f", newodds) + "/1");
potentialWinnings.setText(String.format("%.2f", (newwinnings)));
newwinningstoString = potentialWinnings.getText().toString();
}
}
}
});
String leaguetext = currentwriter.getLeague();
String datetext = currentwriter.getDatetimer();
String teamstext = currentwriter.getTeams();
String bettext = currentwriter.getBet();
String typetext = currentwriter.getType();
String idtext = currentwriter.getId();
String commentsText = currentwriter.getComments();
String oddstext = currentwriter.getOdds();
holder.leaguetxt.setText(leaguetext);
holder.datetxt.setText(datetext.substring(0,datetext.lastIndexOf(":")) + " GMT");
holder.teamstxt.setText(teamstext);
holder.bettxt.setText(bettext);
holder.betid.setText(idtext);
holder.commentstxt.setText(commentsText);
holder.oddsbtn.setText(oddstext);
holder.typetxt.setText(typetext);
if (typetext.equals("Low Risk")) {
holder.typetxt.setTextColor(Color.parseColor("#067103"));
}
else if (typetext.equals("Medium Risk")) {
holder.typetxt.setTextColor(Color.parseColor("#D9D216"));
}
else if (typetext.equals("Longshot")) {
holder.typetxt.setTextColor(Color.parseColor("#F75528"));
}
return itemView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
public void clicking(View v) {
}
public void NewBetMaker(View v) {
menu menu = (menu) getFragmentManager().findFragmentById(R.id.fragment);
int value = (int) stake;
if (value == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Stake");
builder.setMessage("You did not enter any stake for your bet.");
builder.setNeutralButton("Ok.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
builder.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm Bet Placement");
builder.setMessage("Are you sure you would like to place this bet?");
builder.setNegativeButton("Nope.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
builder.setPositiveButton("YES, BET NOW!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
menu menu = (menu) getFragmentManager().findFragmentById(R.id.fragment);
int pass = (int) stake;
Intent i = new Intent(AllGameslistActivity.this, MyBets.class);
HashMap<Integer, Game> listofgames = new HashMap<Integer, Game>();
HashMap<Integer,String> betdatabasesetter = new HashMap<Integer, String>();
listofgames = newBet.getlistofgames();
for (Integer x : listofgames.keySet()) {
TextView teams = (TextView) findViewById(R.id.textView2);
String getTeams = listofgames.get(x).getTeams();
teams.setText(getTeams);
TextView selectionodds = (TextView) findViewById(R.id.textView3);
String selectedoutcome = listofgames.get(x).getSelection();
Double selectedoutcomeodds = listofgames.get(x).getSelectedOdds();
String selectedteam = "";
if (selectedoutcome.equals("home")) {
selectedteam = listofgames.get(x).getBet();
betdatabasesetter.put(x,"1");
}
String selection = (selectedteam + " #" + selectedoutcomeodds);
BetParameters y = new BetParameters(getTeams, selection);
listwriter.add(y);
Log.d("teams", getTeams);
Log.d("selected odds", Double.toString(selectedoutcomeodds));
Log.d("selected team", selectedteam);
Log.d("selected outcome", selectedoutcome);
Log.d("selection", selection);
}
i.putExtra("hash",new DataWrapper(betdatabasesetter));
i.putExtra("data", new DataWrapper(listwriter));
i.putExtra("stake", stake);
i.putExtra("winnings",newwinningstoString);
((AppController) getApplicationContext()).setGamesList(gamesList);
startActivity(i);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public String getName() {
SessionManager session;
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.USERNAME);
return name;
}
public void checkhighlight(View v) {
TextView betid = (TextView) v.findViewById(R.id.gid);
String id = betid.getText().toString();
Button button = (Button) v.findViewById(R.id.oddsbutton);
if (ids.contains(Integer.parseInt(id))) {
button.setTextColor(Color.parseColor("#EB102E"));
button.setTextSize(20);
}
else {
button.setTextColor(Color.parseColor("#000000"));
button.setTextSize(18);
}
}
}

Related

Unable to calculate proper value from each row in ListView

// i have two button for increasing and decreasing the quantity, after increasing or decreasing the value i want to calculate price from each row but it is not giving correct value.Also the quantity getting changed while scrolling .Mostly the above said problem occurs whenever the size of listview is more than screen size.
public class Baseddapter extends BaseAdapter
{
#Override
public int getCount()
{
return prodetailarray.size();
}
#Override
public Object getItem(int i)
{
// Log.d("item_value",""+prodetailarray.get(i).getPrice());
return null;
}
#Override
public long getItemId(int i)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
listrowposition = position;
final ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowbill_detail, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtproname_prodetail);
holder.sellprice = (TextView) convertView.findViewById(R.id.txtprice_prodetail);
holder.proid = (TextView) convertView.findViewById(R.id.txtproid_prodetail);
holder.qty = (TextView) convertView.findViewById(R.id.txtquntty_prodetail);
holder.imgplus = (ImageView) convertView.findViewById(R.id.imgplus_prodetail);
holder.imgminus = (ImageView) convertView.findViewById(R.id.imgminus_prodetail);
holder.singlerowprice = (TextView) convertView.findViewById(R.id.txtsinglerow_price);
holder.baseprice = (TextView) convertView.findViewById(R.id.txt_base_price_prodetail);
holder.taxid = (TextView) convertView.findViewById(R.id.txt_taxid_prodetail);
holder.taxname = (TextView) convertView.findViewById(R.id.txt_taxname_prodetail);
holder.taxval = (TextView) convertView.findViewById(R.id.txt_taxval_prodetail);
// holder.singlerowprice.addTextChangedListener(new MytextWatcher(convertView));
holder.delete = (ImageView) convertView.findViewById(R.id.txtdeleterow);
holder.txtkg = (TextView) convertView.findViewById(R.id.txtkg);
holder.whole_qntty = (TextView) convertView.findViewById(R.id.txt_whole_qntty_prodetail);
holder.delete.setTag(position);
holder.circularImageView = (CircularImageView) convertView.findViewById(R.id.productImage_billdetail);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearkg);
holder.name.setTypeface(light);
holder.singlerowprice.setTypeface(light);
holder.baseprice.setTypeface(light);
holder.qty.setTypeface(light);
//holder.qty.setTag(position);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
base_price = prodetailarray.get(listrowposition).getBaseprice();
Log.d("baseprice==", "***" + base_price);
holder.baseprice.setText(prodetailarray.get(listrowposition).getBaseprice());
//this means if qnty contain only number means add as unit otherwise add as kg
if(prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setText(prodetailarray.get(position).getQntity());
//holder.linearLayout.setVisibility(View.VISIBLE);
holder.imgplus.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
// holder.txtkg.setVisibility(View.GONE);
Log.d("qntty_kg??",""+prodetailarray.get(listrowposition).getQntity());
}
else
{
// holder.linearLayout.setVisibility(View.GONE);
holder.imgplus.setVisibility(View.GONE);
holder.imgminus.setVisibility(View.GONE);
// holder.txtkg.setVisibility(View.VISIBLE);
holder.qty.setText(""+prodetailarray.get(listrowposition).getQntity());
Log.d("qntty_kg==",""+prodetailarray.get(listrowposition).getQntity());
// Toast.makeText(Bill_details.this,""+prodetailarray.get(position).getQntity(),Toast.LENGTH_LONG).show();
}
holder.name.setText(prodetailarray.get(listrowposition).getProductname());
holder.sellprice.setText(getResources().getString(R.string.Rs)+" "+prodetailarray.get(position).getPrice());
holder.taxid.setText(prodetailarray.get(listrowposition).getTaxid());
holder.taxname.setText(prodetailarray.get(listrowposition).getTaxname());
holder.taxval.setText(prodetailarray.get(listrowposition).getTaxvalue());
holder.whole_qntty.setText(prodetailarray.get(listrowposition).getWhole_qntty());
holder.proid.setText(prodetailarray.get(listrowposition).getProducuid());
final String str=prodetailarray.get(listrowposition).getQntity();
Double q = Double.parseDouble(str.replaceAll("KG", ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(prodetailarray.get(listrowposition).getPrice()) * q);
drawable = mDrawableBuilder.build(String.valueOf(holder.name.getText().toString().trim().toUpperCase().charAt(0)),
mColorGenerator.getColor((holder.name.getText().toString().trim().charAt(0))));
holder.circularImageView.setImageDrawable(drawable);
holder.delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
total_item = totalquantity-1;
totalquantity=total_item;
Integer index = (Integer) view.getTag();
Log.d("indexval==","delete"+index.intValue());
prodetailarray.remove(index.intValue());
adapter.notifyDataSetChanged();
listView.invalidateViews();
Log.d("listCount==",""+listView.getCount());
// totalprice=0;
Double add = 0.0;
Double pr = 0.0;
// listView.invalidateViews();
if (listView.getCount() == 0)
{
totalitem.setText("0 Items");
totalamount.setText( getResources().getString(R.string.Rs)+" 0");
editor.remove("count");
editor.remove("price");
editor.commit();
}
Log.d("liistvisiblepos==",""+(listView.getLastVisiblePosition()-listView.getFirstVisiblePosition())) ;
for (int i = 0; i < listView.getCount(); i++)
{
// this if is for after delete item it will take first item so we dont want like this
if(index.intValue() != i)
{
/* View v = listView.getChildAt(i);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
*/
String str = holder.qty.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
totalitem.setText("" + total_item + " Items");
totalamount.setText(getResources().getString(R.string.Rs) + " " + pr);
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr + "p==" + p);
}
}
}
});
holder.imgplus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
View v1=view;
PLUSMINUS = 100;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
plus_qnty = Integer.parseInt(holder.qty.getText().toString());
Log.d("plus_qnty==",""+plus_qnty);
//this is for check the quantity that useer enter is not more than qntty in stock
Log.d("whole_qnt_plus==",""+holder.whole_qntty.getText().toString());
whole_qnt= Integer.parseInt(holder.whole_qntty.getText().toString());
Log.d("whole_qnt_plus==",""+whole_qnt);
plus_qnty = plus_qnty + 1;
if(plus_qnty>whole_qnt)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
prodetailarray.get(listrowposition).setQntity(String.valueOf(plus_qnty));
holder.qty.setText("" + plus_qnty);
//remove all the text except price (integer value)
String str=holder.sellprice.getText().toString().trim();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(plus_qnty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * plus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i < listView.getCount(); i++)
{
Log.d("listviewcount==",""+listView.getCount());
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
// String str_qun=tvquan.getText().toString().trim();
String str_qun=tvquan.getText().toString().trim();
Log.d("listviewcount==",""+str_qun);
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
// String str = holder.singlerowprice.getText().toString().trim();
Log.d("str_qun==",""+str_qun+str);
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else {
}
}
});
holder.imgminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLUSMINUS = 200;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
minus_qnty = Integer.parseInt(holder.qty.getText().toString());
if (minus_qnty == 1)
{
// holder.qty.setText(""+);
}
else
{
minus_qnty = minus_qnty - 1;
holder.qty.setText("" + minus_qnty);
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(minus_qnty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * minus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0; i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else
{
}
}
});
if(!prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final Integer index = (Integer) view.getTag();
Log.d("indexval==","index==="+index);
final Dialog dialog_item = new Dialog(Bill_details.this);
dialog_item.setContentView(R.layout.add_item_dialog);
dialog_item.getWindow().setLayout(AppBarLayout.LayoutParams.FILL_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT);
final EditText edt_enter_qntty = (EditText) dialog_item.findViewById(R.id.txtqntty_item_dialog);
TextView ok = (TextView) dialog_item.findViewById(R.id.txtok_item_dialog);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(edt_enter_qntty.getText().toString().equals(""))
{
}
else
{
Double dialog_qntty= Double.parseDouble(edt_enter_qntty.getText().toString());
// PLUSMINUS = 100;
kg_qntty = dialog_qntty;
//this is for checking entered qunnt is not more than avail qntty
String whole_qnt=holder.whole_qntty.getText().toString();
String whole_qnt_replce= (whole_qnt.replaceAll("KG", ""));
whole_qnt_kg= Double.parseDouble(whole_qnt_replce);
Log.d("whole_qnt_kg==",""+whole_qnt_kg);
if(kg_qntty>whole_qnt_kg)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
prodetailarray.get(listrowposition).setQntity(String.valueOf(kg_qntty));
holder.qty.setText("" + kg_qntty+"KG");
//remove all the text except price (integer value)
String str_qnty=holder.qty.getText().toString();
Double qty= Double.parseDouble(str_qnty.replaceAll("KG", ""));
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + qty * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(kg_qntty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * kg_qntty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_quan=tvquan.getText().toString().trim();
Log.d("strqn",str_quan);
String c = (str_quan.replaceAll("KG", ""));
Log.d("strqn", "" + c);
add = Double.parseDouble(c) + add;
String str_pri=tvprice.getText().toString().trim();
Double p= Double.parseDouble(str_pri.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("total_qntty", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
// totalitem.setText("" + add+" Items");
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
dialog_item.dismiss();
}
});
dialog_item.show();
}
});
}
return convertView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
Never update an item view in a list from the event handler (controller).
It looks like you are correctly updating the model (prodetailarray), but in an onClick or any event handler, all you want to do is update the model and then call notifyDataSetChanged(). This will inform your list view that the model has changed, and the list view will regenerate item views based on the new model data.
If that's not sufficient to solve your problem, you'll need to post your entire adapter code so we can identify the problem.
//see below getview method which I updated .
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
final ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowbill_detail, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtproname_prodetail);
holder.sellprice = (TextView) convertView.findViewById(R.id.txtprice_prodetail);
holder.proid = (TextView) convertView.findViewById(R.id.txtproid_prodetail);
holder.qty = (TextView) convertView.findViewById(R.id.txtquntty_prodetail);
holder.imgplus = (ImageView) convertView.findViewById(R.id.imgplus_prodetail);
holder.imgminus = (ImageView) convertView.findViewById(R.id.imgminus_prodetail);
holder.singlerowprice = (TextView) convertView.findViewById(R.id.txtsinglerow_price);
holder.baseprice = (TextView) convertView.findViewById(R.id.txt_base_price_prodetail);
holder.taxid = (TextView) convertView.findViewById(R.id.txt_taxid_prodetail);
holder.taxname = (TextView) convertView.findViewById(R.id.txt_taxname_prodetail);
holder.taxval = (TextView) convertView.findViewById(R.id.txt_taxval_prodetail);
// holder.singlerowprice.addTextChangedListener(new MytextWatcher(convertView));
holder.delete = (ImageView) convertView.findViewById(R.id.txtdeleterow);
holder.txtkg = (TextView) convertView.findViewById(R.id.txtkg);
holder.whole_qntty = (TextView) convertView.findViewById(R.id.txt_whole_qntty_prodetail);
holder.circularImageView = (CircularImageView) convertView.findViewById(R.id.productImage_billdetail);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearkg);
holder.name.setTypeface(light);
holder.singlerowprice.setTypeface(light);
holder.baseprice.setTypeface(light);
holder.qty.setTypeface(light);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
base_price = prodetailarray.get(listrowposition).getBaseprice();
holder.qty.setTag(listrowposition);
holder.delete.setTag(listrowposition);
holder.imgplus.setTag(listrowposition);
holder.imgminus.setTag(listrowposition);
Log.d("baseprice==", "***" + base_price);
holder.baseprice.setText(prodetailarray.get(listrowposition).getBaseprice());
//this means if qnty contain only number means add as unit otherwise add as kg
if(prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setText(prodetailarray.get(listrowposition).getQntity());
//
holder.imgplus.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
//
Log.d("qntty_kg??",""+prodetailarray.get(listrowposition).getQntity());
}
else
{
holder.imgplus.setVisibility(View.GONE);
holder.imgminus.setVisibility(View.GONE);
//
holder.qty.setText(""+prodetailarray.get(listrowposition).getQntity());
Log.d("qntty_kg==",""+prodetailarray.get(listrowposition).getQntity());
}
holder.name.setText(prodetailarray.get(listrowposition).getProductname());
holder.sellprice.setText(getResources().getString(R.string.Rs)+" "+prodetailarray.get(listrowposition).getPrice());
holder.taxid.setText(prodetailarray.get(listrowposition).getTaxid());
holder.taxname.setText(prodetailarray.get(listrowposition).getTaxname());
holder.taxval.setText(prodetailarray.get(listrowposition).getTaxvalue());
holder.whole_qntty.setText(prodetailarray.get(listrowposition).getWhole_qntty());
holder.proid.setText(prodetailarray.get(listrowposition).getProducuid());
final String str=prodetailarray.get(listrowposition).getQntity();
Double q = Double.parseDouble(str.replaceAll("KG", ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(prodetailarray.get(listrowposition).getPrice()) * q);
drawable = mDrawableBuilder.build(String.valueOf(holder.name.getText().toString().trim().toUpperCase().charAt(0)),
mColorGenerator.getColor((holder.name.getText().toString().trim().charAt(0))));
holder.circularImageView.setImageDrawable(drawable);
holder.delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
total_item = totalquantity-1;
totalquantity=total_item;
Integer index = (Integer) view.getTag();
Log.d("indexval==","delete"+index.intValue());
prodetailarray.remove(index.intValue());
adapter.notifyDataSetChanged();
listView.invalidateViews();
Log.d("listCount==",""+listView.getCount());
Double add = 0.0;
Double pr = 0.0;
if (listView.getCount() == 0)
{
totalitem.setText("0 Items");
totalamount.setText( getResources().getString(R.string.Rs)+" 0");
editor.remove("count");
editor.remove("price");
editor.commit();
}
for (int i = 0; i < listView.getCount(); i++)
{
// this if is for after delete item it will take first item so we dont want like this
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
totalitem.setText("" + total_item + " Items");
totalamount.setText(getResources().getString(R.string.Rs) + " " + pr);
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr + "p==" + p);
}
}
});
holder.imgplus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
int in=(Integer) view.getTag();
PLUSMINUS = 100;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
plus_qnty = Integer.parseInt(holder.qty.getText().toString());
Log.d("plus_qnty==",""+plus_qnty);
//this is for check the quantity that useer enter is not more than qntty in stock
Log.d("whole_qnt_plus==",""+holder.whole_qntty.getText().toString());
whole_qnt= Integer.parseInt(holder.whole_qntty.getText().toString());
Log.d("whole_qnt_plus==",""+whole_qnt);
plus_qnty = plus_qnty + 1;
if(plus_qnty>whole_qnt)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
for(int i=0;i<prodetailarray.size();i++){
Log.d("proarr==","getQntity=="+""+prodetailarray.get(i).getQntity()+"baseprice=="+prodetailarray.get(i).getBaseprice());
}
holder.qty.setText("" + plus_qnty);
//remove all the text except price (integer value)
String str=holder.sellprice.getText().toString().trim();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
Bills_Activity.productlistarray.set(position,);
prodetailarray.get(in).setQntity(String.valueOf(plus_qnty));
prodetailarray.get(in).setBaseprice("" + Double.parseDouble(base_price) * plus_qnty);
for(int i=0;i<prodetailarray.size();i++)
{
Log.d("proarr=="," after_getQntity=="+""+prodetailarray.get(i).getQntity()+"baseprice=="+prodetailarray.get(i).getBaseprice());
}
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else
{
}
}
});
holder.imgminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLUSMINUS = 200;
int in=(Integer) view.getTag();
if(holder.qty.getText().toString().matches("[0-9]+"))
{
minus_qnty = Integer.parseInt(holder.qty.getText().toString());
if (minus_qnty == 1)
{
}
else
{
minus_qnty = minus_qnty - 1;
holder.qty.setText("" + minus_qnty);
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(in).setQntity(String.valueOf(minus_qnty));
prodetailarray.get(in).setBaseprice("" + Double.parseDouble(base_price) * minus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0; i < listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
// totalamount.setText(""+ pr);
}
}
else
{
}
}
});
if(!prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
index = (Integer) view.getTag();
Log.d("indexval==","index==="+index);
final Dialog dialog_item = new Dialog(Bill_details.this);
dialog_item.setContentView(R.layout.add_item_dialog);
dialog_item.getWindow().setLayout(AppBarLayout.LayoutParams.FILL_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT);
edt_enter_qntty = (EditText) dialog_item.findViewById(R.id.txtqntty_item_dialog);
TextView ok = (TextView) dialog_item.findViewById(R.id.txtok_item_dialog);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(edt_enter_qntty.getText().toString().equals(""))
{
}
else
{
Double dialog_qntty= Double.parseDouble(edt_enter_qntty.getText().toString());
// PLUSMINUS = 100;
kg_qntty = dialog_qntty;
//this is for checking entered qunnt is not more than avail qntty
String whole_qnt=holder.whole_qntty.getText().toString();
String whole_qnt_replce= (whole_qnt.replaceAll("KG", ""));
whole_qnt_kg= Double.parseDouble(whole_qnt_replce);
Log.d("whole_qnt_kg==",""+whole_qnt_kg);
if(kg_qntty>whole_qnt_kg)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
holder.qty.setText("" + kg_qntty+"KG");
prodetailarray.get(index).setQntity(String.valueOf(kg_qntty));
//remove all the text except price (integer value)
String str_qnty=prodetailarray.get(index).getQntity().toString();
Double qty= Double.parseDouble(str_qnty.replaceAll("KG", ""));
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
Log.d("qty * sell_price==",""+qty+" "+sell_price);
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + qty * sell_price);
prodetailarray.get(index).setBaseprice("" + Double.parseDouble(base_price) * kg_qntty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i < listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_quan=tvquan.getText().toString().trim();
Log.d("strqn",str_quan);
String c = (str_quan.replaceAll("KG", ""));
Log.d("strqn", "" + c);
add = Double.parseDouble(c) + add;
String str_pri=tvprice.getText().toString().trim();
Double p= Double.parseDouble(str_pri.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("total_qntty", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
// totalitem.setText("" + add+" Items");
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
dialog_item.dismiss();
}
});
dialog_item.show();
}
});
}
return convertView;
}

How to get edit text values from a listview

I am not able to get edittext value from dynamic listview. When I am scrolling listview, entered values in edit text is going invisible
Below is My Activity file -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_servic_homepage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
url = getResources().getString(R.string.webservice);
aq = new AQuery(ServicHomepage.this);
cd = new ConnectionDetector(ServicHomepage.this);
findviewbyId();
progressdialog();
if (cd.isConnectingToInternet()) {
getintentData();
} else {
Toast.makeText(ServicHomepage.this, "CheckIternet connection", Toast.LENGTH_SHORT).show();
}
}
private void progressdialog() {
pd = new ProgressDialog(ServicHomepage.this);
pd.setMessage("Loading...");
}
public void findviewbyId() {
recyclerview = (ListView) findViewById(R.id.service_recycler_view);
update_descrptn = (TextView) findViewById(R.id.update_descrptn);
uploadimages = (TextView) findViewById(R.id.uploadimages);
}
public void getintentData() {
SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
catid = prefs.getString(Constants.CATID, "");
subcatid = prefs.getString(Constants.SUBCATID, "");
user_id = prefs.getString(Constants.USERID, "");
isappointment = prefs.getString(Constants.IS_APPOINTMENT, "");
clicklistener();
}
public void clicklistener() {
uploadimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GalleryAlbumActivity.class);
startActivity(i);
}
});
update_descrptn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ServicHomepage.this, "" + serv_adapter.getItem(POSITION), Toast.LENGTH_SHORT).show();
for (int i = 0; i < serv_adapter.getCount(); i++) {
View view = serv_adapter.getView(i,null,null);
EditText edittext = (EditText)view.findViewById(R.id.et_amount);
EditText et_description = (EditText)view.findViewById(R.id.et_description);
String str = edittext.getText().toString();
String str1 = et_description.getText().toString();
Toast.makeText(ServicHomepage.this, str + "==" + str1, Toast.LENGTH_SHORT).show();
}
updateList();
}
});
}
private void updateList() {
String substring = null, msgString = "";
String MAIN_CART = null;
MAIN_CART = "{\"service\":[%s]}";
String temstring = "";
for (int i = 0; i < arrayList.size(); i++) {
substring = "{\"title\":\"" + arrayList.get(i).getTitle() + "\",\"subcatid\":\"" + arrayList.get(i).getSubcatid()
+ "\",\"amount\":\"" + "" + "\",\"description\":\"" + "" + "\"}" + ",";
temstring = temstring + substring;
}
temstring = temstring.substring(0, temstring.length() - 1);
msgString = msgString + String.format(MAIN_CART, temstring);
Log.e("msgString=============", msgString);
}
This is the method where all the items are adding in the list
public String parseanimcat(String object) {
try {
JSONObject json = new JSONObject(object);
JSONObject jsonobj = json.getJSONObject("data");
status1 = jsonobj.getString("status");
message = jsonobj.getString("message");
arrayList = new ArrayList<>();
JSONArray jarray = jsonobj.getJSONArray("dataFound");
for (int i = 0; i <= jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String category = jobj.getString("category");
String subsubcat_id = jobj.getString("subsubcat_id");
Toast.makeText(ServicHomepage.this, category + "==" + subsubcat_id, Toast.LENGTH_SHORT).show();
model = new Data_Model();
model.setTitle(category);
model.setSubcatid(subsubcat_id);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
This is my adapter class-
private class service_list_adapter extends ArrayAdapter<Data_Model>{
private ArrayList<Data_Model> array_list;
Context context;
String[] etValArr;
ViewHolder holder;
String[] totalValue;
Data_Model model;
HashMap<String, String> hm = new HashMap<>();
ArrayList<HashMap<String, String>> list = new ArrayList<>();
public service_list_adapter(Context context,int resourceId,ArrayList<Data_Model> arrayList) {
super(context,resourceId,arrayList);
this.context = context;
this.array_list = arrayList;
etValArr = new String[array_list.size()];
totalValue = new String[array_list.size()];
}
private class ViewHolder {
public TextView serv_title;
public EditText serv_descrptn, serv_amount;
}
public View getView(int position, View convertView, ViewGroup parent) {
model = array_list.get(position);
POSITION = position;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.serv_cat_rowitem, null);
holder = new ViewHolder();
holder.serv_title = (TextView) convertView.findViewById(R.id.serv_txt);
holder.serv_descrptn = (EditText) convertView.findViewById(R.id.et_description);
holder.serv_amount = (EditText) convertView.findViewById(R.id.et_amount);
convertView.setTag(holder);
holder.serv_title.setTag(position);
holder.serv_descrptn.setTag(position);
holder.serv_amount.setTag(position);
} else
holder = (ViewHolder) convertView.getTag();
holder.serv_title.setText(model.getTitle());
holder.serv_descrptn.setText(model.getServdescription());
holder.serv_amount.setText(model.getServamount());
holder.serv_amount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServamount(s.toString());
}
});
holder.serv_descrptn.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServdescription(s.toString());
}
});
return convertView;
}
}
be more specific exactly which editText value you want.
you can implement onScrollListner on list and save the value of the editText on that event and later use it

Fully displayed listview image is not displaying properly

its my following code.
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
//Toast.makeText(getApplicationContext(), productID[j] + "" + ProductName[j] + "" + ProductPrice[j] + "" + ProductQuantity[j] + "" + ProductModel[j] + "" + ProductImage[j] + "" + ProductManufacturer[j], Toast.LENGTH_SHORT).show();
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
getListViewSize(ListCart);
String s1 = ProductPrice.toString();
}
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
if (listItem != null) {
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
if (params != null) {
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
}
myListView.requestLayout();
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
Adapter class
Public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
listview is working properly
i just inflate cardview in listview.
when using this code image cannot displaying. only dispaly last image in list view
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
my problem is: In listview only displaying last image
check this image:
Try adding your ImageView to Holder class and use like viewholder.img.setImageBitmap(new LoadImage().execute(urll)) and change the return type to Bitmap
Use BaseAdapter instead of ArrayAdapter. Load and show image with UIL, Picasso or other image loader library.
public class ImageAdapter extends BaseAdapter {
private List<ImageBean> list;
private ArrayList<ImageBean> arraylist;
private LayoutInflater inflater;
public ImageAdapter(Context context, List<ImageBean> list) {
this.list = list;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public ImageBean getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.recycler_view_item, parent, false);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Loading image with UIL example
ImageLoader.getInstance().displayImage(getItem(position).getUrl(), holder.ivImage, ImageUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
return convertView;
}
private class ViewHolder {
public ImageView ivImage;
}
}

sharedPreference or onSaveInstanceState on an EditText/TextView result

I have a little test project below. All I want to do is save the EditText numbers entered and TextView result (thing1, thing2, result) . What's best? onSaveInstanceState, sharedPreference, or something different like SQLite?
I've frustratingly tried the first two (for probably embarrassingly too long), but couldn't figure it out. Could someone please help by adding it to the code below?
public class MainActivity extends ActionBarActivity {
EditText thing1;
EditText thing2;
TextView result;
double n1=0;
double n2=0;
double total=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button divideButton = (Button) findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1+n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button subtractButton = (Button) findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1-n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button multiplyButton = (Button) findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1*n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
}
If you will just use the values later like when you open your application, you
can use the SharedPreferences. Based on your code above you can add the code below
to save your EditText data to SharedPreferences and restore it later.
To save your EditText value:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("thing1", thing1.getText.toString());
editor.commit();
To get the value from SharedPreferences you can do this in your onCreate function:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
String sValue = sharedPreferences.getString("thing1", "default");
thing1.setText( sValue );

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

Categories

Resources