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 + "");
Related
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!
I'm having a problem with my app.
So, I'm trying to save some data into another activity, from mainactivity inputs. And I think I found the error but can't fix it.
I believe my app is searching for textview reference in wrong activity, in main. The problem is that I want to change another activity's textview. Is there anybody that could explain for me how to do that or give me some advice here?
public void saveEvent(View saveView){
Saved save=new Saved();
save.SaveNow(day,tvResultBefore.getText().toString(), tvResultAfter.getText().toString());
// Save class
public class Saved extends MainActivity {
TextView tvMonthResult;
TextView tvResultBef;
TextView tvResultAft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
tvMonthResult=findViewById(R.id.tvMonthResult);
tvResultBef=findViewById(R.id.tvResultBef);
tvResultAft=findViewById(R.id.tvResultAft);
}
public void SaveNow(String day, String resBef, String resAft){
tvMonthResult.setText(month);
tvResultBef.setText(resBef);
tvResultAft.setText(resAft);
}
get values from MainActivity like this ::
MainActivity.class
String data = editText.getText().toString();
Intent intent=new Intent(context,AnotherActivity.class);
intent.putExtra("DATA",data);
startActivity(intent);
Now, in AnotherActivty get value and set it to textview :
AnotherActivity.class
if(getIntent!=null)
String data = getIntent().getStringExtra("DATA");
if(data!=null)
textView.setText(data);
it solved your problem.
Below is the code which I'm using to return a number which should be 1 when the button is clicked. However when I try to get that number from another class, it always stays 0.
As you might recognize, I tried to change the number in the onClickListener and returned it below.
I also tried to use the onPause command so that it will return the number onPause but it still doesn't work.
public class MainActivity extends Activity {
public int number;
Button btnAngled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
btnAngled = (Button) findViewById(R.id.btnAngled);
final Intent intent = new Intent(this, angledForeheadActivity.class);
btnAngled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = 1;
startActivity(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
public int getNumber() {
return number;
}
}
I try to get the code in another class with:
MainActivity a = new MainActivity();
int number = a.getNumber();
Sorry for the noob question..
declare the variable as static variable. Then you can simply obtain the result you want since there is only one copy of that variable. If you want to pass the value using intent, you can call putExtra() of intent to carry information to another activity.
Intent reference page
What you actually want is getting the number from another Class. Don't mix the job with button click together. You should setup the concept of model to store data and seperate UI and data, UI just change/get the data.
I suggest you either of the two ways
Store the number in some global model, then you can get the number from another Class.
User Android Broadcast to transfer the data
Use static variable in Activity is not a good idea, it may cause memroy leak, though it can solve your problem.
I have experience with programming languages but am a bit new to android programming.
I have a program with some fields that function as labels(textview), buttons, and data entry(edittext).
Whenever i declare them at the beginning of the program out of any methods(but in the class of course), when I start my application it crashes and simulation gives a "unfortunately, your program has stopped" alert.
Eclipse doesn't give any errors for the declaration and i did use the same way for defining regular variables with no issue. It also gives the same error when i declare a mediaplayer object in the class body.
Does anyone know why it gives error?
And is there another way to declare global objects like edittext, viewtext, etc... Declaring them over and over again in methods sounds weird to me.
Thank you!!
public class TrainerActivity extends Activity {
Button stopTimer = (Button)findViewById(R.id.StopTimer);
Button startTimer = (Button)findViewById(R.id.StartTimer);
EditText totalTime = (EditText)findViewById(R.id.TotalTime);
EditText enterMin = (EditText)findViewById(R.id.EnterMin);
EditText enterSec = (EditText)findViewById(R.id.EnterSec);
private boolean breaker = false;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StartTimer();
}
});
stopTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StopTimer();
}
});
}
Without seeing example code of what you're trying it's impossible to say for definite (we don't do mind-reading here). But let me guess, you're doing something like this?...
public class MyActivity extends Activity {
TextView tv1; // This is fine.
TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.textview1); // This is fine
tv1.setText("Some text"); // This works
tv2.setText("Some text"); // NullPointerException here
}
}
The tv2.setText(...) will fail because you used findViewById(...) BEFORE you call setContenetView(...) and as a result, tv2 will be null.
It's quite acceptable to declare your widgets as instance members in your Activity but don't try to use findViewById(...) until AFTER you have set your content view.
try declaring the widget objects names only outside the onCreate() method
Button stopTimer;
Button startTimer;
EditText totalTime;
EditText enterMin;
EditText enterSec;
then initialise them after setContentView() inside onCreate()
setContentView(R.layout.main);
stopTimer = (Button)findViewById(R.id.StopTimer);
startTimer = (Button)findViewById(R.id.StartTimer);
totalTime = (EditText)findViewById(R.id.TotalTime);
enterMin = (EditText)findViewById(R.id.EnterMin);
enterSec = (EditText)findViewById(R.id.EnterSec);
Can you post a bit of sample code that illustrates the issue? It is fine to declare a member variable that is an EditText or TextView in the class.
logcat(in DDMS) should be give you some info about the error as well. If you are using eclipse there is a tab for DDMS, if not you can just run DDMS from a command line look at the logcat tab and launch your app (with your phone plugged in via usb, of course.) You should be able to see the actual error being reported.
You can declare these variables inside the Class body or inside the method body. In the former case, the variables are global and thus can be accessed within the whole class; in the latter case, they are local and thus can be only accessed within that method. Both of them could be commonly seen in proramming.
In Android, the typical application is that you declare the variables in the Class body and instantiate them in the onCreate() method. Something like this:
public Class MyClass extends Activity{
TextView label;// so this variable can be accessed within any methods in this Class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(Bundle savedInstanceState);
setContentView(R.layout.main) // load the layout of the activity
label=(TextView)findViewById(R.id.<the TextView id defined in the layout file>); //this variable get instantiated. From now on you can manipulate it anywhere inside the class.
Button submit=(Button)findViewById(R.id.<the Button id defined in the layout file>);//you declared and instantiated it, but it could only be used within this method since you declared it here.
}
}
If you just declare a variable in the Class body,in most caeses, you can't use it until you instantiate it, because they are null before the instantiation. I think this is why you have problems. Please post the logcat so we can specify the real problem.
My problem is that i've a tabhost with two tabs.
The first is a listview and the second only have two textviews.
What i want is when i click on an item in the listview on tab one, the array position id (int) should be sent to tab/class two, where there is an array who fetches a text by the position id that was sent.
The switching of tabs is done, but i fail everytime i try to send the position-id.
This is how i send it:
TAB ONE:
//This function is called when i click a listitem
public void setDetails(String Text, long arr_id){
Detail detail = new Detail();
detail.setDetail(); // right now i don't send the parameters because it wont even work with or without it.
}
TAB TWO:
TextView descr;
TextView title;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
descr = (TextView)findViewById(R.id.desc);
title = (TextView)findViewById(R.id.title);
}
public void setDetailText(String Text){
descr.setText(Text);
}
public void setDetailTitle(String Text){
title.setText(Text);
}
public void setDetail(){
this.setDetailTitle("example text");
this.setDetailText("example text2");
}
I want to set the text on tab two BEFORE it switch to tab two.
This works if i use SetDetail() and setDetailTitle() in the same tab/class, but not in another.
I've googled my ass off, please help me
i do this in my code using getParent() or getActivity() methods in my TabActivity and inner Activitys, cause if we use a TabActivity (wich subclass the ActivityGroup class) we can obtain the 'TextActivity' using ActivityManager and obtain the activity instance, so, here we can call the setDetail() method, and this will execute before the Activity is showed,
in your ListActivity do something like this
((MyTextActivity)((MyTabActivity)getParent()).getLocalActivityManager().getActivity(ACTIVITY_ID)).setDetail();
this works only if in you start the childs activity within your TabActivity with:
intent = new Intent(ACTIVITY_ID).setClass(this, MyMapActivity.class);
getLocalActivityManager().startActivity(ACTIVITY_ID, intent);