Here i wrote some code, and i want to call a method of other class from onClick() and getting NPE in "new Start().moreApplication(feedsId);" line..
final TextView feeds=(TextView)findViewById(R.id.more_feeds);
feeds.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Log.e("MoreChoices","onclick---------");
final int feedsId= feeds.getId();
Log.e("MoreChoices","onclick----After initialization of id--------");
new Start().moreApplication(feedsId);
Log.e("MoreChoices","onclick----------------After calling--------");
}
});
Start.java is my an other Activity class, and i have one in Start.java, and i want to call that method from other class with using this code..
Please tell why i am getting NPE in
"new Start().moreApplication(feedsId);"
line...
Thanks in Advance please guide me....
Please, take some time reading anddev book, a very good place to start android development.
Read pages 50+ and you will understand that your not doing the right thing to create activities and pass data from one to another.
You should
startActivity by using either an intent or the class of this activity
pass data from your activity to the new one using intent's extra parameters.
Regards,
Stéphane
replace this line
final TextView feeds=(TextView)findViewById(R.id.more_feeds);
by
final TextView feeds=(TextView)this.findViewById(R.id.more_feeds);
I hope you got solution .
I think u need to get the View ID which u have clicked the enhanced code look like
final TextView feeds=(TextView)findViewById(R.id.more_feeds);
feeds.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Log.e("MoreChoices","onclick---------");
final int feedsId= arg0.getId();
Log.e("MoreChoices","onclick----After initialization of id--------");
new Start().moreApplication(feedsId);
Log.e("MoreChoices","onclick----------------After calling--------");
}
});
Related
this is my first question being asked on stackoverflow. My question is regarding variable use across different recyclable intents.
e is declared like this.
final Bundle e=getIntent().getExtras();
Here i am creating new intents for different setOnClickListener() and passing a different variable for each intent.
Intent info = new Intent(EItemListView.this, ItemInfo.class);
Bundle extras = new Bundle();
int[] a=new int[listview.getAdapter().getCount()];
if (i == 0) {
extras.putIntArray("img", n5x_images);
extras.putString("info", n5x_info);
extras.putInt("pc",a[0]);
} else if (i == 1) {
extras.putIntArray("img", op3_images);
extras.putString("info", op3_info);
extras.putInt("pc",a[1]);
}
info.putExtras(extras);
startActivity(info);
Now this is the OnClickListener() where i am trying to update the variables which i passed through the intent extras, but am unable to update those variables.
addtc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c=e.getInt("pc");
c=c+1;
Log.i("Log","value "+c);
}
The log message which i get from the above method is always 1, i think the variable in c is always set to 0 and then increments by 1 and hence the log message shows 1.
I need the variables a[0],a[1],a[2], etc to pertain its increment operation.
To make it more clear, this is the java file i am using. The error is in the OnClickListener of addtc button at the bottom of this code.
public class ItemInfo extends AppCompatActivity {
private ViewAnimator viewanimator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_info);
Button next=(Button)findViewById(R.id.bnext);
Button prev=(Button)findViewById(R.id.bprev);
viewanimator=(ViewAnimator)findViewById(R.id.viewAnimator);
TextView info=(TextView)findViewById(R.id.item_info);
Button addtc=(Button)findViewById(R.id.badd);
Button test=(Button)findViewById(R.id.button);
Bundle e=getIntent().getExtras();
int img[]=e.getIntArray("img");
for(int i=0;i<img.length;i++)
{
ImageView imgview = new ImageView(getApplicationContext());
imgview.setImageResource(img[i]);
viewanimator.addView(imgview);
}
info.setText(e.getString("info"));
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewanimator.showNext();
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewanimator.showPrevious();
}
});
addtc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c=e.getInt("pc");
c=c++;
Log.i("Log","value "+c);
}
});
}
}
Thanks in advance!!!
Your approach is wrong. You cannot do this in this way. Your understanding of what an "extra" in an Intent is incorrect.
When you do this:
extras.putInt("pc",a[1]);
This adds an "extra" to the extras Bundle. The Bundle is simply a key/value pair map and you have added an entry that contains the key "pc" and the value is whatever a[1] is. It puts a copy of the value of a[1] into the Bundle, it does not put a reference to a[1] in the Bundle.
Therefore, if a[1] is 5 when you add it to the extras Bundle, a[1] will always be 5 and will never be changed to anything else.
You can't do this in this way.
Alternative: Depending on your application architecture and what you are trying to do, you can use one of the following methods:
1) Use startActivityForResult(), pass the data from one Activity to another, have the second Activity update the data and put it back into the Intent which is then returned to the "calling" Activity by using setResult().
2) Use a static variable (basically a "global" variable) to contain the data. Both activities can then access the data directly (you don't need to put the data in the Intent.
3) Put the data in a database. Both activities can then read/write from/to the database.
First advice I can give you is debugging and posting debug result. for example, are you sure that a[0] and a[1] aren't 0?
Assuming they are not, why are you declaring the bundle as final? referring to this probably final is not what you were looking for. Try removing it or replacing with private
Another suggestion is more for readable purpose, replace c = c+1; with c++; but this doesn't change the result, it just make it more linear and easier for reading.
Now after this fix (the final keyword one) tell me if something changed please :)
I'm programming an app which one of its functionalities is that the users can tap on a plus button (typical (+)...) that has to create a new activity and a new XML file with a specific structure.
I'm beginner on Android and also in Stack Overflow, so due to that I'm unable to post images and make this question easier to understand.
I need you to summarize how to program this. I'm not telling you to codify my code, I just need to know if it's possible to do and ,more or less, the steps to get it.
Hope you can help me. Thanks!
Okay, so this is how you'd do it, if you're sure you want to create a new instance of the activity from that very same activity. First, make a reference to your "plus button". Assuming the android:id="#+id/plusButton, it'd be like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//Initialize your layout and variables
findViewById(R.id.plusButton).setOnClickListener(new View.onClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
This would launch a new instance of the same Activity (MainActivity) and give it focus.
You can make the activity yourself and have a button open the activity.
You'd start by making a new android activity. With eclipse it's simply File >> New >> Other >> Android Activity and then just fill out the form and hit finish. Make sure your current project is open.
Draw the button in your xml file, make sure it has a unique Id to reference and your text is declared in your strings.xml file that should look like this.
<string name="strX">(x)</string>
then in your activity's xml file under your button make sure you have
android:text="#string/strX"
You can also reference this in the GUI in the properties window under text.
With the button code in your .java you could use OnClickListener and Intent and the code for the button would look something like this.
TextView buttonYourButton = (TextView) findViewById(R.id.ButtonYourButtonId);
Button pushYourButton = (Button) buttonPlay;
pushYourButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent nameOfIntent = new Intent(NameOfCurrentClass.this, NameOfNewClass.class);
startActivity(nameOfIntent);
}
});
R.id.ButtonYourButton is the Id you gave the button, and the .class is the name of the public class in that .java file. Like:
public class MainActivity { ...
Anyways, good luck I was where you were about a month ago. Don't forget to check out tutorials on Android development on youtube, there are about a million of them. Also you can search stackoverflow for questions that already have been asked.
Is there any way to call a listener manually from code?
More background information: I use a Spinner and a DatePicker. With the Spinner you can choose a reason for staying at home (maybe your ill, maybe you have vacation) and with the DatePicker you can choose the date how long you will not be available. With these two pieces of information I build up a string for a TextView and show the same data in a compact way. The building process for the string is set by some listeners which recognize changes on one of the two controls and build and set up the new string.
If I start the program and read some data from a server the string will not be build (clearly because nothing changed and no listener will called).
The workaround is to build the string in my own onLoaddata() method. But I think it would be smoother way to call one listener to build the string for me. I also can "call" a listener if I just do some fake .updateDate but I don't think it’s a good idea to create useless calls...
Maybe someone of you have a good hint for me?
Use the following pattern:
public class YourActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Some initialization here
findViewById(R.id.some_button).setOnClickListener(this);
...
// Here you want to update your view
updateTextView();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.some_button:
// Here you also want to update your view
updateTextView();
break;
...
}
}
private void updateTextView() {
// Here you update your view
...
}
}
public class Menu extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
//myIntent.setClassName("hello.World", "hello.World.mybuttonclick");
// myIntent.putExtra("com.android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key needs current package prefix.
//startActivity(myIntent);
//Button myButton = (Button) findViewById(R.id.my_button);
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void updateLayout(){
Intent myIntent = new Intent(Menu.this, mybuttonclick.class);
startActivity(myIntent);
// TextView sayHello = (TextView) findViewById(R.id.Hello);
}
}
Hey guys, I am a new android java student and we have to develop a simple hello world app.. I am finding some difficulty getting my onClick() activity to work, using android:Onclick in xml.. what i am trying to do is change the content view do display a simply a different layout and saying hello.. i am using setContentLayout to do this, every time i click said button tho the android app crashes out.. am i doing something wrong?
regards,
Stefan
When you set a click listener in xml you must have the method defined inside the activity you are clicking in. Lets say you set the onClick in xml to be "buttonClicked", you must create a method looking exactly like the one below.
public void buttonClicked(View view)
{
//Your code here
}
The thing to notice is that the method is a public void with only a single parameter of type View. XML defined click listeners must be like this to work. The view object in the example above is the view that was clicked.
You update layout function needs to read
public void updateLayout(View view)
In response to your question, there are a number of things that are issues causing the complication that you described. Let it first be said, that you don't have to do anything any particular way, provided that you make concessions for certain things. Android is a very flexible platform and Java, as an OOP language allows you to do things that many non OOP languages do not.
Whenever you create a "clickable" item, like a Button, if you want to have your program respond, you must have something "listen" to it. This is known as a Listener. In your case, you are looking for an OnClickListener. The OnClickListener does not have to be a part of the Activity necessarily. It just has to be a class that implements View.OnClickListener. Then, you have tell the setOnClickListener() method of the Button who its listener is. The following example shows what is necessary without your declaration in XML (but it is important).
class Menu extends Activity implements View.OnClickListener
{
public void onCreate(Bundle icicle)
{ setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML);
btn.setOnClickListener(this);
}
public void onClick(View view)
{ int id = view.getId();
if (id == R.id.BUTTON_ID_AS_DEFINED_BY_YOUR_XML)
updateLayout()//Do your Click event here
}
public void updateLayout()
{ //updateLayout code...
}
}
Something that needs to be noted is the OnClick() above. Every OnClickListener must use the same signature as theOnClick() That means itmust have the same return and same arguments even if it has a different name. For what you are trying to do (in XML), you have set your android:OnClick to updateLayout. This means that `updateLayout() must be declared as follows:
public void updateLayout(View view)
Now, getting the update method to actually work: While you provide your code, we don't actually know what errors you are getting. It is always much easier to solve a problem if we have a copy of the Logcat output that includes the error you are receiving. Once, we have that we can target your error specifically and I can edit my answer to include what you may additionally need.
FuzzicalLogic
So, I am again, asking a very basic question. I apologize for my ineptness but I guess I read the given tutorials on these topics poorly. My question is as follows:
I would like to use a "listener" pattern to handle button presses on my GUI. I believe an onClickListener is what I need to use to handle these button presses. However, I'm not sure if I should be creating and handling events that occur after the GUI is created within an onCreate method. The following code is within my onCreate method for one of my Activities:
View.OnClickListener upDownListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(v == (upOneButton))
{
Log.d("OptionSelect", "Up One Button Pressed.");
ops.getOptionList().get(0).incrementProbability(4);
} . . .
This method being called updates some GUI text with a different number. It is being called, but the GUI isn't responding. I imagine this has to do with my attempt to use it within the onCreate method.
In short, what is a good and simple way to deal with user events within a GUI and where should this occur?
Thank you so much.
EDIT: Log.d() does in fact get called. Also, ops is an object of type OptionSelect which happens to be the type of the class in which the onCreate() call is made. Will that become an issue? Also, here is the method for incrementProbability():
public void incrementProbability(int numberOfOptions)
{
probability += (numberOfOptions - 1);
if(probability > 100)
{
Log.i("OptionSelect", "Exceeded Maximum by " + (probability - 100));
probability = 100;
}
}
Also, here is relevant code I should've included that is updating my GUI at the end of the onClick() method:
private void refreshDisplay(TextView a, TextView b, TextView c, TextView d)
{
a.setText(getOptionList().get(0).getProbability() + "");
b.setText(getOptionList().get(1).getProbability() + "");
c.setText(getOptionList().get(2).getProbability() + "");
d.setText(getOptionList().get(3).getProbability() + "");
a.invalidate();
b.invalidate();
c.invalidate();
d.invalidate();
}
Thanks for the help so far!
I personally prefer to have my Activities implement listener interfaces and add an onClick method to the Activity itself such as...
public class MyActivity extends Activity
implements View.OnClickListener {
...
#Override
public void onClick(View v) {
...
}
}
I then just use...
myGuiObject.setOnClickListener(this);
...whenever I want to set that method as the listener for any GUI object.