What is the best practice to set text for a textview with a given string and some value from my database?
My MainActivity:
MyModel model;
TextView title = (TextView) findViewById(R.id.tvTitle);
title.setText("Username: ", model.getName());
My Model
private String name;
public String getName() {
return name;
}
I couldn't find a solution so far.
The method setText() has several signatures, but the one you need is:
public final void setText (CharSequence text)
So you could do:
title.setText("Username: " + model.getName());
but AS usually complains in these cases that you should avoid concatenating strings inside setText(),
so what you can do is:
String str = "Username: " + model.getName();
title.setText(str);
Also you should consider to store literal values like "Username: " in resources like:
<string name="username">Username:</string>
and use it like this:
String str = getResources().getString(R.string.username) + model.getName();
title.setText(str);
Creating getters and setters are a good practice, which you can automatically generate in Android Studio after defining the variables for the model. Other than that I dont know why in your getName() your method wants to return a long and you are actually returning a string. Change long to String
like this :
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
Everything others have said about concatenating strings outside of the setText method is valid. As far as placement in the Activity or Fragment (I'm using a Fragment in this example), I use the follow conventions:
Declare my class fields in the class body outside of my methods (for class-wide access)
public class MyFragment extends Fragment {
private TextView titleView;
public MyFragment() {
//Constructor
}
// and so on ...
}
Then, find my TextView reference once the Fragment is inflated, and if needed immediately, set its value
// ...
#override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_container, container, false);
titleView = view.findViewById(R.id.title);
String titleStr = "Username: " + model.getName();
titleView.setText(titleStr);
return view;
}
// ...
If I'm expecting the database value in question to change (for example the user updating their username in settings) then I may also wish to make use of certain lifecycle methods that trigger when a Fragment (or Activity) resumes after being suspended, but is not completely rebuilt.
// ...
#override
public void onResume() {
titleStr = "Username: " + model.getName();
titleView.setText(titleStr);
}
// ...
Here's a link regarding the Android Activity Lifecycle if you're not familiar with it, and here's a good rundown on Fragments. Hope this helps.
Related
I have a static class:
public static void culculateFprice(){
TextView FinalBuy = (TextView) findViewById(R.id.buyText);
int Pprice = MainActivity.pepperoni.getFinalPrice();
int Cprice = MainActivity.calzone.getFinalPrice();
int QCprice = MainActivity.quattrostagioni.getFinalPrice();
int QFprice = MainActivity.quattroformaggi.getFinalPrice();
int Mprice = MainActivity.mexican.getFinalPrice();
int FinalPrice = Pprice + Cprice + QCprice + QFprice + Mprice;
FinalBuy.setText("Стоимось вашего заказа: " + FinalPrice + " руб.");
}
How can I use find findViewById in this class?
I call this method from this method
public static void onPlus(int i){
ArrayList<String> list = listok();
switch (list.get(i)){
...
}
adapteR.refreshData(listokadd());
culculateFprice();
}
And have problem "Non-static method "findViewById(int)" cannot be referenced from a static context"
I assume this function exists in your Activity class and you would like to process some information based on the View. There are two ways you can solve this:
Remove the static modifier and let the instance take care of this.
Create a field that holds a View reference that gets created as soon as your layout is set.
So your Activity will hold the field:
class MyActivity extends Activity {
static View FinalBuy; // needs to be static, otherwise would give same error
}
#Override
void onCreate(Bundle savedInstance) {
// after setLayout
FinalBuy = (TextView) findViewById(R.id.buyText);
}
But to save your code from a potential runtime error, use an if...else block in your static method:
public static void culculateFprice(){
if(FinalBuy != null) {
// your code here.
}
}
This problem is basic Java and not Android. That is how Java language is designed to provide instance vs. static methods for the programs.
This static View declaration leads to a potential design flaw because this View will outlive the Activity. Instead of this, you should consider using the approach I suggested in the list as option 1 and see why you are unable to use an instance method in your program. You should read more on this thread.
This will likely need you to change your other fields of MainActivity to be declared as non-static as well!
I have searched the documentation end-on-end and tried numerous things but none worked so far.
The issue is that, after I have successfully built a class with working query system (SearchContentActivity.java) and its supporting classes (UserContent.java, UserContentAdapter.java, UserContentBoxapp.java), I have to build a new database for One-to-Many relationship with the content (CategoryNameSet.java, with only one attribute "String categoryName").
Most of the codes looks like the other query:
public class TestActivity extends AppCompatActivity {
private TextView textView;
private BoxStore store;
Box<CategoryNameSet> categoryNameSetBox;
List<CategoryNameSet> categoryNameSetList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
textView = (TextView) findViewById(R.id.activity_test_textView);
store = ((UserContentBoxApp) getApplication()).getBoxStore();
categoryNameSetBox = store.boxFor(CategoryNameSet.class);
categoryAdd();
}
private void categoryAdd() {
categoryNameSetList = categoryNameSetBox.query().contains(CategoryNameSet_.categoryName, "yahoo").build().find();
String text = "categoryNameSet instances: " + categoryNameSetBox.count()
+ ". Name of instances: " + categoryNameSetList;
textView.setText(text);}
}
When I ran the code, it displays full package name, class name, and #random string
example:
categoryNameSet instance: 155. Name of instances:
[com.google.test.myapp.CategoryNameSet#ccd488d, com.google.test.myapp.CategoryNameSet#9910a42]
The number of results were two, which was the number of times put "yahoo" into categoryNameSetBox in another class. This indicates that the query can search and "see" the results.
How could I change the result from these random strings to categoryName attribute contained in the CategoryNameSet.java?
I think you are looking for property queries, which do not return back an object, but only a single property of each object.
For example,
public void show_message(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
I want this method add auto Activity.java when create new activity or java class.
I want to save different methods like this and include it in the my project quickly where it is needed.
What you should do is create a BaseActivity and make your activity extend this BaseActivity. Add all the default methods in this activity so you can use them everywhere. You can refer this Github project for reference. It uses MVP.
Here is direct link to BaseActivity.
You just need to make a Common Utilities class. Just copy and paste the class in whatever project you are using it. Just make its method access specifiers as public staic so that you can easily access it.
For e.g.
CommonUtilities.showToastMessage(String text);
What I would do is create a config class and store all these small things in it. For example have a look at this :
public class Config {
public Context context;
public String sharedPrefsName;
public String carTablesName, carsTableCarColumn, databaseName;
public int databaseNewVersion, databaseOldVersion;
public boolean showNotificationsToCustomer;
public String customerNotificationState;
public String userMobile;
public SharedPreferences preferences;
public String customerChatTableName;
public String customerChatMessageColumn;
public String customerChatSentByCustomerColumn;
public String customerChatTimeColumn;
public String loggedInUserId;
public String loggedInUserName;
public String customerChatSupportNotifyingUrl;
public Config(Context context) {
this.context = context;
customerChatSupportNotifyingUrl = "";
customerChatTableName = "customerChat";
customerChatMessageColumn = "customerMessage";
customerChatTimeColumn = "sentOn";
customerChatSentByCustomerColumn = "isSentByCustomer";
sharedPrefsName = context.getString(R.string.shared_prefs_login_validator);
preferences = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
customerNotificationState = context.getString(R.string.customer_notification_state);
showNotificationsToCustomer = preferences.getBoolean(customerNotificationState, true);
carTablesName = context.getString(R.string.user_car_table);
carsTableCarColumn = context.getString(R.string.user_car_table_car_column);
databaseName = context.getString(R.string.user_db);
databaseNewVersion = 3;
databaseOldVersion = 1;
loggedInUserId = preferences.getString(context.getString(R.string.user_db), "");
userMobile = preferences.getString(context.getString(R.string.user_mobile), "");
loggedInUserName = preferences.getString(context.getString(R.string.user_name), "");
}
}
I've placed all the constants in a single file so you need not look at them always. If your app grows in size this would be extremely useful.
For using a progress dialog I use a class like this :
public class MyProgressDialog extends ProgressDialog {
String title, message;
public MyProgressDialog(Context context, String title, String message) {
super(context);
if (!title.equals("")) this.setTitle(title);
this.setMessage(message);
this.setCancelable(false);
this.setIndeterminate(false);
}
}
This is nothing but a single class that extends ProgressDialog.So you can aquire all the functionalities of the progress dialog class.
Similarly for toast you could do the same. If you want them to appear when the activity gets created simply keep this:
MyProgressDialog dialog=new MyProgressDialog(this,"title","message");
dialog.show();
in your activity's onCreate() method. You can do the same for toast too.
In case if it is a java class just create a constructor and keep that snippet in that constructor..
You need to read about "File Templates" https://riggaroo.co.za/custom-file-templates-android-studio/ this a large topic, but this is worth it.
I use Sugar ORM for Android Development via Android Studio.
But I think I have a quite similar question.
How can I display one/multiple result queries as String or int?
My entity looks like this:
public class PersonsDatabase extends SugarRecord<PersonsSelection>{
String adultText, childText;
int adultCount, childCount;
public PersonsDatabase()
{
}
public PersonsDatabase(String adultText, String childText, int adultCount, int childCount)
{
this.adultText = adultText;
this.childText = childText;
this.adultCount = adultCount;
this.childCount = childCount;
this.save();
}
}
It saves correctly. But when I want to display like this:
public class PersonsSelection extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persons_selection);
PersonsDatabase personsDatabase = new PersonsDatabase("1 Adult","No Childs",1,0);
List<PersonsDatabase> personsList = PersonsDatabase.findWithQuery(PersonsDatabase.class,"Select adult_Text from PERSONS_DATABASE");
list = (ListView)findViewById(R.id.listView);
list.setAdapter(new ArrayAdapter<PersonsDatabase>(this, android.R.layout.simple_list_item_1, personsList));
}
}
I get something like: PACKAGENAME.PersonsDatabase#4264c038
But I want the values that I wrote in the constructor.
Thanks for help.
From the docs on ArrayAdapter:
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
In short: just override the toString() method in your PersonsDatabase class to return the desired textual respresentation.
Alternatively:
To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.
(again from the docs). Plenty of examples out there on how to go about doing that.
Simply override the toString() method.
In that method, return whichever database value you want to retrieve.
In my case, I returned a variable name that I needed (i.e. message) :
#Override
public String toString() {
return message;
}
We started an informal Android development group at work. We'll each be adding semi-independent Activities to a single app. Goofing around yesterday, the best I could come up with to make this 'easy' was to have our main activity be a GridView and allow developers to 'register' their Activities in the main Activity via an element in a hard-coded array of 'ActionItems':
private final ActionItem[] actionItems = {
new ActionItem(R.drawable.dms_to_dd, "DMS to/from DD", DegreeConverter.class)
};
where an ActionItem is just this:
public class ActionItem {
private int drawingID;
private String label;
private java.lang.Class<?> activity;
public ActionItem(int drawingID, String label, Class<?> activity) {
this.drawingID = drawingID;
this.label = label;
this.activity = activity;
}
public int getDrawingID() {
return drawingID;
}
public String getLabel() {
return label;
}
public Class<?> getActivity() {
return activity;
}
}
To get people started I created the first simple Activity/ActionItem and it is registered as shown above.
We want the drawable to be there for the image in the GridView and the String for labeling and, most importantly, the class that will be launched through an Intent when the corresponding GridView item is selected.
All of this works. However, it would be nice if folks didn't have to edit the main Activity to make this work. I was hoping we could read this same information (for the ActionItem) from a text file before populating the GridView. The drawable id and the String are no problem. So the main question: How might we specify that class in a text file?
Is there someway to create a java.lang.Class instance from a name (String/char[])?
Is there some better way to do what I've described above?
Happy to provide further details if helpful.
Have you tried with:
Class.forName("com.something.MyClass")
http://developer.android.com/reference/java/lang/Class.html#forName(java.lang.String)
You can read the name from a file, and set the string in the forName method.
So, you can do something like this:
public ActionItem(int drawingID, String label, String activityClassName) {
this.drawingID = drawingID;
this.label = label;
this.activity = Class.forName(activityClassName);
}
Using reflection, an example below:
Class theClass = Class.forName("YourClass");
YourClass instancevariable = (YourClass)theClass.newInstance();