How to add two functions in one onClick method? - android

The code below is an onClick() method for a Button.
It keeps giving me an error.
If I delete the startActivity(), then it works fine.
How can I use a POST method when I click the Button, and also move to another Activity?
public void onClick(View view) {
switch (view.getId()) {
case R.id.register:
if (!validate())
Toast.makeText(getBaseContext(), "Enter user information!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute(herokuServer);
startActivity(new Intent(this, FoodPreference.class));
break;
}
startActivity(new Intent(Register1Activity.this, FoodPreference.class));
}
THE ERROR:
04-27 19:41:26.066 1974-1974/com.opshun_test.opshun_test E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.opshun_test.opshun_test, PID: 1974
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.opshun_test.opshun_test/com.opshun_test.opshun_test.FoodPreference}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1761)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at com.opshun_test.opshun_test.Register1Activity.onClick(Register1Activity.java:173)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-27 19:41:26.106 1974-2307/com.opshun_test.opshun_test I/output﹕ org.apache.http.client.methods.HttpPost#5b541ce

If you are using anonymous inner class for the click listener , use className.this instead of this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Activity2.class));
}
});
if you are handling the click in the activity, make sure the Activity is defined in the manifest file. Provide the stack trace for a complete solution.

You didn't declare you activity in you manifest. Add the following lines to you manifest file.
<activity
android:name=".FoodPreference"
android:label="#string/title_activity_food_preference" >
</activity>
Moreover, the more safe way to start an intent is always checking the intent is resolvable or not, like the following code.
Intent intent = new Intent(this, FoodPreference.class);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
// TODO: activity not found
}

Register your Activity FoodPreference in Manifest
and you are calling
new HttpAsyncTask().execute(herokuServer);
So better Intent to FoodPreference.class in onPostExecute()

Related

Android - referencing a string in strings.xml in a .java file

i have this code in MainActivity.java:
String passName = new String(getString(R.string.name));
where name is a string in strings.xml:
<string name="name">My name</string>
it does not give me an error, but the app keeps crashing, how can i do this properly?
basically i want to save my name as a string variable in MainActivity.java, but store the actual text in strings.xml
i originally had:
String passName = new String("my name");
and i was able to successfully pass it to the second activity, but i want the text to be stored in strings.xml, not the .java file
edit: i have provided more of my code for context:
public class MainActivity extends AppCompatActivity {
Button button;
//code that will eventually point to my name in strings.xml
String passName = new String("my name");
//String passName = getResources().getString(R.string.name);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code that senses when the button is clicked
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code that executes when the button is clicked
Toast.makeText(getApplicationContext(),"Moving to second activity...",Toast.LENGTH_SHORT).show();
//code that passes my name to the second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", passName);
startActivity(intent);
}
});
}
}
as for a crash log, there doesn't seem to be one. when i launch the app it opens and then immediately closes again.
the message it gives me is this:
01/19 15:21:11: Launching 'app' on Pixel 4 XL API 30 (test).
Install successfully finished in 388 ms.
$ adb shell am start -n "my.name.n0000.lab_n0000/my.name.n0000.lab_n0000.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
edit: i have added the proper logcat dialogue:
2023-01-19 15:32:41.587 7562-7562/my.name.n00000.lab_n00000 E/AndroidRuntime: FATAL EXCEPTION: main
Process: my.name.n00000.lab_n00000, PID: 7562
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.name.n00000.lab_n00000/my.name.n00000.lab_n00000.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:97)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:134)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:128)
at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:612)
at my.name.n00000.lab_n00000.MainActivity.<init>(MainActivity.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2023-01-19 15:32:41.615 7562-7562/my.name.n00000.lab_n00000 I/Process: Sending signal. PID: 7562 SIG: 9
There is a lifecycle involved when creating activities. Some things should not be accessed before the onCreate method is called. So you should be able to declare passName prior and then inside onCreate, you can initialise it.
public class MainActivity extends AppCompatActivity {
Button button;
String passName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code that senses when the button is clicked
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code that executes when the button is clicked
Toast.makeText(getApplicationContext(),"Moving to second activity...",Toast.LENGTH_SHORT).show();
//code that passes my name to the second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", passName);
startActivity(intent);
}
});
passName = getResources().getString(R.string.name);
}
}
You can read more about the activity lifecycle here
And in particular in this paragraph, it talks about instantiating class scope variables.
For example, your implementation of onCreate() might bind data to lists, associate the activity with a ViewModel, and instantiate some class-scope variables.

why does this onclicklistener not work?

I created this click listener in a android project, it is taken from a tutorial.
It worked there but does not seem to work when I tried it in my new app.
ImageView animals = (ImageView) findViewById(R.id.anim);
animals.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent animalsIntent = new Intent(MainActivity.this, animals.class);
// Start the new activity
startActivity(animalsIntent);
}
});
The app crashes when I do this.
This is the logcat error message:
03-13 23:28:21.750 7734-7734/com.example.android.trollsounds E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.trollsounds, PID: 7734
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.android.trollsounds/com.example.android.trollsounds.animals}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1895)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1589)
at android.app.Activity.startActivityForResult(Activity.java:4228)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4187)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at android.app.Activity.startActivity(Activity.java:4515)
at android.app.Activity.startActivity(Activity.java:4483)
at com.example.android.trollsounds.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22288)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
animals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent animalsIntent = new Intent(MainActivity.this, animals.class);
// Start the new activity
startActivity(animalsIntent);
}
});
In the onClickListerner you had (new OnClickListener(), should new new View.OnclickListener. This should work for you
In animals.setOnClickListiner, you need to do new View.OnClickListener()instead of new OnClickListener(). Hope that helps!
ImageView animals = (ImageView) findViewById(R.id.anim);
//Its View.OnClickListener()
animals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Also change to this instead of GameActivity.this
Intent animalsIntent = new Intent(this, animals.class);
// Start the new activity
startActivity(animalsIntent);
}
});
Also, change Intent animalsIntent = new Intent(MainActivity.this, animals.class); to Intent animalsIntent = new Intent(this, animals.class);
EDIT:
You also have a ActivityNotFound error, meaning that the animals class dosent exist. Try checking the name

Application has stopped when close button clicked

I am developing an android app but my app is being stopped
Here is the steps I did: I ...
1. am using tabbed activity and there is a list view
2. Each element in listView is registered for context menu
3. First option is context menu is for editing info for the view
4. Once it is clicked, it opens another activity(intent is used)
And the error is when I click close button while the new activity is open, I am having error:"Unfortunately app has stopped"
Edit Class:
public class Editor extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Intent intent = getIntent();
int position = intent.getIntExtra("POSITION", -1);
TextView t = (TextView)findViewById(R.id.intentResult);
t.setText(position+"");
}
}
Intent Call :
public boolean onContextItemSelected(MenuItem item) {
if(item.getItemId()==EDIT_ID){
}
else if(item.getItemId()==DELETE_ID){
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
Intent intent = new Intent(getContext(), Editor.class);
intent.putExtra("POSITION", acmi.position);
startActivity(intent);
}
return super.onContextItemSelected(item);
}
//acmi is just an integer
Error: 01-21 16:54:59.714 2820-2820/com.example.abu_bakr.darsjadvali
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abu_bakr.darsjadvali, PID: 2820
java.lang.RuntimeException: Unable to resume activity
{com.example.abu_bakr.darsjadvali/com.example.abu_bakr.darsjadvali.MainActivity}:
java.lang.IllegalStateException: trying to requery an already closed
cursor android.database.sqlite.SQLiteCursor#2e3a8e12
at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:3033)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3064)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.IllegalStateException: trying to requery an
already closed cursor android.database.sqlite.SQLiteCursor#2e3a8e12
at android.app.Activity.performRestart(Activity.java:6076)
at android.app.Activity.performResume(Activity.java:6099)
at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:3022)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3064) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5356) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) 
at com
.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
As your error log says, it's a database exception.
Post the complete code of your MainActivity so we can understand what's going on

ActivityNotFoundException, error starting an activity

This is my social fragment activity and it contains buttons view. when i click on it i want to switch from one activity to other but when i lauch it on phone and click on button it says "unfortunately app stopped" what should i do to switch from one fragment to other fragment.
here is my social frag code:
SocialFrag
and i want to switch from social fragment to TechGadget Fragment on button click.
Here is Log cat
Log Cat
my App contains navigation drawer with tabhlayout and i declared buttons in one tab...while i want to open new activity when button gets clicked.
**#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.social_layout,container,false);
b = (Button) rootView.findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),TechGadgets.class);
startActivity(i);
}
});
return rootView;
}
}**
it reutrns error and here is log cat
04-28 01:07:07.300 17089-17089/com.example.android.techfnss E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.techfnss, PID: 17089
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.android.techfnss/com.example.android.techfnss.TechGadgets}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1885)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1579)
at android.app.Activity.startActivityForResult(Activity.java:3934)
at android.app.Activity.startActivityForResult(Activity.java:3894)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:907)
at android.support.v4.app.Fragment.startActivity(Fragment.java:916)
at com.example.android.techfnss.SocialFragment$1.onClick(SocialFragment.java:26)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-28 01:07:10.275 17089-17089/com.example.android.techfnss I/Process: Sending signal. PID: 17089 SIG: 9
This question has been asked tens of times (at least), so you could've found an answer by a Google search. However, here is how you do it...
Button button = (Button) findViewById(R.id.my_button);
button.setOnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
};
Of course you would replace the relevant values with corresponding ones in your own code.
If you're looking for a more specific answer, ask a more specific question (with evidence that you have done research to find the answer yourself, or even at least a log trace from the crash you are getting).
You need to add setOnClickListener on your button inside onViewCreated method, like this --
public void onViewCreated(View view, Bundle savedInstanceState){
b = (Button)view.findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), 2nd_Activity.class);
startActivity(intent);
}
});
}
Hope this helps!
use this code -
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
startActivity(intent);
here, OtherActivity.class is the name of activity that you want to go,and Mainactivity.this is your current activity.
You can pass the context to the Fragment when you create it and then reference it there. Or you can just use getActivity() instead of getActivity().getApplicationContext() but the first option is the best because sometimes getActivity() just doesn't work.
Always pass the context to the fragment.
Clearly it says that the activity is not declared in the manifest, instead of extend fragment, extend to any type of activity and add this line to your manifest inside the <aplication> </aplication> body:
<activity android:name=".TechGadgets"></activity>
Example:
<aplication>
...
<activity android:name=".TechGadgets"></activity>
...
</application>
And close this ask please
try using the below code
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
and also check did you added activity in manifest
<activity android:name=".TechGadgets"></activity>

FATAL EXCEPTION: main NullPointerException in Android

I have two class. One of them is activity. I have a function in activity class and try to call in other class. In function i can't use view functions(setContentView, findViewById) These functions works well in onCreate. I try to change image position and size.
function definition like:
public void changePosition(int x, int y, int z){
}
I always got this error. Why these functions works only in onCreate?
Logcat:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.scan, PID: 26122
java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1970)
at com.example.project.scan.ProjectActivity.changePosition(ProjectActivity.java:255)
at com.example.project.scan.Model$1.handleMessage(Model.java:145)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
ProjectActivity.java:255 :
image = (ImageView)findViewById(R.id.im);
Model.java:145:
myActivity.changePosition(x,y,z);
Seems like you've instantiated your myActivity with new. Never instantiate activities with new as they won't be properly initialized for anything you'd use an activity for.
Use an Intent to instantiate activities with correct lifecycle initialization, or pass the activity reference (this in an activity) to other methods that need to call methods in the activity.
You can pass the Activity reference
use below code:
public class YourClass
{
Activity activity ;
public YourClass(Activity _activity)
{
activity = _activity ;
}
}
Then use it as :
classObject.changePosition(x,y,z);
Now you can use method like :
activity.findViewById(id)
Don't forget to pass the Activity reference as:
YourClass classObject = new YourClass(ProjectActivity.this);
Hope it helps ツ

Categories

Resources