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.
Related
I'm trying to separate some of my java in a few different files.
I have my main class:
public class StartPage extends Activity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
}
...
}
And then I have this other class that I'd like to run on the same layout:
public class part_settings_session extends Activity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
Toast.makeText(getApplicationContext(), "This is from settings", Toast.LENGTH_SHORT).show();
}
...
}
But I'm not able to see that Toast happen anywhere or at any time. Is there a way to make both of these classes work in two separate files? This is to organize scripts for my own sake.
Two Activities can not be visible at same time and here in your code you have defined two Activities with same layout. Your code is fine but to see both activities working, you have to manually start next activity. Below code will help you. This code will start Next Activity 3 seconds after loading First Activity.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(StartPage.this, NextPage.class));
finish();
}
}, 3000);
in your onCreate() for the 2nd class, put a Log.d("part_settings_session", "onCreate"); and see if the onCreate ever gets called in the first place. (Since they are using the same layout, it might be difficult to see if you are 'actually' creating an instance of THIS class.
My guess is that you might not even be creating an instance of the part_settings_session class. And without logging it is pretty hard to tell that.
Here is a nice Activity base class that will log all life-cycle events for you
https://github.com/douglascraigschmidt/CS282/blob/c5cf5c4808ea082988ab87c00eeade4837eac967/assignments/assignment1/src/edu/vandy/common/LifecycleLoggingActivity.java
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 am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.ExerciseButton);
button1.setOnClickListener (new View.OnClickListener(){
public void onClick(View v) {
setContentView(R.layout.exercises);
}
});
}
}
anybody able to help me out there? thanks
Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:
public void onClick(View v) {
Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
startActivity(intent);
}
You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.
Well, from your code, I see a couple of things:
I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
Second thing:
Start a new Activity (if that is what you want) by using an Intent:
Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);
You CAN absolutaly call setContentView on any event, even after the view has loaded
I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)
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.
First off, I did post this to the android google group first but its moderated and I'm not sure how long itll take to show up there so hoping someone here can help.
I created a simple app with a ListView following the ListActivity
examples I found on the net.
The app has 2 activities with the first having a button to create the
second. When i hit the close button on the second activity I would
like it to release its memory (or at least allow it to be garbage
collected). Currently it will never release.
I must be doing something wrong here because the MyListActivity never
gets released. Can anyone tell me if I am doing something wrong with
the way my activities are created/destroyed? or if my usage of the
ListView is wrong?
Thanks.
My App as a zip - http://www.mediafire.com/?l26o5hz2bmbwk6j
Screen Shot of Eclipse MAT showing the list activity never releasing
memory - www.mediafire.com/?qr6ga0k
public class MyListActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
ListAdapter ada = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, GENRES);
setListAdapter(ada);
}
#Override
public void onDestroy()
{
super.onDestroy();
System.gc();
}
public void ClickHandler(View target)
{
switch (target.getId())
{
case R.id.LL_Btn1:
finish();
break;
}
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};}
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void ClickHandler(View target)
{
switch (target.getId())
{
case R.id.M_Button01:
Intent intent = new Intent();
intent.setClassName(MyListActivity.class.getPackage().getName(), MyListActivity.class.getName());
startActivity(intent);
break;
}
}}
Have you tried getting rid of System.gc() and see what happens? Calling System.gc() is merely telling the VM to initiate garbage collection - there is no guarantee when it will be done.
Not sure if this will help, and its not generally recommended to do this, but the following will kill your process in onDestroy():
System.runFinalizersOnExit(true);
android.os.Process.killProcess(android.os.Process.myPid());
Put that in the onDestroy method. Now this may actually kill your main process if called from a child activity (havn't tested it).
WARNING: I generally don't recommend doing this as its a "hackly" way of doing it, but if you just need your app (or activity) to close upon exit then this will work. You still need to debug to find out why your app is staying open and eating memory.
Eclipse MAT was the cause. New Android Studio doesn't cause these problems.