Unable to get the data to textView in activity - java

public class About extends AppCompatActivity {
ImageView imageView;
TextView textView;
String mediaUrL;
private FirebaseFirestore firebaseFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
firebaseFirestore = FirebaseFirestore.getInstance();
imageView = findViewById(R.id.showGraphImage);
textView = findViewById(R.id.jkbdsjfdvshf);
firebaseFirestore.collection("crimeData").document("graph").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot snapshot) {
mediaUrL = snapshot.getString("imageUrl");
textView.setText(mediaUrL);
System.out.println(snapshot.getString("imageUrl"));
}
});
Glide.with(this).load(mediaUrL).into(imageView);
System.out.println(mediaUrL);
I am new to android and I am using Cloud Firestore to store the data online .the variable mediaUrl prints on the console but don't show in the activity. I got the answer but still, now it is not working. Further, I added a used mediaUrl to display the image but it is also not showing on the activity.

As Sahil Goyal wrote, you need to use TextView.
final TextView textView = findViewById<TextView>(R.id.textView);
...
public void onSuccess(DocumentSnapshot snapshot) {
mediaUrL = snapshot.getString("imageUrl")
System.out.println(snapshot.getString("imageUrl"));
textView.setText(mediaUrL);
}

You must have to add an adapter item and initiate that with a template adapter item in order to work with it.
Make a adapter class and inside oninstantiateitem() function create a itemview -
val itemView: View = LayoutInflater.from(container.context).inflate(
R.layout.pageadapteritem, container, false
)
After you have created itemview set -
itemView.textView.setText(mediaUrl)
PS - This code is in Kotlin, kindly change it to java when android studio asks to do so while pasting.

The problem in your code lies in the fact that you are trying to set the image using the following lines of code:
Glide.with(this).load(mediaUrL).into(imageView);
System.out.println(mediaUrL);
Outside the "onSuccess()" callback. Any code that needs data from Cloud Firestore, needs to be inside the onSuccess method, or be called from there. So the simplest solution is to move both lines of code right after:
System.out.println(snapshot.getString("imageUrl"));
This is happening because Firebase API is asynchronous. For more info about this topic, please see my answer from the following post:
How to return a DocumentSnapShot as a result of a method?

If you want to show the image onto the ImageView, you should consider the following first:
1.- Please, double check if the image on your firebase has public access, you can set that permissions from the Google Cloud console through the shell console with this command.
gsutil acl ch -u AllUsers:R gs://<YOUR_BUCKET>/<IMAGE_NAME>
After that, to validate if your image has public access you can copy and paste the url string on a web browser, you must see your image in there.
2.- Also verify, if the path on the code to your image on firebase database has no typos and is correct. After checking the previous, If you see the “imageURL” value is printed on the console.
3.- You should move this line
Glide.with(getApplicationContext()).load(mediaUrl).into(imageView);
inside the onSuccess() method like this:
public void onSuccess(DocumentSnapshot snapshot) {
mediaUrl = snapshot.getString("imageUrl");
textView.setText(mediaUrl);
Glide.with(getApplicationContext()).load(mediaUrl).into(imageView);
}
then it will be set on your imageView.
Good luck!

Related

The value of QR Code Scanner cannot show on new activity

I am trying to make a simple QR Code scanner and run well if the result shows in the MainActivity. But when I'm trying to generate new Activity as a result, it can't show. Would you like to help me with this problem? Thank you.
Here is the result of the scanner code in the scanner.java:
#Override
public void handleResult(Result rawResult) {
startActivity(new Intent(getApplicationContext(),ResultActivity.class));
ResultActivity.scanText2.setText(rawResult.getText());
onBackPressed();
}
And here is the code of my new Activity for showing the result:
public class ResultActivity extends AppCompatActivity {
public static TextView scanText2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient);
scanText2 = (TextView) findViewById(R.id.scanText2);
}
}
There are a lot of issues with this:
You are launching PatientActivity, not ResultActivity in handleResult()
You are trying to set the value of a TextView in another Activity with this code:
ResultActivity.scanText2.setText(rawResult.getText());
This is an absolute no-no. Pass the data to ResultActivity as an Intent extra when you launch it. You cannot access the views of another Activity like that.
You expect that ResultActivity.scanText2 will contain a reference to a TextView, but at this point it will only contain null. The reason is that it takes some time for ResultActivity to actually start and call its onCreate(). You have not accounted for this timing in your code. To solve this problem, just see (2) above.
Also, you should have gotten a bunch of crashes with useful messages in your logcat. In the future please look there to solve problems and/or post the messages with stacktrace in your Stackoverflow questions.

How to use global variable in onCreate method of Android

I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.
Here's my code:
public class MyActivity extends AppCompatActivity
{
public static int num_i=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
TextView tv = findViewById(R.id.textView);
tv.setText(num_i);
num_i++;
}
}
Please help me in this.
setText(CharSequence text)
Sets the text to be displayed. it takes String as a parameter not a number
Sample : tv.setText("PREM");
setText(int resid)
Sets the text to be displayed using a string resource identifier.
Sample : tv.setText(R.string.app_name);
first you have to convert your int value in to a String
Try this use
tv.setText(String.valueOf(num_i));
or
tv.setText(num_i+"");
instead of this
tv.setText(num_i);
Don't use tv.setText() with a number as parameter. Try using String.valueOf(num_i).
So in your case:
tv.setText(String.valueOf(num_i)) or tv.setText(num_i + "");

FirebaseListAdapter not pushing individual items for chat app - Firebase-Ui 3.1

I am making a chat app on Android that uses google firebase to store messages that users write to each other. To display these messages to the users I read them from the database and organize them into a custom ListView with a ListAdapter. This was working fine until I updated my dependencies, specifically firebase ui to:
com.firebaseui:firebase-ui:3.1.0
Now the code to construct the list adapter does not work, being:
adapter = new FirebaseListAdapter<ChatMessage>(FirebaseDatabase.getInstance().getReference("Lobbies").child(leaderID).child("Messages"), ChatMessage.class, R.layout.message, this) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
// Get references to the views of message.xml
TextView messageText = (TextView)v.findViewById(R.id.message_text);
TextView messageUser = (TextView)v.findViewById(R.id.message_user);
TextView messageTime = (TextView)v.findViewById(R.id.message_time);
// Set their text
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
model.getMessageTime()));
}
};
To fix this issue, I updated the code to conform to the new firebase ui requirements, making the code become:
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
.setQuery(FirebaseDatabase.getInstance().getReference("Lobbies").child(leaderID).child("Messages"), ChatMessage.class).setLayout(R.layout.message).build();
adapter = new FirebaseListAdapter<ChatMessage>(options) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
// Get references to the views of message.xml
TextView messageText = v.findViewById(R.id.message_text);
TextView messageUser = v.findViewById(R.id.message_user);
TextView messageTime = v.findViewById(R.id.message_time);
// Set their text
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
model.getMessageTime()));
}
};
This code compiles fine now, but the listview is not displaying the data. Is there a specific right way to use the new firebase ui dependency to make the list adapter?
To let the FirebaseRecyclerAdapter and FirebaseListAdapter show the data on the activity
You need to use this:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Since FirebaseListAdapter uses a listener to check for changes in the firebase database, then to being listening for data you need to add adapter.startListening() inside the onStart() to be able to show the data in the listview.
Then inside onStop() (when activity is stopped), you can use adapter.stopListening() to remove the listener and the data in the adapter.
Check this for more info: Adapter LifeCycle
Note:
If after using the above, you get a nullpointexception or cannot resolve symbol, you have to declare adapter as global variable and please check the below answer: Error in startListening()
In addition to what's been said in Peter's answer, according to FirebaseRecyclerAdapater latest api documentation, you can create a FirebaseRecyclerAdapter passing in a FirebaseRecyclerOptions instance which is created by a builder. In the builder you specify a lifecycle owner so you don't have to modify either its onStart or its onStop manually:
private fun MainActivity.setUpFirebaseRecyclerAdapter():
FirebaseRecyclerAdapter<User, ListOnlineViewHolder> {
val options = FirebaseRecyclerOptions.Builder<User>()
.setQuery(ONLINE_USERS.limitToLast(10), User::class.java)
.setLifecycleOwner(this)
.build()
return object : FirebaseRecyclerAdapter<User, ListOnlineViewHolder>(options){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListOnlineViewHolder {
return ListOnlineViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.user_layout, parent, false))
}
override fun onBindViewHolder(holder: ListOnlineViewHolder, position: Int, model: User) {
holder.bindMessage(model)
}
}
}
The options builder is made up of a setQuery method which takes in a reference to the db and a model object; the setLifecycleOwner which takes in the activity that will trigger the adapter updates.

How to dynamically add rows from a table (sqlite) to layout? (Android)

I am trying to take all the rows from my db and add it to the current layout, also, making each row clickable in the layout to take the user to a new screen with the id...
Here is my current code, but stuck on that part... I understand that I can put an onClickListener, but then does it have to be a button?
For a visual representation refer to a notepad app on any device where each note title appears and clicking on it takes you to that note.
public class MainActivity extends Activity implements OnClickListener {
private Button add_new_dictionary;
// Database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// db setup
db = new DatabaseHelper(getApplicationContext());
// get all dictionaries
List<db_dictionary> allDictionaries = db.getAllDictioniaries();
for (db_dictionary dictionary_found : allDictionaries) {
// create new view for each dictionary name include id and make it
// dynamic and include onclick to take to dictionary_view screen
Button dictionary_button = new Button(this);
}
add_new_dictionary = (Button) findViewById(R.id.add_new_dictionary);
}
#Override
public void onClick(View v) {
if (v == add_new_dictionary) {
Intent add_new_dictionary_intent = new Intent(MainActivity.this,
add_new_dictionary.class);
startActivity(add_new_dictionary_intent);
}
}
}
To re-iterate the question: How do I go about dynamically taking rows from my db and adding it to my layout dynamically based on how many results are returned from the query? (However, the rows should be able to point to a new screen with the dictionary id)
All views in android can implement the OnClickListener interface. So no, it doesn't HAVE to be a button.
As you've decided to use the activity to handle this then you need to tell your code to pass the event to your implementation wihin your activity.
// create new view for each dictionary name include id and make it
// dynamic and include onclick to take to dictionary_view screen
Button dictionary_button = new Button(this);
dictionary_button.setOnClickListener(this);
A trick I use to store information is the setTag method which would allow you to retrieve the correct reference during your onClick:
dictionary_button.setTag(some_record_id);
Then retrieve it later:
#Override
public void onClick(View v) {
if (v == add_new_dictionary) {
Intent add_new_dictionary_intent = new Intent(MainActivity.this,
add_new_dictionary.class);
startActivity(add_new_dictionary_intent);
}
else (
Object tag = v.getTag();
//now launch the detail activity using the data from the tag
}
}
You should really look into ListAdapters and cursors to do this properly, but this method should get you going for now
If you need to pick data from a db and show it as a list (getting click events) you should probably look into CursorAdapter and ListView
http://developer.android.com/reference/android/widget/CursorAdapter.html
http://developer.android.com/reference/android/widget/ListView.html
You can fins many examples on the web on how to use a cursoradapter and the listview

How do I call a class in the print function?

I am a beginner in developing and I know the question may sounds very basic but, let me cut to the chase: here is my class
public class MainActivity extends Activity {
private ListView lvPhone;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPhone = (ListView)findViewById(R.id.listPhone);
List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_blah", "384765345667", "something#someprovider.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_blah", "34856834796", "something#someprovider.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
"blah_name", "868734633", "something#someprovider.com"));
PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
}
}
and here I'd like it to be "attached" so then when the button is clicked the phone book comes up.
public void addListenerOnButton(){
imageButton = (ImageButton) findViewById(R.id.pb_button);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(MyAndroidAppActivity.this,//phone_book goes here
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();//no toaster instead
}
});
}
Would any of you please help? This is going to be really helpful for me. And please if you do answer, try to explain as you're explaining to a "Java_moron" :) (as through as possible please)
[Now I did try the chat room, no reputation point so that didn't happen and I tried to google as much as possible couldn't find anything helpful; maybe there was answer but my lack of knowledge failed me.]
Thank you,
[EDIT: Or instead of using the phone book class, how can I call contacts from phone's native contact list? Anything would be helpful really.]
The best option to start would be to activate a native activity that will bring up phone book contacts and show them to the user as a list. Selected contacts is then passed to starting activity.
Explanation:
You can learn how to start an activity and receive result from the following link:
http://developer.android.com/training/basics/intents/result.html
Basically the main code do that is as follows:
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new Uri("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
Note that the user will be calling the startActivityForResult method this will start a new activity and once that activity is finished the System will call onActivityResult() method of the original Activity and here you will receive results to which contacts has been selected.

Categories