screen output **write(A,'+',B,'=',C)** for android - android

1) is there any easy way for screen output like in Pascal: write(A,'+',B,'=',C) ?
I tried :
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_layout);
Toast.LENGTH_LONG).show();
int A,B,C;
A=4;
B=8;
C=A+B;
String text = getString(A,"+",B,"=",C);
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(text);
//Toast.makeText(this,text, Toast.LENGTH_LONG).show();
}
but ít doesn't work.
Every time I will get "...apliccation has stopped"
the best would be something like :
tv.setText(A,"+",B,"=",C) //without stringing integers;
thanks for all your help.

Concatenate the string and use setText afterwards:
tv.setText(A + "+" B + "=" + C);
For longer text, use a StringBuilder.

This is wrong getString(A,"+",B,"=",C)
you want
String text = A + "+" + B + "=" + C;
getString is used for retrieving package string resources
http://developer.android.com/reference/android/content/Context.html#getString(int)

Related

Best way to put variables in a Textview?

I try to put one or more variables in a TextView.
For exemple :
Hello I am a "girl" and I live in "Boston"
I would like to know what is the best way to do it :
Can i do it directly in the layout file ?
Can i do it only via Java Class ?
Can i do it via values/styles.xml ?
For now i do it like this :
String text1 = "Hello I am a ";
String text2 =" and I live in ";
String var1= preferences.getString("sex", "null");
String var2= preferences.getString("city", "null");
TextView Text = (TextView) findViewById(R.id.text);
Text.setText(text1 + var1 + text2 + var2);
It works yes but in fact my TextView are very long so I don't think my way is really appropriate.
Can i have some advice ?
Use String.format(String format, Object... args)
String sex = preferences.getString("sex", "null");
String city = preferences.getString("city", "null");
String str = String.format("Hello I am a %s and I live in %s", sex, city);
TextView text = (TextView) findViewById(R.id.text);
text.setText(str);
Note - Avoid concatenation in TextView.setText()
If Text-view is really long then you should be try this.
String var1= preferences.getString("sex", "null");
String var2= preferences.getString("city", "null");
Text.setText("Hello I am a"+var1+"\n"+"I live in"+var2);
This is good way Present Text in Text View

Data passing through intents with string returns null

I'm trying to pass a string and a few integers to another activity. The problem is that the integers can be passed successfully, but not the string value. I'm searched the forum for similar questions, but I was not able to find my problem.
Main Activity Class:
public void onClick(View v)
{
Intent debug = new Intent("bluetooth_4.pack.USBDebugMode");
if((port != null))
{
debug.putExtra("port", port.toString());
debug.putExtra("buadRate", buadRate);
debug.putExtra("dataBits", dataBits);
debug.putExtra("stopBits", stopBits);
debug.putExtra("parity", parity);
startActivity(debug);
Toast.makeText(MainActivity.this, "Switching to USB Debug Mode" , Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "You haven't selected a device yet!" , Toast.LENGTH_SHORT).show();
}
}
New Activity Class:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.usb_debug_main);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(myButtonListener1);
button2.setOnClickListener(myButtonListener2);
ActionBar actionBar = getActionBar();
actionBar.hide();
port = getIntent().getStringExtra(port);
buadRate = getIntent().getIntExtra("buadRate", 0);
dataBits = getIntent().getIntExtra("dataBits", 0);
stopBits = getIntent().getIntExtra("stopBits", 0);
parity = getIntent().getDoubleExtra("parity", 0);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
TextView text = (TextView) findViewById(R.id.textView2);
text.append("Port: " + port + "\r\n");
text.append("Buad Rate: " + buadRate + "\r\n");
text.append("Data Bits: " + dataBits + "\r\n");
text.append("Stop Bits: " + stopBits + "\r\n");
text.append("Parity: " + parity + "\r\n");
}
I have a text box, and all it does is that the displays some data, while parameters such as buad rate, data bits, stop bits, and parity has data, port always return null.
However, port must not be null in order to start the activity.
Change this line
port = getIntent().getStringExtra(port);
To
port = getIntent().getStringExtra("port");
You forget to pass the correct key in your NewActivityClass, i have a tip for you!
Always define public constants some where in your app. ( i usually create MyConstants.Java for that purpose. This is the only way in which you can be sure that you are passing the correct keys in both sending class and receiving class
Thanks.

Reference string resource from code

I have the following string declared in strings.xml:
<string name="last_msg">Your last click was on</string>
Now when someone clicks a button, I want a textview to show this string, with a space, then a variable value that is a timestamp.
Unfortunately, using #string/last_msg isn't working, and I'm not sure how to do this properly so I'm not hardcoding in content.
Here's my code for the onClick function:
public void showMsgNow(View view) {
TextView lastMsg = (TextView)findViewById(R.id.textView2);
long currentTimeStamp = System.currentTimeMillis();
lastMsg.setText(#string/last_msg + " " + currentTimeStamp);
}
I'm a newbie, any help would be great !
I found the answer on Google:
getString(R.string.last_msg)
you cant access String directly by #, for that you need to have context resource and then just do this...
lastMsg.setText(context.getResources().getString(R.string.last_msg) + " " + currentTimeStamp);
in your case use
<string name="last_msg">Your last click was on %1$s</string>
implementation:
public void showMsgNow(View view) {
TextView lastMsg = (TextView)findViewById(R.id.textView2);
long currentTimeStamp = System.currentTimeMillis();
lastMsg.setText(context.getResources()
.getString(R.string.last_msg, currentTimeStamp));
}
// getString is method of context
if (this instanceof Context)
//If you are in Activity or Service class
lastMsg.setText(getString(R.string.last_msg)+ " " + currentTimeStamp);
else
//you need to context to get the string
lastMsg.setText(getString(mContext,R.string.last_msg)+ " " + currentTimeStamp);
public String getString(Context mContext, int id){
return mContext.getResources().getString(id);
}
use below line
lastMsg.setText(getString(R.string.last_msg) + " " + currentTimeStamp);
Try this :
lastMsg.setText(R.string.last_msg + " " + new SimpleDateFormat(d-MM-YYYY).format(new Date()));

How can I display a previous EditText user input, as well as a recent EditText user input?

I have a SharedPreferences that saves EditText input from one activity and displays the String value in another activity.
When I enter an input into the EditText fields and press (a button I created) "Save" (which commits the EditText to editor), the file is stored and displayed successfully.
However, I want it so that everytime the user adds another entry in the EditText, it displays underneath the previously added EditText input. Like a list. I understand that both are reading from the SharedPreferences file. How would I go about doing this?
CustomStoreEditActivity - Just storing the user inputs (EditText entries):
final Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (saveButton.isClickable()) {
SharedPreferences prefs = getSharedPreferences(
"customtime", 0);
// prefs.registerOnSharedPreferenceChangeListener(this);
final SharedPreferences.Editor edit = prefs.edit();
EditText shopName = (EditText) findViewById(R.id.shopName);
EditText open1 = (EditText) findViewById(R.id.open1);
EditText close1 = (EditText) findViewById(R.id.close1);
EditText open2 = (EditText) findViewById(R.id.open2);
EditText close2 = (EditText) findViewById(R.id.close2);
EditText open3 = (EditText) findViewById(R.id.open3);
EditText close3 = (EditText) findViewById(R.id.close3);
EditText open4 = (EditText) findViewById(R.id.open4);
EditText close4 = (EditText) findViewById(R.id.close4);
EditText open5 = (EditText) findViewById(R.id.open5);
EditText close5 = (EditText) findViewById(R.id.close5);
EditText open6 = (EditText) findViewById(R.id.open6);
EditText close6 = (EditText) findViewById(R.id.close6);
EditText open7 = (EditText) findViewById(R.id.open7);
EditText close7 = (EditText) findViewById(R.id.close7);
EditText comments = (EditText) findViewById(R.id.comments);
edit.putString("shopName", shopName.getText().toString());
edit.putString("Monday1", open1.getText().toString());
edit.putString("Monday2", close1.getText().toString());
edit.putString("Tuesday1", open2.getText().toString());
edit.putString("Tuesday2", close2.getText().toString());
edit.putString("Wednesday1", open3.getText().toString());
edit.putString("Wednesday2", close3.getText().toString());
edit.putString("Thursday1", open4.getText().toString());
edit.putString("Thursday2", close4.getText().toString());
edit.putString("Friday1", open5.getText().toString());
edit.putString("Friday2", close5.getText().toString());
edit.putString("Saturday1", open6.getText().toString());
edit.putString("Saturday2", close6.getText().toString());
edit.putString("Sunday1", open7.getText().toString());
edit.putString("Sunday2", close7.getText().toString());
edit.putString("comments", comments.getText().toString());
edit.commit();
Intent myIntent = new Intent(getBaseContext(),
CustomStoreActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(myIntent);
Toast.makeText(getBaseContext(), "Opening Hours Saved!",
Toast.LENGTH_SHORT).show();
}
}
});
}
CustomStoreActivity - where I retrieve the data and display:
public void onResume() {
SharedPreferences prefs = getSharedPreferences("customtime", 0);
String shopName = prefs.getString("shopName", "Empty");
String shopTimeM1 = prefs.getString("Monday1", " ");
String shopTimeM2 = prefs.getString("Monday2", " ");
String shopTimeT1 = prefs.getString("Monday1", " ");
String shopTimeT2 = prefs.getString("Monday2", " ");
String shopTimeW1 = prefs.getString("Monday1", " ");
String shopTimeW2 = prefs.getString("Monday2", " ");
String shopTimeTH1 = prefs.getString("Monday1", " ");
String shopTimeTH2 = prefs.getString("Monday2", " ");
String shopTimeF1 = prefs.getString("Monday1", " ");
String shopTimeF2 = prefs.getString("Monday2", " ");
String shopTimeS1 = prefs.getString("Monday1", " ");
String shopTimeS2 = prefs.getString("Monday2", " ");
String shopTimeSU1 = prefs.getString("Monday1", " ");
String shopTimeSU2 = prefs.getString("Monday2", " ");
String shopComments = prefs.getString("comments", "");
TextView displayPrefs = (TextView) findViewById(R.id.displayPrefs);
displayPrefs.setText(
"------------------------------------------------------------" +
"\n\nSHOP NAME: " + shopName +
"\n\nTIMINGS: " + "\n\n Monday: " + shopTimeM1 + " - " + shopTimeM2 +
"\n Tuesday: " + shopTimeT1 + " - " + shopTimeT2 + "\n Wednesday: "
+ shopTimeW1 + " - " + shopTimeW2 + "\n Thursday: " + shopTimeTH1
+ " - " + shopTimeTH2 + "\n Friday: " + shopTimeF1 + " - " + shopTimeF2 +
"\n Saturday: " + shopTimeS1 + " - " + shopTimeS2 + "\n Sunday: " +
shopTimeSU1 + " - " + shopTimeSU2 +
"\n\nCOMMENTS: " + shopComments +
"\n\n------------------------------------------------------------");
super.onResume();
}
Thank you for your humble time.
It sounds to me like you are trying to build a list. Pardon my initially nebulous answer but I promise it will eventually focus in on a point.
What I would recommend for the overall framework is this:
You have an Activity (presumably your CustomStoreActivity) which displays a list of saved Store objects. Store will need to implement Parcelable or Serializable (preferably the former).
On this Activity there is a New Store button (if you are following Android design convention, this is likely as a "+" button in the Action Bar).
On pressing the New Store button, your CustomStoreActivity calls startActivityForResult(CustomStoreEditActivity.class).
Your CustomStoreActivity implements onActivityResult as per the answer on the last question you asked. Here, you will get a result code and an Intent which contains Extras (to be retrieved by intent.getExtras()).
Your CustomStoreEditActivity takes user input, as above, and instead of writing it to SharedPreferences it uses the information to create a new Store object which contains all of the information, and uses setResult(RESULT_OK,intent) where intent is the Intent to which you have added the Store extra (as a Parcelable).
This means that when CustomStoreEditActivity calls finish() (which you will do instead of using an intent to re-launch your CustomStoreActivity because the CustomStoreActivity is already just behind it) you'll get your call to onActivityResult and can pull the Store object out of the Extras from the Intent you just passed back.
And now to the point:
You can use a ListView in your CustomStoreActivity, and use a StoreAdapter that extends ArrayAdapter<Store>, and for each item in the list of Stores adds a view to the list containing that Store's name. Then you'll just add your new Store object to the array you passed into your StoreAdapter, and call adapter.notifyDataSetChanged() in onActivityResult and that should take care of it.
If ultimately you need to persist this data between application sessions, you should handle writing the Store objects to the SharedPreferences in the onPause method of CustomStoreActivity (it being the keeper of the list) rather than touching your shared preferences from every direction. You can then read in the list again in onCreate should you need to.
I know it's a lot to parse through/digest, but it's a pretty standard mechanism for passing data between Activity constructs in Android and for persisting data.
Let me know if you have any questions on the implementation and I'll see what I can do! :)
Take a look at my answer here: Show a drop down list of recently entered text when clicks on an android edit box
All you would really need to do is change the preference mode to public, not private.

Simple If Statement

I am trying to pass two variables from one screen to another. From the previous screeen you click a button, 1 or 2 and it passes that value on. It also passes the value 2 as the correct value. I know they are both working as I output each variable on the next screen. Here is the code. It always outputs wrong though.
Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText == correct){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
titles.setText("Wrong" + newText + " " + correct + "");
}
because you are not comparing the string. you are comparing if both are pointing to same object.
to compare string use
if(nexText.equals(correct))
if(newText == correct)
This will always be false. To compare the contents of two Strings character by character, use the .equals method:
if( newText.equals(correct) )
Using == on objects in Java means you are comparing the values of the memory address stored in these pointers/references. Since they are different String objects, they will never have the same address.
You don't compare Strings this way, rewrite code this way to get things done:
Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText.equals(correct)){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
titles.setText("Wrong" + newText + " " + correct + "");
}

Categories

Resources