I have a button on Main's android xml file which once clicked will display another view/activity.
My problem is the error message displays that the application must end unexpectedly.
Here is the button
<Button android:id="#+id/showmeurcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="OnShowMeUrCode"
>
The method OnShowMeUrCode is defined in the MainActivity class as
private void OnShowMeUrCode(View btn)
{
Intent urCode=new Intent(this,CodePage.class);
startActivity(urCode);
}
CodePage is generated from a class of the same name
public class CodePage extends Activity
{
....
}
That is all I have done in the hope that I could accomplish the simple task with Intent to display another view but I run in an unexpected error and my program fails short.
You need to change your OnShowMeUrCode() function to be public, not private. Since it's part of the Activity class, your Button won't have access to it if it's private.
Plus it's in the docs:
http://developer.android.com/reference/android/widget/Button.html
Based on your code without the error log output, I guess you didn't pass a correct Context to the method.
This is your code:
private void OnShowMeUrCode(View btn)
{
Intent urCode=new Intent(this,CodePage.class);
startActivity(urCode);
}
Try replace the relevant line with:
Intent urCode=new Intent(MainActivity.this,CodePage.class);
Say, I have two Activities, A and B. If I'm calling B from A, I should write something like:
Intent i = new Intent(A.this, B.class);
startActivity(i);
Besides, you need to register your Activity in AndroidManifest.xml each time you create a new activity. In your case, please check if there are 2 activities in your AndroidManifest.xml
Related
I used the anko library to create a login view.
class SingInView : AnkoComponent<SingleInActivity> {
override fun createView(ui: AnkoContext<SingleInActivity>) = with(ui) {
verticalLayout {
lparams(width = matchParent, height = matchParent)
textView("Member Login")
editText {
hint = "E-mail"
}
editText {
hint = "PassWord"
}
button("Login")
}
}
}
and SingleInActivity.kt
class SingleInActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState)
SingInView().setContentView(this)
and MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, SingInView.class));
finish();
}
}
current My app MainActivity -> SingleInActivity -> SingInView .
of course it can be made simply.
but there is a condition
1. MainActivity is java (kotlin prohibition)
2. use only MainActivity, SingInView.
How to solve this problem?
How to call the Anko class directly from a Java class
If you dig through the Anko source code you'll quickly find this:
interface AnkoComponent<in T> {
fun createView(ui: AnkoContext<T>): View
}
And from the wiki (where MyActivityUI is the component): MyActivityUI().setContentView(this). Now, the AnkoComponent is just an interface and the setContentView method is an extension function that returns createView.
Anyways, the setContentView extension function passes the last variable of the AnkoContextImpl as true. The last variable is whether or not to actually set the content view, which is the reason the activity is passed in the first place.
TL;DR (and possibly more sensible summary of my point):
The component is not an Activity
The setContentView method is not a replacement for setContentView in an Activity; just a wrapper for it.
And since it isn't an activity, you can't use an intent into it. And, as a result of that, you cannot use it standalone. You need an activity. Now, you can of course use the regular approach, but there's also another way. Since the AnkoComponent itself doesn't have any fields, it can be serialized without much trouble. Just to clarify: some fields can be serialized even if it isn't serializable (all though some classes like Context cannot be serialized). Anyways, you create an activity:
class AnkoComponentActivity : AppCompatActivity(){//Can be a regular Activity too
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
val component = intent.getSerializableExtra("uiComponent") as AnkoComponent<AnkoComponentActivity>//The type has to match this activity, or setContentView won't allow passing `this`
component.setContentView(this)//The context of the activity doesn't get passed until this point, which enables the use of this system.
}
}
Or it's equivalent in Java:
public class AnkoComponentActivity extends AppCompatActivity {
public void onCreate(Bundle sis){
super.onCreate(sis);
AnkoComponent<AnkoComponentActivity> component = (AnkoComponent<AnkoComponentActivity>) getIntent().getSerializableExtra("uiComponent");
org.jetbrains.anko.AnkoContextKt.setContentView(component, this);//For reference, this is how you call Kotlin extension functions from Java
}
}
Note that any UI component sent to this class has to be declared with <AnkoComponentActivity>. In addition, the components have to implement Serializable. Otherwise they can't be passed through the Bundle. Alternatively, you can use ints or Strings as identifiers and use the value to pick which AnkoComponent to show.
All though, the absolutely easiest way is just creating one activity per component.
TL;DR: AnkoComponent is not an Activity, meaning you can't use intents into it. You have to use an Activity, but using Serializable enables you to pass the component through a bundle to an Activity made for manual creation of multiple AnkoComponents without specifying specific types.
I need some pointers on doing the following:
lets say i have 10/20 (number doesn't matter) of activities.
each of these activities has a textview that should work like a counter.
each of these activities has a button to go to the next activity.
this counter starts when the app is launched, and increment itself every second.
So what i did so far is:
have in my main activity a method that instantiate a class that extends Thread.
In that class in the run() method, i increment a variable when a second passes.
Now i'm stuck on what i should do next. Any pointers would be appreciated thanks.
Edit: i need a way to communicate from inside the run method, to whichever activity is now currently on screen, to update its textview.
Just a bit of theory here for standard Object Oriented Programming : stick to the recommended principles like Loose Coupling which makes your project code less tied to each other. You can read more on that later.
Now, using Events, you can setup a system that is synonymous with the natural Publisher/Subscriber design pattern. Like this:
The activity that needs to notify the other activities is called Publisher and the other activities that need to be notified are called Subscribers.
From here:
There are already built and tested libraries to do Events in android. Like my favorite EventBus.
Step 1 Add this line to your app-level build.gradle file:
compile 'org.greenrobot:eventbus:3.0.0'
Then create a simple Plain Old Java Object aka POJO class like this:
public class UpdateTextViewEvent{
private String textToShow;
public UpdateTextViewEvent(String text){
this.textToShow = text;
}
//add your public getters and setters here
}
Step 2 Notify others:
When you want to notify anyone of the changes, you simply called this method:
EventBus.getDefault().post(new UpdateTextViewEvent("Some new Text"));
Step 3 Receive notifications
For those who want to be notified of this event, simply do this:
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
NOTE: to actually handle the event:
#Subscribe
public void onEvent(UpdateTextViewEvent event){
String text = event.getTextToShow();
//now you can show by setting accordingly on the TextView;
}
This is so much easier to do, do decouple your code by eliminating static references in your different activities
I hope this helps! Good luck!
make that Textview in second class as
public static Textview text;
and call it in main activity as
SecondActivity obj=new SecondActivity();
obj.text.settext("");
You can create one another activity e.g. BaseActivity extend with Activity class and your all 10/20 activity extends with created BaseActivity Class.
You can use your textview with protected access specifiers.
What you need to do is inside the counter class, create an a method and passed in a TextView as the parameter. Then create an int variable and set the counter as the instance:
Like this
public static class Counter extends Thread{
private static int x;
#Override
public void run(){
x = counter;
}
public void setCounter(TextView tv){
tv.setText(String.valueOf(x));
}
}
Now call this method setCounter(TextView) in all the activity's onCreate() method you'll like to display the counter, and passed in your the layout TextView as the argument. Like this
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState):
....
TextView cTextView = (TextView)findViewById(R.id.texT1);
Counter c = new Counter();
c.setCounter(cTextView);
}
I made an application "Quiz", which has 4 activities. Main activity sends a String with your name from EditText to activity with first question. I have a problem here, because I don't know how to send this string immediately to final activity from main activity, but without going to final activity. I want to go to Activity with first question from main activity, then to activity with second question, and in the end I want to go to final activity.
Thanks for your help!
You could use static fields to pass data.
Inside your FinalActivity class you could add the following variable:
private static String NAME = "";
And with the following getters and setters:
public static String getName(){
return NAME;
}
public static void setName(String name){
NAME = name;
}
You can use the getter setter here at Application class so you can get the string data from anywhere were you want to. This is not the only way but i think it is also the easy way.
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
add this in your manifest
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
hen in your activities you can get and set the variable like so:
/ set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
Some Url which may help you Android global variable
You can use shared preference also but as per our requirement i don't recommend that to you
Android Shared preferences example
You can use Broadcast Receiver for your requirement. In your activity from which you want to send data, do this way:
Intent intent = new Intent();
intent.setAction("fourthactivity");
sendBroadcast(intent);
And In your fourth activity, make a broadcast receiver which receive your intent :
public class IncomingReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("fourthactivity")) {
System.out.println("GOT THE INTENT");
}
}
}
Tell me if this doesn't work or click right if it works for you.
You can use SharedPreference to store the answers as you go from one activity to other and later compare all the answers in the FinalActivity in that way less complex coding and you will achieve your desired result.
This is the code for android activity I want to run, if at all possible without creating a new activity. Need to get rid of the Listener function. I tried to make a new java class but it gave me error on putExtra functions. Also how can I deal with the instance of newConnection inside the Listener constructor.
public class NewConnection extends Activity {
private Bundle result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
private class Listener implements OnMenuItemClickListener {
//used for starting activities
private NewConnection newConnection = null;
public Listener(NewConnection newConnection)
{
this.newConnection = newConnection;
}
Trying to run the code below without clicking:
#Override
public boolean **onMenuItemClick**(MenuItem item) {
{
// this will only connect need to package up and sent back
Intent dataBundle = new Intent();
String server = ("tsp//:server address");
String port = ("1823");
//put data into a bundle to be passed back to ClientConnections
dataBundle.putExtra(ActivityConstants.server, server);
dataBundle.putExtra(ActivityConstants.port, port);
...
...
//add result bundle to the data being returned to ClientConnections
dataBundle.putExtras(result);
setResult(RESULT_OK, dataBundle);
newConnection.finish();
}
return false;
}
This is the code used to call the activity:
createConnection = new Intent();
createConnection.setClassName(
clientConnections.getApplicationContext(),
"org.eclipse.paho.android.service.sample.NewConnection");
clientConnections.startActivityForResult(createConnection,
ActivityConstants.connect);
This is a basic constructor within a listener paradigm. It's a core idea within computer science that code should be reusable, and to facilitate this code needs to generally be self contained. This is often done within Java with a listener. It's usually an abstract class or an interface that has a few set functions. The main class that uses the listener is assigned this object or objects, and when it reaches a relevant point will trigger the listener to notify your code of an event.
This allows people to write code that is fully contained and still provide event hooks whereby other user who employ that code can get feedback such as when a menu item is clicked or a new connection is made, and have this dealt with by the person using this code, but without the author of the original class knowing anything about your code. It allows things like menus and connection managers and buttons that have no connection to the code that they trigger, by design. So that any number of these can be made and used.
I've got two activities, one of them is called MyActivity. I want both of them to be able to use a function located in a class othat we may call MyClass. In MyClass, I try to use an intent to launch the activity AnotherActivity. Since the constructor takes a context as parameter, I simply tried to store a context from the activity in the constructor, and then use it when I try to create my intent.
class MyClass {
private Context cxt;
MyClass(Context cxt) {
this.cxt = cxt;
}
startIntent() {
Intent intent = new Intent(cxt, AnotherActivity.class);
startActivity(intent); // this line throws a NullPointerException
}
}
The code in MyActivity to use the class is shown below:
myClassObject = new MyClass(MyActivity.this);
myClassObject.startIntent();
However, even thought none of the arguments are null (checked that with a simple if-statement), intent seems to be null and a NullPointerException is thrown. Why does it not work, and what can I do to solve the problem?
I'm quite new to Android and Java development, so please explain it as basic as you can.
cxt.startActivity(new Intent(cxt, AnotherActivity.class));
and to be sure that it's intent is NULL, and not something internal in startActivity method, you can add some checks, i.e.
Intent intent = new Intent(cxt, AnotherActivity.class);
Log.d(toString(), "intent = " + intent.toString());
cxt.startActivity(intent);
I've used almost identical code in my applications and it's worked fine.
I suspect there's something else going on that's in code you haven't shown us; I suspect there's some cut-and-paste issues --- e.g. what are you calling startActivity() on in MyClass?