I am working on ListView having EditText inside.I have used four EditText in each item of ListView.I am facing problem with getting the position of EditText in the ListView. Below is my code. I am able to fetch the position of TextView,but while fetching the position of EditText I am facing problem.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
myproductpercarton = (TextView) view.findViewById(R.id.txtorderamount);
final String ssss =(String) ((TextView) view.findViewById(R.id.txtorderamount)).getText();
mytotalprice = (TextView) view.findViewById(R.id.txtprice);
mm = (CheckBox) view.findViewById(R.id.mycheck);
mm.setFocusableInTouchMode(true);
mm.setFocusable(true);
mm2 = (CheckBox) view.findViewById(R.id.mynewcheck);
mm2.setFocusableInTouchMode(true);
mm2.setFocusable(true);
myorderprice = (EditText) view.findViewById(R.id.txtorderby);
myorderprice.setFocusableInTouchMode(true);
myorderprice.setFocusable(true);
mycartonno = (EditText) view.findViewById(R.id.txtordercarton);
mycartonno.setFocusableInTouchMode(true);
mycartonno.setFocusable(true);
myproductno = (EditText) view.findViewById(R.id.txtproduct);
myproductno.setFocusableInTouchMode(true);
myproductno.setFocusable(true);
myproductno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myprodpercart;
map = (HashMap<String, String>) getListView().getItemAtPosition(position);
HashMap<String, String> map2 = (HashMap<String, String>) getListView().getItemAtPosition(position);
HashMap<String, String> map3 = (HashMap<String, String>) getListView().getItemAtPosition(position);
double orderId4;
double mycarton2;
double mynewcart;
double myprodno2;
double mycartquantity;
double mytotal;
String mynoocarton;
double mynoocarton44;
int myprodno3;
String temp=mycartonno.getText().toString();
String contents = mycartonno.getText().toString();
orderId4 = new Double(map.get(TAG_PRODUCTPERCARTON));
Log.d("MyOrderId :: ", String.valueOf(orderId4));
mycartonprice2 = map.get(TAG_PRODUCTPERCARTON2);
Log.d("MyCartonPrice :: ", String.valueOf(mycartonprice2));
mynoocarton = mycartonno.getText().toString();
mynoocarton44 = new Double(mycartonno.getText().toString());
mycarton2 = new Double(mynoocarton);
mynewcart = new Double(mycartonprice2);
myprodno2 = new Double(orderId4 * mycarton2);
myprodno3 = new Integer((int) myprodno2);
mycartquantity = new Double(mycartonno.getText().toString());
Log.d("MyCartonNo :: ", mycartonno.getText().toString());
Log.d("MyCartonNo2 :: ",contents);
mytotal = new Double(mycartquantity * mynewcart);
String mynoocarton3 = String.valueOf(mynoocarton44);
String total = String.valueOf(mytotal);
String mm = String.valueOf(myprodno3);
mycartonno.setText(mynoocarton3);
myproductno.setText(mm);
mytotalprice.setText(total);
Toast.makeText(getActivity(), ssss + " " + mynewcart + "----" + mm + " " + total,
Toast.LENGTH_SHORT).show();
}
});
mydiscount = (EditText) view.findViewById(R.id.txtdiscount);
mydiscount.setFocusableInTouchMode(true);
mydiscount.setFocusable(true);
}
});
I solved this issue by myself and now its working fine. I just have taken another textview and two new edittext inside setOnClickListener. I just added below code inside setOnClickListener.
TextView mynewtotal = (TextView) view.findViewById(R.id.txtprice);
EditText mycartonprod = (EditText) view.findViewById(R.id.txtordercarton);
mycartonprod.setFocusableInTouchMode(true);
mycartonprod.setFocusable(true);
EditText myprod = (EditText) view.findViewById(R.id.txtproduct);
myprod.setFocusableInTouchMode(true);
myprod.setFocusable(true);
Related
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
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]);
}
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);
}
}
}
I have done the following things in my program:
I am generating some Buttons programmatically in my MenuItemsActivity class. I have a Listview in the xml of the MenuItemsActivity class.
When I click on the button the appropriate contents get loaded in the Listview. I just refresh the activity i.e I am using the same Listview to load different contents based on the button which is clicked.
I want to do the following:
When the Button is clicked I want to change the background of the button to 'blue_tab` and maintain that same color when the same activity reloads. Can anyone guide me step by step what to do, as I am a newbie to Android.
i = getIntent();
String Salad=i.getStringExtra("Salad");
String cat_name_from_fragment=i.getStringExtra("category name");
final ListView salad_list = (ListView) findViewById(R.id.salads);
category = new ArrayList<HashMap<String, String>>();
items = new ArrayList<HashMap<String, String>>();
db = new DbHelper(MenuItemsActivity.this);
category.clear();
if (i.getStringExtra("category name") != null) {
String getcategory = i.getStringExtra("category name").toString();
items = db.retrieve_item_details(getcategory);
Log.i("sub items", "" + items);
}
else if(cat_name_from_fragment!=null)
{
items = db.retrieve_item_details(cat_name_from_fragment);
}
else
{
items = db.retrieve_item_details("Salads");
}
category = db.retrieve_category_name();
count = category.size();
Log.i("Sqlite database values", "" + count + " " + category);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
LinearLayout l1 = (LinearLayout) findViewById(R.id.tableRow1);
int i = 0;
for (HashMap<String, String> map : category)
for (Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
TextView tv2 = new TextView(this);
tv2.setLayoutParams(new LinearLayout.LayoutParams(40, 90));
Log.i("map", "" + value);
final Button tv1 = new Button(this);
tv1.setId(i);
tv1.setText(value);
tv1.setTextSize(35);
tv1.setTextColor(Color.parseColor("#1569C7"));
tv1.setGravity(Gravity.CENTER);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup));
tv1.setLayoutParams(new LinearLayout.LayoutParams(300,90));
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
});
/*TextView tv2 = new TextView(this);
tv2.setText(" ");
tv2.setTextSize(10);
tv2.setGravity(Gravity.CENTER);*/
l1.addView(tv1);
l1.addView(tv2);
i++;
Log.e("i count ", "" + i);
}
final int imageArra[] = { R.drawable.leftbar_logo ,R.drawable.leftbar_logo};
ListAdapter k = new SimpleAdapter(MenuItemsActivity.this, items,
R.layout.menulist, new String[] { "Item_Name", "Desc",
"Currency", "Price","url","veggie","cat" }, new int[] { R.id.cat_name,
R.id.textView1, R.id.textView2, R.id.textView3,R.id.url,R.id.veggie,R.id.Category}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final View v = super.getView(position, convertView, parent);
final ImageView im=(ImageView)v.findViewById(R.id.imageView1);
TextView url=(TextView)v.findViewById(R.id.url);
TextView veg=(TextView)v.findViewById(R.id.veggie);
String vegg=veg.getText().toString();
ImageView imagevegs=(ImageView)v.findViewById(R.id.veggies);
Log.i("veggie",""+vegg);
if(vegg.compareToIgnoreCase("Veg")==0)
{
imagevegs.setImageResource(R.drawable.veg);
imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
else
{imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imagevegs.setImageResource(R.drawable.non);
}
final String urls="http://166.62.17.208/"+url.getText().toString();
Log.i("urls",""+urls);
imageLoader.DisplayImage(urls,im);
//return super.getView(position, convertView, parent);
return v;
}
};
salad_list.setAdapter(k);
You can use PreferenceManager to save data and use it when the app is reloaded/restarted
sample:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
if(PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).getString("button", "").length != 0)
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
else
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).edit();
editor.putString("button", "1");
editor.commit();
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
}
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
i tried to add two textViews to list item.that data get from list. when the list print, it display correctly. But in list view its not print correctly. Can anyone help me?
This is the custom adapter class.
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
final String text1 = listData.get(0);
final String text2 = listData.get(1);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
This is the activity code.
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
I want to add user name, below of that it's rate.
This is should be the output list.
01-23 11:59:09.102: D/Data(4873): omali 3.5
01-23 11:59:09.102: D/Data(4873): sunil 2
01-23 11:59:09.102: D/Data(4873): kuma#fh.com 1.5
01-23 11:59:09.102: D/Data(4873): fhhhy#ghj.com 0.5
First of all, the way you are building the list, it will never work, since you are deleting it and creating a new one in every iteration, so when you create the adapter, in the listyou only have the last item.
I would do:
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>(); //added
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
//removed listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(new Pair<String,String>(userName,ratOut ));//added
//removed listData.add(userName);
//removed listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
Then, in the custom adapter class, you retrieve that data simply by
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
//only this 3 lines change
Pair<String,String> item= listData.get(arg0);
final String text1 = item.first;
final String text2 = item.second;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
You are always printing the wrong data, regardless of the position of the item
final String text1 = listData.get(0);
final String text2 = listData.get(1);
So Better take the Different lists of the username and ratOut and display the data
final String text1 = userNameListData.get(arg0);
final String text2 = ratOutListData.get(arg0);
Here arg0 is the position
Replace this:
final String text1 = listData.get(0);
final String text2 = listData.get(1);
with:
final String text1 = listData.get(2*arg0);
final String text2 = listData.get((2*arg0)+1);
change to:
final String text1 = listData.get(arg0*2);
final String text2 = listData.get(arg0*2+1);
and override:
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size()/2;
}
As you are adding both the text in one arraylist 0,1 belong to first item and 2,3 belong to 2nd and so on.
Also size of the list view item would be half of the size of arraylist.
Try this.
also change this:
listData = new ArrayList<String>();//<--out side for loop
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}