Here is my onCreate() method. I am trying to pass a variable from one intent to this intent. That works fine. When I press back button and go back to previous intent to change the value, then the application crashes. And also when I change the orientation, the application crashes. I am getting "Nullpointer exception" at the pp.getData() method. It passes null argument into the function. How can I overcome this? do I need to add any other details?
public void onCreate(Bundle savedInstanceState) {
// get intent data
Intent i = getIntent();
setQuery(i.getExtras().getString("query"));
Log.v("query:", getQuery());
userquery = getQuery();
super.onCreate(savedInstanceState);
setContentView(R.layout.product_view_layout);
try {
pp = new Parser(userquery);
productData = pp.getData(asynctask, userquery);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mProductViewPagerAdapter = new ProductViewPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mProductViewPagerAdapter);
}
If the "query" extra doesn't exist in the Intent then it will return null. You should perform a null check to make sure you don't get nullPointerExceptions.
String query = i.getExtras().getString("query"));
if(query == null) {
setQuery("");
}
else {
setQuery(query);
}
If you want to receive results in the first activity you have to user this"
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
also when you start the first activity you have to start it startActivityForResult.
On back set the result as RESULT_OK or RESULT_CANCEL. look in tho activity on developers android.
Related
I am using a Fragment to start a new Activity using startActivityForResult(), I am getting the result (Bundle) in onActivityResult() method.Since onActivityResult() called before onResume().I want to make sure, I keep/save the Bundle properly so that when Fragment's onResume() gets called, I get the kept/saved result to perform further action.
What are the different ways to achieve this. I tried using getArguments()/setArguments(), but that seems to be not the right way to achieve this.
Try this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
mResultBundle = data.getExtras(); //mResultBundle is in fragment
//scope
}
}
}
#Override
protected void onResume(){
super.onResume();
if(mResultBundle != null){
// process saved bundle from activity result here
// don't forget to set it back to null once you are done
mResultBundle = null;
}
}
In my android app I want to change the input method. So I start a new Activity which shows the language settings in the device. Then user can change it. However then I want to know that if the user has changed it. So I wrote a function for that also. My code so far is...
Intent enableIME = new Intent(android.provider.Settings.ACTION_INPUT_METHOD_SETTINGS);
startActivityForResult(enableIME,0);
if(isInputMethodEnabled()){
activateshadow.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_pressed));
activateshadow.setText("Deactivate Shadow");
prefs.edit().putBoolean("Activate", false).commit();
}else{
Toast.makeText(MainActivity.this,"You haven't change the input method to simpleIME.In order to activate you must change it.",Toast.LENGTH_SHORT).show();
}
my is inputMethodEnabled function is....
public boolean isInputMethodEnabled() {
boolean isIME ;
String id = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
String [] name = id.split("/.");
// Toast.makeText(MainActivity.this,"s:"+name[1]+":s",Toast.LENGTH_SHORT).show();
if(name[1].contains("SimpleIME") ){
isIME = true ;
}else{
isIME = false;
}
// Toast.makeText(MainActivity.this,"Returning..."+isIME,Toast.LENGTH_SHORT).show();
return isIME;
}
if(isInputMethodEnabled()) always fails because when the new intent(settings) opens and it take some time to change the input method to simpleIME . How to fix this problem?
You catch when a launched Activity returns in onActivityResult. The requestCode you supplied to startActivityForResult will be a parameter, as will the Activity's result. The Activity may also set other data which you didn't ask about.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 555) {//555 is the intent ID you gave in startActivityForResult(enableIME,555);
if (resultCode == /*Result1*/)
//Do something
else {
//Do something else
}
}
}
You need a unique id when calling startActivityForResult(enableIME,0);
startActivityForResult(enableIME, 555);
Better still replace 555 with a named variable.
if u look at android life cycle, when activity is finished whole android call onDestroy() method.
so u can call and override this method.
just need write:
#override
protected void onDestroy(){
// code
super.onDestroy();
}
u can manage and override all of life cycle's parts in android
e.g: onResume to get current activity
i hope this help u
GOAL
What I am trying to do:
Click on my search button and my database is queried with the results passed in. If nothing is found, we are taken to an activity which says so, but if results are found they are loaded into a list.
What I have done
When I click on the search button I call startActivityForResult then this intent calls an activity (whose layout consist of a list_view). The search button also pass along my parameters and query my database.
if there are no results then an activity saying "No Records" is displayed"
and if there are records the else condition is true and the records are loaded in the list
PROBLEM
The problem I am experiencing is, when the list is loaded, if I want to go back to my search form, I must press the back button a total of three times. I am not entirely sure but I believe this strange behavior is stemming from me not returning a result to the started activity when the else clause is invoked.
I have placed what I think is the important part of my code below, would appreciate any assistance
Main Activity
private void startStudentQuery() {
Intent intent = new Intent(getBaseContext(), retrieveStudentData.class);
intent.putExtra("firstname", firstname);
intent.putExtra("lastname", lastname);
//startActivity(intent);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
Intent X = new Intent();
X.setClass(getBaseContext(),NotFound.class);
startActivity(X);
}
}
retrieveStudent Activity
//this activity is a listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_student)
}
//Left out some code, just showing the main parts
public class StudentAsynTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//return result to show Activity if no records are found
if (jsonArray.length() == 0) {
Intent intent=new Intent();
setResult(2,intent);
finish();
} else {//Show list if records are found
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jRealObject = jsonArray.getJSONObject(i);
Student student = new Student ();
student.setFirstname(jRealObject.getString("f_name"));
student.setLastname(jRealObject.getString("l_name"));
student.setImage(jRealObject.getString("image"));
studentList.add(student);
}
}
In startStudentQuery, you should call startActivityForResult only, but now you have called retrieveStudentData twice.
I'm creating a dynamic form activity and I get the instructions on how to make the forms from a db. The activity essentially just scrolls the list of questions and sees what type they are and adds them. So it's an activity that adds a view as a question. That all works fine by itself. I tried to keep the responses/questions inside the specific question classes which just subclass a base question.
The problem I'm having is when I try to add a camera "question" to prompt the user to take a picture, I can't get the result inside the view. I managed the launch the activity in the view, and it returns the result to the questionnaire activity. The activity doesn't know which question it's meant to add it to, since it's all done dynamically. So I tried passing through the questionId through as an extra in the camera intent and receive it in the questionnaire activity where it then scrolls through the questions it's added and if it's the same one, it adds the picture to the question it's associated to.
The way it adds questions is by having a viewgroup which just inserts at a part for each of them.
This the relevant part that launches the camera (I've tried using it without a bundle, too). This is inside a subclass of a BaseQuestion which is just a subclass of a linearlayout:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Bundle bundle = new Bundle();
bundle.putInt("questionId", getQuestionId());
intent.putExtras(bundle);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
Environment.getExternalStorageDirectory(), "image.tmp")));
((Activity)getContext()).startActivityForResult(intent, TAKE_PHOTO);
This is the relevant part that handles the result which is in an activity.
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
Bitmap image = null;
switch (requestCode)
{
case TAKE_PHOTO:
{
if (resultCode == RESULT_OK)
{
InputStream inputStream = null;
File file = new File(Environment.getExternalStorageDirectory(),
"image.tmp");
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (inputStream == null) {
Uri uri = imageReturnedIntent.getData();
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
image = createScaledBitmapFromStream(inputStream, 200, 300);
Bundle bundle = imageReturnedIntent.getExtras();
if (bundle != null)
{
int questionId = bundle.getInt("questionId");
for (BaseQuestion questionView : questionViews)
{
if (questionId == questionView.getQuestionId())
{
questionView.setResponse(image);
}
}
}
}
else if (resultCode == Activity.RESULT_CANCELED)
{
Log.d("something", "something");
}
break;
}
}
}
EDIT: Solved, might not be clear from answer
I made questionIdForResult in my superclass which I set to -1. I then set it to the questionId when it runs startActivityForResult, and then in onActivityResult, I check each question if their questionIdForResult matches their questionId and if it does, use that one. I then set it back to -1 to make sure if you have two, it doesn't go to the other one.
Your approach will not work, as there is no requirement for any camera app to magically copy extras from the incoming Intent to the result Intent. In fact, I will be rather surprised if any camera activity does this.
You could store questionId() in a data member of the activity (e.g., questionIdForTheNextActivityResult), then use that value in onActivityResult(). Bear in mind, though, that taking a picture using a third-party app means that your process may be terminated before you get control again, so be sure to save that data member via onSaveInstanceState() and restore it via onRestoreInstanceState().
I need help in geting results back from intent launched from
preference screen
// Intent preference
DevicePref =
getPreferenceManager().createPreferenceScreen(this);
// Show a Screen with list of Devices Discovered
Intent i = new Intent(this,getDevice.class);
DevicePref.setIntent(i);
DevicePref.setTitle("Select Device");
DevicePref.setSummary(mSelectedDevice);
deviceOptionsCat.addPreference(DevicePref);
I want user to select device... In preference screeen I show "Select
Device" .. when user clicks that, another screen is launched by intent
where all devices are listed. User selects the device.
Now how do I know user selected which device? And I want to update
that in the summary.
Pls. let me know
Thanks
I got the answer, Hope it will help someone like me...
Do not mention intent while creating preference like I did in above code.. Mention intent on OnPreferenceClickListener and then do StartActivityForResult()
// Intent preference
DevicePref = getPreferenceManager().createPreferenceScreen(this);
// Show a Screen with list of Devices Discovered
DevicePref.setOnPreferenceClickListener(onPreferenceClick);
DevicePref.setTitle("Select Device");
DevicePref.setSummary(mSelectedDevice);
deviceOptionsCat.addPreference(DevicePref);
Then create OnPreferenceClickListner and here do StartActivityFromResult()
OnPreferenceClickListener onPreferenceClick = new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (preference ==DevicePref )
{
Intent i = new Intent(DevuiceOptions.this,getDevice.class);
DevicePref.setIntent(i);
startActivityForResult(i,CHOOSE_DEVICE);
}
return true;
}
};
Finally to get the result handle onActivityResult and update Summary field.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode) {
case Constants.CHOOSE_DEVICE:
{
if (data!=null )
{
Bundle b = data.getExtras();
mSelectedDevice = (String) b.get("Name");
UpdatePreferences();
}
}
}
}
Thanks