bind-onclick-on-textview-using-butterknife - android

I'm a little bit new using Butterknife and I'm having a problem. I want click on a textview and the open another activity. I know how to do that without using Butterknife, but this is what I did so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
}
#OnClick(R.id.tv_forgot_pass)
void forgotPassClick(){
Context mContext = LoginActivity.this;
Class nextActivity = ForgotPasswordActivity.class;
Intent mIntent = new Intent(mContext, nextActivity);
startActivity(mIntent);
finish();
}
}
My problem right now is I don't know how to use my onClick method, because if I put the that method inside the onCreate, the activity will open the next activity immediately. I tried to use tv_forgot_pass.setOnClickListener and didn't work. And also doesn't work in the xml because the method doesnt have a View as parameter.
It is okey what Im doing? or there is another way to set a clicklistner with Butterknife?
I'm going to explain why is not duplicated with this question
First, they are using and old version of Butterknife, I'm using the 8.8.1 version and the "duplicate question" is using 6.1.0. My version doesnt support InjectView(it's Bind now). Second, my question talks about click on a TextView, the other question talks about click on a button. It's similar but not the equal. And the most important, I read the "duplicate question" like an hour ago, before I asked my question and because I didn't find a solution to my problem I decided to post my question.

java.lang.IllegalStateException: Could not find method forgotPassClick(View) in a parent or ancestor
Context for android:onClick attribute defined on view class
android.support.v7.widget.AppCompatTextView with id 'tv_forgot_pass'
Logcat showing IllegalStateException
Signals that a method has been invoked at an illegal or inappropriate
time. In other words, the Java environment or Java application is not
in an appropriate state for the requested operation.
You should Use AppCompatTextView instead of
TextView.
Remove android:onClick="forgotPassClick" from XML.
XML
<android.support.v7.widget.AppCompatTextView
android:id="#+id/tv_forgot_pass"
android:focusable="true"
.... />
Then
#OnClick(R.id.tv_forgot_pass)
void forgotPassClick(){
Context mContext = LoginActivity.this;
Intent mIntent = new Intent(mContext, ForgotPasswordActivity.class);
startActivity(mIntent);
finish();
}
}

For onClick
#OnClick(R.id.tv_forgot_pass)
public void onForgotPassClick(View view) {
Context mContext = LoginActivity.this;
Intent mIntent = new Intent(mContext, ForgotPasswordActivity.class);
startActivity(mIntent);
finish();
}

Whatever you are doing is right.
#OnClick(R.id.tv_forgot_pass)
void forgotPassClick(){
Context mContext = LoginActivity.this;
Class nextActivity = ForgotPasswordActivity.class;
Intent mIntent = new Intent(mContext, nextActivity);
startActivity(mIntent);
finish();
}
above code will be executed when you will click on tv_forgot_pass.

make some change.
first bind text view as local of class like below ..
#BindView(R.id.myTextView)
TextView myTextView;
then after onCreate method bind butter knife like below ..
ButterKnife.bind(this);
then after apply click event like below ..
#OnClick(R.id.myTextView)
private void goNextActivity(){
Intent mIntent = new Intent(this, ForgotPasswordActivity.class);
startActivity(mIntent);
finish();
}
and both activity define in android manifest file.

Use #Bind before oncreate will work fine
public class Login extends AppCompatActivity {
#Bind(R.id.tv_forgot_pass)
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
}
#OnClick(R.id.tv_forgot_pass)
public void forgotPassClick(){
Context mContext = LoginActivity.this;
Class nextActivity = ForgotPasswordActivity.class;
Intent mIntent = new Intent(mContext, nextActivity);
startActivity(mIntent);
finish();
}
}

Related

MainActivity is not an enclosing class, "this" makes a constructor error

I'm new to android studio and i have a problem when I'm trying to jump to a new activity, so when the line is:
public class signup_activity extends AppCompatActivity {
ImageButton logupButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_activity);
logupButton = findViewById(R.id.signuparrow);
logupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, signup_activity.class);
startActivity(intent);
}
});
}}
I get the error:
'com.example.myapplication.MainActivity' is not an enclosing class
and i so a couple of of people advising to chane the intent to this instead of MainActivity.this
but when im changing to this i get the error:
Cannot resolve constructor 'intent'
Intent intent = new Intent(MainActivity.this, signup_activity.class);
Several things:
First, the first param of Intent() constructor is a context. Since you are on signup_activity you need to do signup_activity.this to use it as a context.
I'd assume you want to go to MainActivity, so your second param should be MainActivity.class. It seems you got the order altered there.
you are in signup_activity and when use Intent in fisrt part you should call the current contex to jump to other activity.
so you should replace
Intent intent = new Intent(signup_activity.this, MainActivity.class);
if you want to jump to signup_activity you can call intent from MainActivity.

how to use intent caller on button click properly?

actually I am bit confused on some thing which is working in one scenario very well but in other scenario that is not working fine so I am here to explain my problem to identify the wrong move made by me, if any on will identify the problem please mention it. thank you.
working fine:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.distance_demo_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListViewClass.class);
intent.putExtra(ListViewClass.EXTRAS_TARGET_ACTIVITY, Distance.class.getName());
startActivity(intent);
}
});
NOt working fine:
scan = (Button) view.findViewById(R.id.scan);
scan.setOnClickListener(startListener);
}
//Create an anonymous implementation of OnClickListener
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Toast.makeText(view.getContext(),"Scanning", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ListViewClass.class);
intent.putExtra(ListViewClass.EXTRAS_TARGET_ACTIVITY, Distance.class.getName());
startActivity(intent);
}
}
now the problem is in this line
Intent intent = new Intent(MainActivity.this, ListViewClass.class);
when I use this line in this scenario it shows me error on this line:
Error: 'The constructor Intent(MainActivity, Class<ListViewClass>) is undefined' please mention my problem if you are well aware of it.
use a global context variable glaboaly and use it.
Context myContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myContext = MyActivity.this;
}
and use myContext insted of MainActivity.this.
Im not sure whether it solve the problem, just try it out
When your calling Intent intent = new Intent(MainActivity.this, ListViewClass.class); inside MainActivity class. It will work fine. But when your not in Context of MainActivity class. i.e move to other class. This error will occur.
If you want to rectify, You can follow #jithu method. Otherwise store the context in Application class. And use it in anywhere.
In the first case you are overriding the method onClick().
If you override the method it's like you are declaring the function in your activity class.
This is the reason that you can call MainActivity.this
In the second case you are implementing the abstract method onClick(). You can't call MainActivity.this because your "MainActivity.this" is referencing to the current context and this isn't accessible from OnClickListener.class.

AndroidRuntimeException "Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag"

I create multiple layouts inside a listview, but when i click i get a AndroidRuntimeException "Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?"
Im adding
Intent.FLAG_ACTIVITY_NEW_TASK
to my intent but i get the same message! =(
#Override
public View getView(int position, View convertView, ViewGroup parent) {
retval=LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_anuncio, null);
ImageView image=(ImageView) retval.findViewById(R.id.imageAD);
LoadAds loadAds= new CargaAnuncios();
clickUrl = LoadAds.cargaImagenAnuncio(image, mContext, GlobalInfo.ANUNCIO_CARRIL_PORTADA);
image.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
Bundle bundle=new Bundle();
bundle.putString("url", clickUrl);
Intent intent =new Intent(mContext,CustomWebView.class);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
});
return retval;
}
Replace getApplicationContext() with this. Most likely, you should do that everywhere in your code that you have getApplicationContext() -- only use getApplicationContext() when you specifically need the Application object.
Old thread, but thought this easy solution might help someone. Instead of passing context around, just get it from view. For eg: view.getContext()
#Override
public void onClick(View view) {
Bundle bundle=new Bundle();
bundle.putString("url", clickUrl);
Intent intent =new Intent(view.getContext(),CustomWebView.class);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(intent);
}
I have added:
parent.getApplicationContext()
Instead of just:
getApplicationContext()
Whole line is:
retval=LayoutInflater.from(parent.getApplicationContext()).inflate(R.layout.layout_anuncio, null);
The solution of Warren Lankie Van Tonder is almost the good:
-You should avoid using Activity context and choose Application Context instead, in purpose to prevent memory leaks. This blog of an Android developer explains that http://android-developers.blogspot.be/2009/01/avoiding-memory-leaks.html
-But in the case of Activity context is the only solution for your code (maybe for calling another activity from outside an activity) and regarding the link above, you have to release the static reference in each onPause() with
AppGlobals.setAppContext(null);
In return, set the static field in onResume and not onCreate.
Thanks to CommonsWare i came up with this solution which worked best.
I added a new class
package com.test.test;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class AppGlobals extends Activity {
private static Context appContext;
public static Context getAppContext(){
return appContext;
}
public static void setAppContext(Context context){
appContext = context;
}
public static void StartActivity(Intent intent){
appContext.startActivity(intent);
}
}
All i needed to do then was add the below code on each activity onCreate that i navigated to.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
AppGlobals.setAppContext(this);
}
This allowed the new intent to start as if it working with normal application flow and this way i didn't have to set a Flag for the intent.
Calling the start activity method is as easy as:
Intent totalTimerIntent = new Intent(AppGlobals.getAppContext(), TotalTimer.class);
AppGlobals.StartActivity(totalTimerIntent);
Hope this helps someone as it has helped me.
Thank you CommonsWare.
CustomAdapter mAdapter = new CustomAdapter( getApplicationContext(), yourlist);
or
Context mContext = getAppliactionContext();
CustomAdapter mAdapter = new CustomAdapter( mContext, yourlist);
change to below
CustomAdapter mAdapter = new CustomAdapter( this, yourlist);

Crash when creating Activity

Good evening Stack !
I have started to learn Android development as a hobby and I am now trying to develop my first "real" application (I have made already only five simple applications from books).
In this application, I have two buttons that will "create" the same Activity but by using two different objects from the same base class, hence allowing me to customize the behavior of the application depending on the button that was clicked.
However, when I am trying to create the Intent instance, my application crashes.
Here is the code of the base Activity class
public class BaseDictionnaryActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basedictionnary);
}
public void onDestroy()
{
super.onDestroy();
}
}
and here is the code that crashes. The line is the one creating the Intent object.
public class DictionnaryActivity extends Activity
{
private BaseDictionnaryActivity jlpt1;
private BaseDictionnaryActivity jlpt2;
private Button btjlpt1 = null;
private Button btjlpt2 = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionnary);
jlpt2 = new BaseDictionnaryActivity();
jlpt1 = new BaseDictionnaryActivity();
btJLPT1 = (Button)findViewById(R.id.jlpt1);
btJLPT1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent myIntent = new Intent(DictionnaryActivity.this,
jlpt1.getClass());
jlpt1.this.startActivity(myIntent);
}
});
btJLPT2 = (Button)findViewById(R.id.jlpt2);
btJLPT2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent myIntent = new Intent(DictionnaryActivity.this,
jlpt2.getClass());
jlpt2.this.startActivity(myIntent);
}
});
}
public void onDestroy()
{
super.onDestroy();
}
}
Thank you for your help !
Just to make correction,
Intent myIntent = new Intent(DictionnaryActivity.this,
jlpt1.getClass());
In this the second argument must be, your target activity BaseDictionnaryActivity.class
So, it looks something like,
Intent myIntent = new Intent(DictionnaryActivity.this,
BaseDictionnaryActivity.class);
startActivity(myIntent);
Also please make sure there will be entry of BaseDictionnaryActivity in your Application's manifest file,
Which is look like,
<activity android:name=".BaseDictionnaryActivity"
....>
</activity>
Maybe:
Intent myIntent = new Intent(DictionnaryActivity.this,
BaseDictionnaryActivity.class);
startActivity(myIntent);
change this
Intent myIntent = new Intent(DictionnaryActivity.this,
NextActivity.class);
Intent myIntent = new Intent(DictionnaryActivity.this,
jlpt2.class);
^^^^^^^^^^^^
You need to provide next activity .class in second argument of Intent.
Replace jlpt1.getClass() with NameOfClassToBeLaunched.class
Also this is bad practice to create Activity instances in other activities.

Problems sending data from one activity to another with application

As the title says I want to transfer data, in this case the information introduced by the user on an EditText and a Spinner, from one activity to another.
I am following a tutorial from a book but it doesn't work (I think its not complete). Here the code of the program:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.location=(EditText)findViewById(R.id.location);
this.cuisine=(Spinner)findViewById(R.id.cuisine);
this.grabReviews=(Button)findViewById(R.id.get_reviews_button);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.cuisine, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.cuisine.setAdapter(adapter);
this.grabReviews.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
handleGetReviews();
}
}
);
}
private void handleGetReviews() {
RestaurantsActivity application= (RestaurantsActivity) getApplication();
application.setReviewCriteriaCuisine(this.cuisine.getSelectedItem().toString());
application.setReviewCriteriaLocation(this.location.getText().toString());
Intent intent=new Intent(Constants.INTENT_ACTION_VIEW_LIST);
startActivity(intent);
}
This code above doesn't work. I dont understand four things:
-RestaurantsActivity must be the actual activity right?
-In all the examples I have seen over the internet there is an application extends class, in this example there isnt.
-setReviewCriteria function is missing
-Where does Constants.INTENT_ACTION_VIEW_LIST come from ?
So your target is to get the data to Restaurantsactivity?
Normally data in android are handed over from one activtiy to another by using Intents.
So first you create an intent.
Then you put the data you want to transfer into the intent by using the intent.putExtra() method.
In the activity that gets the intent you can get the data by using getIntent().getExtra() method (getExtra can be something like getStringExtra()).
Here is a small example for a edit box called "name":
public void onCreate(Bundle iBundle){
//do some stuff here
//perhaps define some Buttos and so on
//now lets start the activity
Intent intent = new Intent(currentActivityname.this, ActivityYouWantToStart.class);
intent.putExtra("name", name.getText().toString())
startActivity(intent); // you can also start an startActivityForResult() here :)
}
In our receiving activity you can now handle the intent (e.g. in the onCreate() method
public void onCreate(Bundle iBundle){
String name = this.getIntent().getStringExtra("name",some default value);
}
Try to put data in the Bundle and start Activity with this Bundle
Intent intent = new Intent(this, YourSecondActivity.class);
intent.putExtra(... HERE YOUR BUNDLE WITH DATA ...);
startActivity(intent);
Hope, it help you!

Categories

Resources