Android displaying items on screen on that come from a remote db - android

I am facing an issue of having a screen which gets an id from the SharedPreferences and then I call a remote database, and then I have to display that data on the screen.
Is it possible to do that with ViewText or is there another way to place text on the screen after a remote db call is made?
Whats the best way to do that and how do I accomplish it?
Thanks!!

Use a loader for your db call. Once the data has loaded use onLoadFinished to either add a TextView to your layout or replace the text in an existing layout.
My suggestion would be to create a TextView in your layout in xml so that you can position it exactly as you wish, then replacing the text after your database call using myTextView.setText(databasetext)

The way you display data from a database is completely independent of the way you're getting that data. If it's simply text you need to display, then a TextView seems to be a logical view element to use.
In simple terms, the steps you should be taking would likely be:
Get ID from SharedPreferences
Query database with ID for result
Pass the result to your view layer
Use a TextView to display the result
It's best (and required since 4.0) to make network calls in a thread separate from the UI thread. The best way is probably using an AsyncTask. For example:
private class GetDbItemTask extends AsyncTask<Integer, Void, MyDbItem> {
protected MyDbItem doInBackground(Integer... ids) {
return mDbService.load(ids[0]);
}
protected void onPostExecute(MyDbItem result) {
mTextView.setText(result.toString());
}
}

Have you tried a custom alert dialog this link?
This allows you to have a textview on your screen without changing your activity.
I hope I answered this correctly since you ask
"Is it possible to do that with ViewText or is there another way to
place text on the screen after a remote db call is made?".
Then there is the option of refreshing the screen using onResume() on the activity lifecycle.

The logic would that I would use is to build your screen in XML and have a Textview named myTextView
in your activity declare a Textview
TextView name_field;
String name;
....
.
.
.
//call my database info
//this example get a variable and pass it into String variable name and then display it in your text view
name_field = (TextView) findViewById(R.id.myTextView);
name_field.setText(name);

Related

How to change textviews & imageviews of another activity in Android

I have an activity which can take a few seconds to load its content (mainly pictures) from the cloud. Let's say this content is pictures & description from a person. The user can go to pictures & description from another person by clicking on the next button. I'd like to avoid the loading time When this button is clicked.
To do this I have two activities : firstPersonActivity for the first person content, and secondPersonActivity for the second person content.
What I try to do is to load the content of the secondPersonActivity when the user is in the firstPersonActivity, so that the secondPersonActivity can be displayed "directly" (= without needing to load content from the cloud when the next button is clicked in the firstPersonActivity).
But I do not succeed in doing this, I don't know how to modify the views of the secondPersonActivity layout from the firstPersonActivity class.
I tested the following code in my firstPersonActivity but it doesn't work (there is no connexion to the cloud, it's just a test to better understand how it works). R.id.first_image_second_person is the id of my imageview in the secondPersonLayout (= the layout used in the secondPersonActivity).
ImageView firstImageSecondPerson = (ImageView) findViewById(R.id.first_image_second_person);
firstImageSecondPerson.setImageResource(R.drawable.mypicture);
When I click on the next button to go from the firstPersonActivity to the secondPersonActivity, my firstImageSecondPerson imageview is not filled.
Do you see what's wrong ?
Is there a better way to avoid the loading time when the user click on the next button ?
It is not possible to change activity if activity instance is not created. In my opinion to do what You need I would go to single activity with hidden content of second person ( VIEW.INVISIBLE ) and show/hide it when it is needed.
But if second activity must be there, then create some structure for saving bitmaps in memory. In Your code sample You get picture from drawable so we are not talking about some delays, but if images are downloaded from some server then You can create some class which will have those bitmaps created from url and instance of this class can be used on any activity.
So for example Your class for caching pictures would have some method for creating bitmaps like -How to load an ImageView by URL in Android?. And those bitmaps should be saved in some Array or HashMap to have access to it, for example ( pseudo code ):
//some structure for cashing pictures in app
class PictureCache {
static PictureCache instance;
final HashMap<Integer, Bitmap> bitmaps;
//singleton
static PictureCache getInstance(){
if (instance==null)
instance = new PictureCache();
return instance;
}
public PictureCache(){
bitmaps = new HashMap<>;
}
private Bitmap loadBitmap(String url);//#1
public addPicture(Integer personId, String href){
//add to hashMap
bitmaps.put(personId, loadBitmap(href));
}
public Bitmap getPicture(Integer personId){
return bitmaps.get(personId);
}
}
#1 - method from How to load an ImageView by URL in Android?
Using it in first activity:
PictureCache.getInstance().addPicture(12,"http://url.to.bitmap");
Using it in second activity:
Bitmap pic = PictureCache.getInstance().getPicture(12);
Important note - above code was written here and was not tested, it shows solution concept.
Important second note - using such approach with bitmaps in memory can cause to much memory usage
You cannot access the views of SecondActivity before its creation. If you called this activity once only then you are able to access its views by making them static.
One more Solution for this is..
Access the whole data at once and save it in static arraylist with the help of getter-setters. Then on SecondActivity set data from that arraylist.
Hope this will work.
I don't think you can access the view before creating the activity.
You can try to use Glide for caching your images and minimizing loading time.
Try this
Picasso.with(getContext()).load(R.drawable.generatedId).into(imageView);
or
imageView.setImageDrawable(ActivityCompat.getDrawable(getContext(),
R.drawable.generatedID));`

Automatically/dynamically update TextView text in Android

I have an android app that I have decided to rewrite, one of the reasons for the rewrite is because I could have 10+ TextViews with text set based on a variable in a class e.g.:
MyClass myClass = new MyClass();
myClass.myNumber = 5; // inside MyClass - public int myNumber;
LinearLayout mainLayout = (LinearLayout) view.findViewById(R.id.mainLayout);
TextView myTextView = new TextView(getActivity()); //In a fragment
myTextView.setText(String.format("myNumber currently has a value of %d", myClass.myNumber));
mainLayout.addView(myTextView);
return view;
Up until now I have been using .setOnClickListener on the buttons/views that change myNumber, to set the text of the view again when the value of myNumber changes, which then calls .invalidate() to redraw the TextView, this has worked fine, but I use this method very heavily and code is getting quite repetitive and changing one integer can affect quite a lot of views (all of which use it differently - such as different wording, or a calculation (e.g. myNumber * 2)). I guess it's because it's made an immutable string in the TextView.
I have tried to create a custom TextView that implements Observer (making MyClass extend Observable) and in the update method I can get it to invalidate itself for the refresh, but it still has the same text. I have also tried creating single element arrays, in an attempt to pass the reference not the value in the hope that when it is changed and then the view is invalidated it will pick up the new value but the text still ends up remaining the same.
How can I get a TextView that will auto update when the value of myNumber has changed? Some sort of binding?
Bindroid works perfectly for this, just a note for users, using fragments the sample application is using this from an Activity so the bind method using Activity is called, so in the fragment I was using getActivity() which caused it to not work properly, digging around in the library I found a bind method that takes a View and passed in my view which gets inflated in the fragment and it works great!!! This is super easy to integrate btw it was just me not getting it!

how to exchange data between activity and layout xml in android

I need to exchange data between activity and it's layout xml in Android. But I do not find a way to do this in Android. For example, views and controller in mvc pattern always has a way to exchange data between. So I am wondering is there any way to exchange data between them to should I refresh my mind and realize there is no such way?
use below code to get value from layout in your activity
String value;
EditText editText= (EditText) findViewById(R.id.editText);
value=editText.getText();
code in xml example:
<ImageView
android:id="#+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
in java class (like onCreate()):
ImageView image = (ImageView) findViewById(R.id.image_view);
Then you can do what you want with image
I believe you're unsure exactly what you're asking. If you want to exchange information, such as ID or text entered into a textfield then any good android tutorial should be-able to demonstrate this. Considering your last comment I think you're talking about GET and POST based technologies which can be done usingREST andSOAP, or both if you want.
This questions answer has a good implementation and definition of what both of these webservices are.
P.S. If this is what you're looking for then upvote that answer.
As some additional info, the "view" (XML Layout file) gets set by your activity initially on your activity's onCreate method. Right after you call it's parent method (super.onCreate()).
To maintain scope throughout the activity I tend to declare all the layout widgets that I need to the activity to interact with outside of any methods and within the class.
TextView textWelcomeMessage;
public void MyActivity(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// before calling setContentView() we have the option to change
// window features ex requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_my_activity);
// Now to set the textview
textWelcomeMessage = (TextView) findViewById(R.id.textWelcomeMessage);
// Set some data
textWelcomeMessage.setText("Hello, welcome to my activity");
}
It's not exactly like traditional php style mvc since static typing changes thing up a bit and we have to worry about scope. But the core principles can still apply as far as data abstraction and separation go. Hope this helps =)

Displaying an array of objects, one at a time through a single dialog... instead of several dialogs

In my application I have a list of questions stored in an ArrayList, and I want to display a dialog that shows one question, and then continues to the next one after the question is answered. The way that I'm currently doing it (iterating through a loop) hasn't been working because it just layers all of the dialogs on top of one another all at once which causes a host of other issues. What I'm looking for is a way to still iterate through the questions, but just change the layout of the dialog each time until it has finished each question in the list. Can anyone give me a good pointer for how to get this going?
You can make a function that takes title and message as parameters and shows a dialog.
showDialog(String title, String message){ // Show dialog code here}
Within that dialog's answer button's listener call another function (showQuestion(currentQuestion)) that iterates the arrayList till it is over
int currentQuestion=0;
ArrayList<QuestionObject> questionList;
showQuestion(int i){
if(i<questionList.size()){
showDialog(questionList.get(i).getTitle,questionList.get(i).getMessage);
currentQuestion++;
}else{
//quiz is over
}
}
I assume you mean that you just want to change 1 single layout(created within XML i.e main.xml). In order to do this, make sure that the class your working on is pointing to that layout. From there (assuming your using an Event listener for when the user submits an answer) you can change do as you want by the following:
TextView txt = (TextView) findViewById(R.id.textView); // references the txt XML element
and in your Event listener, if the answer is correct then change(Have i be a global variable thats initially set to 0).
if(i<arrayList.size()){
txt.setText(arrayList.get(++i));
}else{
txt.setText("You Finished");
}
From there, in the else statement, you can change arrayLists and reset i to 0;
If you are trying to use the positive, neutral, and negative buttons; then you may have problems with multiple dialogs. Try defining a customized layout with your own TextViews, ListViews, and Buttons. You can implement listeners and everything else like a regular layout. Then just pass your customized layout to the dialog through AlertDialog.Builder.setView().
PS If you include code examples of what you are currently doing we can provided answers that are less vague.

Displaying large tables without choking UI thread

I have a table with about 1k rows that I want to display. This task obviously chokes the UI thread, resulting in a black screen while the onCreate() builds the table.
I've solved this by using AsyncTask which builds the wanted TableLayout in the "doInBackground" function and display it on the "onPostExecute" function.
Question #1:
Is there any better practice that I'm not familiar with?
Question #2:
My (simplified) "doInBackground" function looks like this:
protected Void doInBackground(Void... v) {
tmpTableLayout = populateTable("");
return null;
}
And my (simplified) "onPostExecute" function looks like this:
protected void onPostExecute(Void v) {
TableLayout ct = (TableLayout)findViewById(R.id.RealTable);
ct.removeAllViews();
/* WHATS HERE? */
}
What should I write instead of the "WHATS HERE?" in the last line of code in order to display the content of "tmpTableLayout" in "ct" ?
Thanks in advance!
Are you sure you want to display it all in one go?
One approach would be to dynamically load in more lines as the user scrolls down. So have a scroll listener that checks if the user is approaching the end of the content that is displayed and therefore start an AsyncTask or a thread loading more content.
Example:
Android List Activity with dynamically loaded images form the web in android
I would probably use a ListView and CursorAdapter and let Android manage fetching the data for you. See the accepted answer here.

Categories

Resources