For loop runs twice the result? - android

I am new to Android. I am creating a native MobilePOS Android application for printng by using Bluetooth. This is my code:
private void showandadd() {
/*String num="";
num=num+String.valueOf(number);*/
String string1="";
String string2="";
String string3="";
if(num==""){
Toast.makeText(this,"Wrong input!! try again", Toast.LENGTH_LONG).show();
}
if(flag==1) {
getItem(directadd);
if(blankflag!=1) {
int updatedPrice = Integer.parseInt(this.price);
int data = Integer.parseInt(this.num);
if(data==0){
Toast.makeText(this,"Wrong input!! insert different quantity number", Toast.LENGTH_LONG).show();
}else {
int d = updatedPrice * data;
this.price = d + "";
// String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add(num);
amount.add(price);
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}
}
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}else {
getItem(directadd);
if(blankflag!=1) {
//String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add("1");
amount.add(price);
num = "";
}
directadd="";
blankflag=0;
}
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
}
There are 3 strings assigned to result.
I am getting result twice when I am press second item.
when I am select first item getting "Itemname Quantity ampount" format like
Tea 1qty 10rs...when I enter second item output will came first item+first item+second item show like this:
Tea 1qty 10rs
Tea 1qty 10rs
Coffee 1qty 12rs
I want to get result
Tea 1qty 10rs
Coffee 1qty 12rs
like this...please any one can help me

A simple example would be to use one label and append to it each time you add a new item.
Instead of this:
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
Change it to this:
str = this.selection.getText().toString();
str += printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
this.selection.setText(str);
num="";

Related

How to set text of multiple codes in one text view

Please have a look at this code and at the bottom is the question. Thanks for your help
int i,fact=1;
String value = edtLCM.getText().toString();
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
System.out.print(i + " x ");
} else {
System.out.print(i);
String two = String.valueOf(i);
}
}
System.out.println(" = " + fact);
LCMResult.setText("");
I want to set the textview of all the 3 "System.out.println()" in one line. The desired result would be like this(if a user input 4 in the edtLCM): 4x3x2x1 = 24
Use a StringBuilder to put the new strings together instead of using system out.
int i,fact=1;
String value = edtLCM.getText().toString();
StringBuilder sb = new StringBuilder(); // find a better name
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
// System.out.print(i + " x ");
sb.append(i).append(" x ");
} else {
//System.out.print(i);
sb.append(i);
String two = String.valueOf(i);
}
}
//System.out.println(" = " + fact);
sb.append(" = ").append(fact);
String result = sb.toString(); // will be 4 x 3 x 2 x 1 = 24
LCMResult.setText("");

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

How to bring forward a integer

This is activityresult1
Button buttonorder;
TextView textviewcard;
private static final int REQUEST_CODE = 10;
int[] image ={R.drawable.friednoodle, R.drawable.friedrice, R.drawable.steamfish,R.drawable.tehice};
String[] item = {"Fried Noodle", "Fried Rice", "Steam Fish","Iced Tea"};
String[] description = {"Classic Chinese stir fried noodle with prawn and Pork", "Special sauce Fried Rice using indian rice", "HongKong Style Steamed Fish ","HongKong classical iced tea"};
String[] cost={"6","5","25","2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityresult1);
Bundle extras = getIntent().getExtras();
String strcardnumber = extras.getString("Card Number");
textviewcard = (TextView) findViewById(R.id.textviewcard);
textviewcard.setText("Welcome, " + strcardnumber + " !" + "\nPlease select the food you want ! : ");
itemList = new ArrayList<DataInfo>();
itemList.add(new DataInfo(item[0], image[0], description[0], cost[0]));
itemList.add(new DataInfo(item[1], image[1], description[1], cost[1]));
itemList.add(new DataInfo(item[2], image[2], description[2], cost[2]));
itemList.add(new DataInfo(item[3], image[3], description[3], cost[3]));
final MenuAdapter adapter = new MenuAdapter(this);
ListView listView = (ListView)findViewById(R.id.list);
LVAdapter lvAdapter = new LVAdapter(this, itemList);
//listView.setAdapter(lvAdapter);
listView.setAdapter(adapter);
for (int i = 0; i < item.length; i++) {
adapter.addData(String.valueOf(i), item[i], image[i], description[i], cost[i]);
}
buttonorder = (Button) findViewById(R.id.suborder);
buttonorder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] a = adapter.getQuantity();
Toast.makeText(getApplicationContext(), "Noodle: " + a[0] + "\nRice: " + a[1] + "\nSteam fish: " + a[2] + "\nIced tea: " + a[3], Toast.LENGTH_LONG).show();
int sum = Integer.parseInt(adapter.getQuantity()[0])*Integer.parseInt(cost[0]) +
Integer.parseInt(adapter.getQuantity()[1])*Integer.parseInt(cost[1]) +
Integer.parseInt(adapter.getQuantity()[2])*Integer.parseInt(cost[2]) +
Integer.parseInt(adapter.getQuantity()[3])*Integer.parseInt(cost[3]);
Intent myIntent = new Intent(activityresult1.this, activityresult2.class);
myIntent.putExtra("sum",sum);
startActivity(myIntent);
Intent intent = new Intent(getApplicationContext(), activityresult2.class);
Bundle bundle = new Bundle();
bundle.putString("Noodle quantity", adapter.getQuantity()[0]);
bundle.putString("Rice quantity", adapter.getQuantity()[1]);
bundle.putString("Fish quantity", adapter.getQuantity()[2]);
bundle.putString("Iced tea", adapter.getQuantity()[3]);
bundle.putInt("sum", sum);
bundle.putBoolean("ANI", adapter.getItem(0).isAddInisCheck());//add noodle ingredients
bundle.putBoolean("ARI", adapter.getItem(1).isAddInisCheck()); // add rice ingredients
bundle.putBoolean("AFI", adapter.getItem(2).isAddInisCheck());// add fish ingredients
bundle.putBoolean("AIT", adapter.getItem(3).isAddInisCheck()); // add ice tea ingredients
intent.putExtras(bundle);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
how do i sent the calculated sum from activityresult1 to activityresult2
static public String txtOrder ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityresult2);
Bundle bundle = getIntent().getExtras();
String strfnq = bundle.getString("Noodle quantity");
String strfrq = bundle.getString("Rice quantity");
String strfsq = bundle.getString("Fish quantity");
String stricq = bundle.getString("Iced tea");
Integer strsum = bundle.getInt("sum");
boolean addNingc = bundle.getBoolean("ANI");
boolean addRingc = bundle.getBoolean("ARI");
boolean addFingc = bundle.getBoolean("AFI");
boolean addTingc = bundle.getBoolean("AIT");
// boolean addmoneyc = bundle.getBoolean("AMY");
Intent mIntent = getIntent();
int sum = mIntent.getIntExtra("sum",strsum);
TextView costtext = (TextView)findViewById(R.id.costtext);
costtext.setText(getIntent().getExtras().getString("sum"));
TextView foodorders = (TextView) findViewById(R.id.foodordershow);
foodorders.setText(getIntent().getExtras().getString("Quantity"));
String addNdlThing = "";
if (addNingc) {
addNdlThing = " with addition of ingredients";
}
String addRlThing = "";
if (addRingc) {
addRlThing = " with addition of ingredients";
}
String addSlThing = "";
if ( addFingc) {
addSlThing = " with addition of ingredients";
}
String addTeac = "";
if ( addTingc ) {
addTeac = " with addition of ingredients";
}
foodorders = (TextView) findViewById(R.id.foodordershow);
if(strfnq.equals("") && strfrq.equals("") && strfsq.equals("")&& stricq.equals("")){
txtOrder = "Sorry, You've not ordered any thing , please return to previous menu to order";
}else if (!strfnq.equals("") && !strfrq.equals("") && !strfsq.equals("")&& stricq.equals("")) {
txtOrder = "Thank you , You've ordered\n" + strfnq + " fried noodle" + addNdlThing +" and\n"+ strfrq
+ " fried rice" + addRlThing +" and\n" + strfsq + " Steam fish " + addSlThing + "and\n" + stricq + " Steam fish " + addTeac;
} else {
txtOrder = "Thank you , You've ordered\n";
if(!strfnq.equals("")){
txtOrder = txtOrder + strfnq + " fried noodle" + addNdlThing;
}
if(!strfrq.equals("")){
txtOrder = txtOrder + strfrq + " fried rice" + addRlThing;
}
if(!strfsq.equals("")){
txtOrder = txtOrder + strfsq + " Steam fish" + addSlThing;
}
if(!stricq.equals("")){
txtOrder = txtOrder + stricq + " Iced Tea"+ addTeac;
}
}
foodorders.setText(txtOrder);
}
i want to calculate the money spent in result1 and display it in result 2
i have tried using the method they written at the bottom but it dont work as i dont know what to fill in for some . please help me , i really need help on this , and i am typing alot to make the word count so i can post , as i have too much codes they say , and please stop disliking this post , dont be such persons , like this and it will be happy for both parties , asking question dont mean i am stupid
You can sent the value of the sum to the next activity and get it via Bundle in the other activity like this. Think that your are sending it to the activity B
Intent i= new Intent(this,B.class);
i.putExtra("sum",sum);
startActivity(i);
you can send the context to the activity B through either one of the following this,getActivity(),getApplicationContext()
Then inactivity B you can add these lines in onCreate() method, to get the passed content
Bundle MainActivityData= getIntent().getExtras();
int sum= MainActivityData.getString("sum");

Android/Java String Concatenation with Unwanted "\n"

I am writing an Android program that parses data from the Translink API web page. The program works, but I am having an issue with the data that I am storing. It seems that each time the program loops, a "\n" is added to the String itself. Here is the code itself:
private class DownloadWebpageText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String...urls) {
// params comes from the execute() call: params[0] is the url.
try {
// Test Code
for(int h=0; h<prev_stops.size(); h++) {
Document doc = Jsoup.connect("http://api.translink.ca/rttiapi/v1/stops/" + prev_stops.get(h) + "/estimates?&timeframe=120&apikey=XMy98rbwFPLcWWmNcKHc").get();
nextbuses = doc.select("nextbus");
schedules = doc.select("schedules");
String bus_times = "";
temp += "Arrival Times for Stop " + prev_stops.get(h) /*+ " (Previous Stop: " + prev_stop + "): \n" + "\nPrevious Stops: " + prev_stop*/;
for(int i=0; i<nextbuses.size(); i++) {
temp += parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp = temp.concat(", ");
}
temp = temp.concat(parseData(expectedleavetime.get(j).toString()));
}
temp += "\n";
}
temp += "\n";
}
return "";
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
Where the parseData() function is just this:
public String parseData(String input) {
int beg = input.indexOf(">") + 1;
int end = input.lastIndexOf("<") - 1;
return input.substring(beg, end);
}
Here is the output from the console:
Arrival Times for Stop 56549
402:
4:10pm,
4:40pm,
5:10pm,
5:40pm
What I want the output to be like is this:
Arrival Times for Stop 56549
402: 3:40pm, 4:10pm, 4:40pm, 5:10pm
403: .....
You could use an ArrayList, which you define outside all for-loops
// Define our ArrayList
ArrayList<String> allStops = new ArrayList<String>();
// Define a string that holds information about the current stop
String currentStopInfo = "Arrival Times for Stop " + prev_stops.get(h);
for(int i=0; i<nextbuses.size(); i++) {
// Define a temporary String that holds all the times for a specific bus
String temp_2 = parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp_2 += ", ";
}
temp_2 = temp_2.concat(parseData(expectedleavetime.get(j).toString()));
}
// Add the string that holds info for one bus to our Array
allStops.add(temp_2);
}
And when you want to print all of your strings(all of your stops for each bus)(every string contains information about one bus) you just do:
//Print the line that holds the current stop information
System.out.println(currentStopInfo);
for(String x : allStops) {
// Loop through our ArrayList, and print the information
System.out.println(x);
}

Get repeated Entries for Some Items in DataBase!

I am working on an android application. In which i have slideShows. I am parsing these through an xml and after parsing them, saving in the SQLite DB. Majority of the slideshows are saved properly but, sometimes this happens that the slides are saved two times that is, every slide in the slideShow is saved two times obviously with different PK but same content. which should be avoided.
Partial code is here, where i am getting the slides and trying to store them in DB.
ArrayList<SlideShowItem> slideItems = null;
slideItems=Utils.database.getSlideItemOfUrl(Constants.StoriesTable,tempSlideShow.getFullStoryUrl().substring(0, index - 1), type);
if (slideItems == null) {
Log.d("store in DB: ", " when SlideItems == null ");
Log.d("SlideShow Title: ", tempSlideShow.getTitle());
Log.d("SlideShow pub Date: ", tempSlideShow.getPubDate());
slideItems = tempSlideShow.getSlideShow();
Utils.database.storeSlideItem(Constants.StoriesTable, myUrl,slideItems, type);
Utils.topStorySlidesArrayList = slideItems;
slideItems = null ;
} else {
Log.d("SlideShow Title: ", tempSlideShow.getTitle());
Utils.topStorySlidesArrayList = slideItems;
slideItems = null ;
}
and code of function storeSlideItem in DataBase is:
public synchronized void storeSlideItem(String tableName, String, url,ArrayList<SlideShowItem> list, String type) {
System.out.println("size of the Array list: " + list.size());
String newType = null;
if (type == null) {
newType = "List";
}else{
newType = type;
}
ArrayList<SlideShowItem> newList = new ArrayList<SlideShowItem>();
//newList = null;
Iterator<SlideShowItem> iterator = list.iterator();
while (iterator.hasNext())
{
SlideShowItem sSItem = iterator.next();
if(!newList.contains(sSItem))
{
newList.add(sSItem);
}
}
try {
for (int i = 0; i < newList.size(); i++) {
SlideShowItem item = newList.get(i);
String itemUrl = url + i;// Unique URL for the DB;
String imgString = null;
Log.e("Loop Counter", " time " + i);
Drawable drawable = item.getImage();
if (item.getBody() != null) {
item.setBody(item.getBody().replace('\'', '`'));
// replace as it create syntax error for storing data
}
if (item.getSubTitle() != null) {
item.setSubTitle(item.getSubTitle().replace('\'', '`'));
}
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
imgString = Base64.encodeBytes(b);
}
if (isOpen()) {
myDB.execSQL("INSERT INTO " + tableName + "(" + column[1] + "," + column[2] + "," + column[3] + "," + column[4] + "," + column[6]
+ "," + column[7] + ",type) VALUES('" + itemUrl + "','" + item.getSubTitle() + "','" + item.getBody() + "','"
+ item.getImagePath() + "','" + item.getIndex() + "','" + imgString + "','" + newType + "Slide')");
if (item.getBody() != null) {
item.setBody(item.getBody().replace('`', '\''));// " ' "
// replace as it create syntax error for storing data
}
if (item.getSubTitle() != null) {
item.setSubTitle(item.getSubTitle().replace('`', '\''));
}
if (tableName.equals(Constants.StoriesTable)) {
item.setItemId(getItemID(tableName, itemUrl));
Utils.hashListStoriesIds.put(itemUrl, item.getItemId());
if (imgString != null) {
Utils.hashListImages.put(item.getItemId(), new Boolean(true));
} else {
Utils.hashListImages.put(item.getItemId(), new Boolean(false));
}
}
}
}
} catch (Exception e) {
Log.e("Error", "Exception: storeSlideItem type " + e.toString());
} finally {
closeConnection();
}
}
Please tell me anything that can get me out of this irritating problem. Any help is appreciated.
in DB for duplication of slides the view is somewhat like:
1 abc USA 111
2 abc USA 111
and so on this was for one slide of a slideShow. if i have 3 slides in a slideshow, i'll get 6 entries in DB each slide being saved for two times.
Use HashSet instead of ArrayList

Categories

Resources