Placement of OnActivityResult with OnClicklistener - java

I have implemented a 3rd party camera scanning app within a project of mine
I have an adaptor that extends a viewholder so i can have a custom layout
Within a view i have a button
When i create the view i add an OnclickListener to the image which i want to make clickable
i want this OnclickListener to call the camera but i need to call an startActivityForResult
i am confused about the placement of the onActivityResult when calling in this way.
my current attempts have been to create a seperate class(scan_activity) which extends activity but i couldnt get the onclicklistener to start the class
i have then attempted to declare it within the setOnClickListener, which as you can guess also failed.
Im guessing the call to the class is the way forward.im sure its an easy fix, but im not seeing it
please help
thanks in advance
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, 1);
((Activity) context).startActivityForResult(intent,99);
}
}
);
and the class
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ScanActivity
}
}
);

The first option should work. You create an Intent object and you specify activity component as a parameter. Android will create an Activity object for you, so, never do that manually. Android should manage the lifecycle of activity.
By starting activity for result you tell Android that it should call onActivityResult callback with request code 99 on your first activity when ScanActivity will be closed.
Handling onActivityResult in your Activity:
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == 99) {
// handle your result here
}
}

Related

I want to open Adapter class when I click the imageView but i get ActivityNotFoundException,any alternative method to do so?

#Override
public void onClick(View v) {
int i = v.getId();
if (i==R.id.cars){
Intent open_adapter_class = new Intent(this,ItemsAdapter.class);
startActivity(open_adapter_class );
}
}
//this is the error I get
android.content.ActivityNotFoundException: Unable to find explicit activity class
{com.dikolobe.salesagent/com.dikolobe.salesagent.ItemsAdapter}; have you declared this activity in your
AndroidManifest.xml?
I know that am getting this error because adapter is not an activity so I just want to get help on how to
open this adapter class if there is a way to do so
From Android documentation:
An intent is an abstract description of an operation to be performed.
It can be used with startActivity to launch an Activity,
broadcastIntent to send it to any interested BroadcastReceiver
components, and Context.startService(Intent)
So, ItemsAdapter has to be an activity, (eg ...extends AppCompatActivity) so you change from one activity to another.
But what you can do is pass an object from that class to another activity
Intent open_adapter_class = new Intent(this,ItemsAdapter.class);

Returning string from Android Activity started with `startActivityForResult` inside `onClickListener` returns null

I use an Intent in MainActivity to start another Activity called MatchesActivity using startActivityForResult. I put breakpoints at finish() inside the started activity (MatchesActivity) and on the Log statement inside onActivityResult because I got NPE inside onActivityResult.
intent.getStringExtra("TXAMATCHES") contains what it should.
But Intent data comes back null.
Is this likely/possibly because I start the Intent inside an onClick listener?
Or because MatchesActivity calls a method in another class that extends AsyncTask and the data is what that task produces? (But the correct data is found in txaMatches just before it is returned to MainActivity...)
public class MainActivity extends Activity
{
...
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v)
{
...
Intent matchesIntent;
matchesIntent = new Intent(MainActivity.this, MatchesActivity.class);
startActivityForResult(matchesIntent, 0);
...
}
...
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.w("MainActivity","" + onActivityResult " + data.getStringExtra("TXAMATCHES"));
}
}
...
public class MatchesActivity extends Activity implements DatabaseConnector.DatabaseProcessListener
{
...
#Override protected void onDestroy()
{
super.onDestroy();
finishThisAndReturnString();
}
public void finishThisAndReturnString()
{
Intent intent = new Intent();
intent.putExtra("TXAMATCHES",txaMatches.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
(The started Activity is terminated by user pressing back icon.)
You can't finish a activity in the onDestroy method. In this lifecycle phase the activity is already dying.
The call of the finish() method will call the onDestroy, not the other.
Call the finish method when you want to to finish the MatchesActivity.
What you're trying to do is not correct. You're trying to call finish() on the onDestroy() method. onDestroy() gets called when the Activity is about to be killed. So basically calling finish() at that point is wrong.
I assume that you are trying to do some processing in the AsyncTask. I suggest that you call the finish() method on the onPostExecute() method of the AsyncTask.
You are setting the data in the Intent object in onDestroy() method . So in this case, whenever you call setResult() in onDestroy() method, you will always get resultCode in onActivityResult() as '0' which is the value for RESULT_CANCELED and whenever you get RESULT_CANCELED in onActivityResult() you get data object null. That's why you don't get the values you set in Intent .
First try to get the value of
txaMatches.getText().toString()
Check this value in the MatchesActivity Class.
It is possible that it is returning null value due to which u are getting the problem.
The problem is fixed by removing finishThisAndReturnString() from onDestroy, as stated in the first two Answers.

Using buttons on android - newbie

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)

Do I need to include a default Intent in order to return to the previous Activity?

I am working on a To Do List Android application (it happens to be for a class assignment, but that's not what I'm asking about--I've tried to leave out as much code as I could). The main screen displays a list of ToDo items with a button at the bottom to open the Add New ToDo Item screen.
On the Add New ToDo Item screen, there is a Cancel button.
Relevant ToDoManagerActivity.java snippet:
public void onCreate(Bundle savedInstanceState) {
// Init and setup adapter, etc.
footerView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ToDoManagerActivity.this, AddToDoActivity.class);
startActivityForResult(intent, ADD_TODO_ITEM_REQUEST);
}
});
// Attach the adapter to this ListActivity's ListView
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
log("Entered onActivityResult()");
// Check result code and request code.
// If user submitted a new ToDoItem
// Create a new ToDoItem from the data Intent
// and then add it to the adapter
}
Relevant AddToDoActivity.java snippet:
protected void onCreate(Bundle savedInstanceState) {
// Initialize default view, handle other events, etc.
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED, new Intent());
finish();
}
});
}
The above code works. Previously, I was trying this in the onClick handler for cancelButton:
public void onClick(View v) {
finishActivity(RESULT_CANCELED);
}
When I clicked the Cancel button, I could see that the onActivityResult was being reached in the logs, but the screen was not reverting back to the main ToDo list screen.
Why does the above code not return me to the previous screen, but the following code does return me to the previous screen? What am I misunderstanding about the task backstack/activities?
public void onClick(View v) {
setResult(RESULT_CANCELED, new Intent());
finish();
}
According to the documentation:
public void finish ()
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via
onActivityResult().
and
public void finishActivity (int requestCode)
Force finish another activity that you had previously started with startActivityForResult(Intent, int).
You should call finish() to close the current activity and finishActivity() to close another activity you started using startActivityForResult(Intent intent, int requestCode). Calling finishActivity() on the current activity will not close it.
Also, there's no point in creating a new Intent for setResult() as you are not passing back any data. Doing this would be sufficient:
setResult(RESULT_CANCELED);
finish();
From Android Docs:
public void finishActivity (int requestCode)
Force finish another activity that you had previously started with startActivityForResult(Intent, int).
finishActivity does not finish the current activity but calls finish for an activity called with requestCode
If you look at the documentation for finishActivity() it says that it will force finish an activity started with startActivityForResult(), but you have to pass in the request code that you used to start the other activity. In your case it would be ADD_TODO_ITEM_REQUEST.
This is probably not the API you want to use. Your 2nd method is cleaner in that you don't need to force close the child activity, but let it finish in the normal way.

Switching back to previous activity in tabhost

I am using TabActivity(for example, TActivity) to create tab and in every tab I am loading instance of same activity(for example, MainActivity).
Through this activity I want to switch another activitity(for example, ChildActivity which will be same for every tab i.e. in every tab we will get instance of this activity) using Button click.
This button is hardcoded in original TabActivity(TActivity).
Now I am able to do up to this. But Now I want to switch between 'MainActivity' and 'ChildActivity' using same Button.
MainActivity:
class MainActivity ...{
onCreate(){
Btn.setOnClickListener(new OnClickListener(--) {
public void onClick(--){
Intent intent = new Intent(getBaseContext(),ChildActivity.class);
replaceContentView("MainActivity", intent);
}});
}//MainActivity
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) .getDecorView(); this.setContentView(view);
}//replaceContentView
in ChildActivity:
public void hideCurrentActivity(){
Intent intent = new Intent(getBaseContext(),MainActivity.class);
replaceContentView("ChildActivity", intent);
}
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .getDecorView(); this.setContentView(view);
}
Ok, now problem is that this code creates fresh activity everytime. So all previous data is getting lost once I switch to previous activity.But i don't want to create fresh activity instead just want to bring old one to front.
Can anybody help?
Thanks in advance.

Categories