I am passing values between two activities and fetching the values like this:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
initialUrl = extras.getString("initialUrl");
isFollow = extras.getString("isFollow");
}
if (isFollow == "true") {
editUrl.setText(initialUrl);
setUpWebView(initialUrl);
} else if (isFollow == "false") {
editUrl.setText("http://www.google.com");
setUpWebView("http://www.google.com");
}
the problem is I can see the values being retrieved in the debug window by adding watch to the variables but when the compiler enters the statement if(isFollow=="true"), the condition fails. The else case is also not dealt with. What else do i need to do to ensure that my if condition is satisfied properly?
You should use
isFollow.equals("true")
in your statements.
If String type of data is put in bundle then Try with the following code
String isFollow = null;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
initialUrl = extras.getString("initialUrl");
isFollow = extras.getString("isFollow");
}
if (isFollow.equals("true")) {
editUrl.setText(initialUrl);
setUpWebView(initialUrl);
} else if (isFollow.equals("false")) {
editUrl.setText("http://www.google.com");
setUpWebView("http://www.google.com");
}
If Boolean type of data is put in bundle then Try with the following code
boolean isFollow = null;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
initialUrl = extras.getString("initialUrl");
isFollow = extras.getBoolean("isFollow");
}
if (isFollow) {
editUrl.setText(initialUrl);
setUpWebView(initialUrl);
} else {
editUrl.setText("http://www.google.com");
setUpWebView("http://www.google.com");
}
You need to test either
isFollow.equals("true") or if it is a boolean and not a string, either
isFollow == true or just plain isFollow
(note the no quotes on the second one)
I know this is a really late answer but it would be better to do this if you are passing a Boolean into the intent from the sender:
Boolean isFollow = extras.getBoolean("isFollow");
if(isFollow) {
//Do stuff
}
Related
I created a layout that displays on a SurfaceView and I can get the setDataSource by using Bundle extras = getIntent().getExtras().
Everything works fine until I try to set the landscape layout from land\layout.xml.
My logcat is
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at asia.sumikawa.cybereyeview.liveActivity.onCreate(liveActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6092)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2608)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4216)
at android.app.ActivityThread.access$900(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1476)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
My java coding
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.activity_live_alternate);
//loadLibrary();
final String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString = null;
} else {
newString = extras.getString("urlAddress");
}
} else {
newString = (String) savedInstanceState.getSerializable("urlAddress");
}
urlLink = "rtsp://" + newString.trim().substring(2);
urlString = newString;
The null pointer exception is on line
urlLink = "rtsp://" + newString.trim().substring(2);
which gets the value from
Bundle extras = getIntent().getExtras();
PS I would prefer not using android:configChanges="orientation" as I'm trying to make the layout have different height/width value
EDIT
After adding these code thanks to cricket_007
if (newString != null){
urlLink = "rtsp://" + newString.trim().substring(2);
}else{
Log.i(LOG,"Error");
}
I got this error instead
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char java.lang.String.charAt(int)' on a null object reference
at asia.sumikawa.cybereyeview.liveActivity.playAll(liveActivity.java:307)
at asia.sumikawa.cybereyeview.liveActivity.onCreate(liveActivity.java:77)
which point to these lines of codes
void playAll(){
if(urlString.charAt(0) == '1'){
videoPlay();
}else if(urlString.charAt(0) == '2'){
videoPlay();videoPlay2();
}else if(urlString.charAt(0) == '3'){
videoPlay();videoPlay2();
videoPlay3();
}else if(urlString.charAt(0) == '4'){
videoPlay();videoPlay2();
videoPlay3();videoPlay4();
}}
Just in case this is needed,these are the codes I use to pass the String from the previous class
Intent i = new Intent(addressActivity.this, liveActivity.class);
String strName = content.toString();
i.putExtra("urlAddress", strName);
startActivity(i);
which gets the value from
Bundle extras = getIntent().getExtras();
Not always - if savedInstanceState is not null, then newString is the value of savedInstanceState.getSerializable("urlAddress");, which could possibly return null.
Alternatively, getIntent().getExtras() is null, therefore you hit
if (extras == null) {
newString = null;
}
Which will definitely cause an error.
In either case, you can catch the error by using this
if (newString != null) {
urlString = "rtsp://" + newString.trim().substring(2);
// Code that requires urlString
playAll();
} else {
// Show an error
}
And, then to address the problem, you might have to implement onSaveInstanceState to put the url string into that savedInstanceState Bundle. But, you should be using putString and getString, probably, instead of put / get - Serializable. That way you avoid the cast.
In order to find where the variable is getting null, it's just a matter of logging and debugging appropriately.
Approaches to saving your data between orientation changes can be found at Handling Runtime Changes
So I decided to make it manually
I use
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_live_alternate_land);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_live_alternate);
}
with this setting on AndroidManifest.xml
android:configChanges="orientation"
This will make the height/width value different without destroying the activity
I need to pick contacts in my app and would like to exclude those which are stored in my SIM card. Is it possible with ACTION_PICK?
No, it's not possible
Unfortunately, it's not possible for now.
To proof it, let's dive into source code of ContanctsListActivity.
Here's an onCreate() method of the Activity. In it, ContactApp reads Intent(ACTION_PICK) we passing to it and handles it respectively:
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
mContactsPrefs = new ContactsPreferences(this);
mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture);
// Resolve the intent
final Intent intent = getIntent();
// Allow the title to be set to a custom String using an extra on the intent
String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY);
if (title != null) {
setTitle(title);
}
String action = intent.getAction();
String component = intent.getComponent().getClassName();
// When we get a FILTER_CONTACTS_ACTION, it represents search in the context
// of some other action. Let's retrieve the original action to provide proper
// context for the search queries.
if (UI.FILTER_CONTACTS_ACTION.equals(action)) {
mSearchMode = true;
mShowSearchSnippets = true;
Bundle extras = intent.getExtras();
if (extras != null) {
mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY);
String originalAction =
extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY);
if (originalAction != null) {
action = originalAction;
}
String originalComponent =
extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY);
if (originalComponent != null) {
component = originalComponent;
}
} else {
mInitialFilter = null;
}
}
Log.i(TAG, "Called with action: " + action);
mMode = MODE_UNKNOWN;
if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) {
.....
else if (Intent.ACTION_PICK.equals(action)) {
// XXX These should be showing the data from the URI given in
// the Intent.
final String type = intent.resolveType(this);
if (Contacts.CONTENT_TYPE.equals(type)) {
mMode = MODE_PICK_CONTACT;
} else if (People.CONTENT_TYPE.equals(type)) {
mMode = MODE_LEGACY_PICK_PERSON;
} else if (Phone.CONTENT_TYPE.equals(type)) {
mMode = MODE_PICK_PHONE;
} else if (Phones.CONTENT_TYPE.equals(type)) {
mMode = MODE_LEGACY_PICK_PHONE;
} else if (StructuredPostal.CONTENT_TYPE.equals(type)) {
mMode = MODE_PICK_POSTAL;
} else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) {
mMode = MODE_LEGACY_PICK_POSTAL;
}
....
// VERY LONG IF WITH DIFFERENT MODE-SELECTION
....
}
.....
if (mMode == MODE_JOIN_CONTACT) {
setContentView(R.layout.contacts_list_content_join);
} else if (mSearchMode) {
setContentView(R.layout.contacts_search_content);
} else if (mSearchResultsMode) {
setContentView(R.layout.contacts_list_search_results);
} else {
setContentView(R.layout.contacts_list_content);
}
setupListView();
...
}
It's very long method (and I also suggest to check setupListView() method), but pretty straightforward. And, as you can see, there's no parameter you can pass to specify source of contacts you want to pick from. Only thing you can configure here is the particular mMode ContactsApp to use (MODE_PICK_CONTACT, MODE_PICK_PHONE, etc.) - but unfortunately number of possible modes is very limited by 6 and non of them suits you.
(If anyone needs to pass mMode to ContanctsListActivity - use intent's setType() method, for example: intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);)
Workaround
As a workaround - as tiny sunlight's suggested in comments - render non-SIM contacts within the app and pick the one you needed from there.
How to get all android contacts but without those which are on SIM - this link looks like most promising one explaining how to query cursor with all contacts, apart from SIM ones.
I hope, it helps
Iam building Android application that checks the format of the received message
if it starts with $A its starts Activity A and send the content of the message to Activity A
if it starts with $B it starts Activity B and send the content of the message to Activity B
Please Any help
You can do it like this
if(messages.getMessageBody().contains("$A")) {
//Write your code here
}
else if(messages.getMessageBody().contains("$B")) {
//Write your code here
}
And to pass data to the next activity,do it like this,,
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
i.putExtra("STRING_I_NEED", strName);
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I want to implement a search in my Android application.
In this page, first I am displaying a user list and then performing a search on the user list. Both are in the same activity. In the following manner, I am getting intent and some values from the previous page. When I display the user list, all the values are coming. But while performing search, spaceId gets lost and becomes null. I need this value.
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
What should I do to get this value?
Edit:
String spaceId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
getMatchingstrings()
ArrayList<Ticket> getMatchingStrings(ArrayList<Ticket> list, String regex1) {
ArrayList <Ticket> listClone = new ArrayList<Ticket>();
for (Ticket string : list) {
if(string.getAssignedTo().equals(regex1)){
listClone.add(string);
}
}
return listClone;
}
Try it
getIntent().getExtras().getString("spaceId");
You said your activity is recreating. So you are not getting the value of spaceID after recreation. Then do this thing as below.
public String PREFS_NAME = "Shared_Pref";
Bundle receiveBundle = this.getIntent().getExtras();
String spaceId_value = receiveBundle.getString("spaceId");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(spaceId_value == null) {
spaceId_value = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId_value);
}
I hope this will help you out.
edit :
I am editing your code.
Which part i have edited, i have mentioned that part as edited. Carefully see what i have changed and do that thing in your code. Then let me know.
String spaceId;
public String PREFS_NAME = "Shared_Pref"; //edited part
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//editing start
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Bundle receiveBundle = this.getIntent().getExtras();
if(receiveBundle != null) {
spaceId = receiveBundle.getString("spaceId");
if(spaceId == null) {
spaceId = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId);
}
}
//editing end
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
When you are firstly loading your list in activity,you have to save that spaceId in some SharedPreference variable for further use.And while reloading activity with search result,you can find that Id from SharedPreference variable previously saved.
Be sure,you overwrite that variable as and when you firstly load list in your activity to meet your needs cleanly.
Also you have to get spaceId from intent like:
int spaceId=0;
if(getIntent().hasExtra())
spaceId=getIntent().getStringExtra("spaceId");
Doing this wont give you excpetion when you reload the same activity with no extras to your intent.
Or,you will have to pass this spaceId along with intent you are using to reload the same activity for showing search result.
Hope,you get the point!
If u relaunching the same activity while performing search,u will lost that value. If u r doing so,while relaunching also pass that spaceId to the relaunching activity also using intent.putextra() method
as in your question and comments i guess you are getting problem if your activity is recreated
add following code in manifest file under your activity tag
android:configChanges="keyboardHidden|orientation"
your activity will not be created again
and then use the value of spaceID where you need
I have a Tab Activity and with in Tab, im using Activity Group. and using LocalActivityManger,
im trying to destroy an Activty using the following function call provided in LocalActivityManger class
manager.destroyActivity(mIdList.get(index), true);
in the code. but later i found that there is a bug in Android impl for this
The exact source of the problem is in the following chunk of code in LocalActivityManager.java:
public Window destroyActivity(String id, boolean finish) {
LocalActivityRecord r = mActivities.get(id);
Window win = null;
if (r != null) {
win = performDestroy(r, finish);
if (finish) {
mActivities.remove(r);
}
}
return win;
}
The variable mActivities is the hashmap containing the activity records and it uses the id passed into startActivity() as the key. In this method, the object passed in for the key is a LocalActivityRecord instead of the id string. This results in the hashmap not finding the entry and thus not removing it.
More info refer this link. http://code.google.com/p/android/issues/detail?id=879More
and i found a work around for this issue and im using following function to fix the problem.
public boolean destroy(String id) {
if(manager != null){
manager.destroyActivity(id, false);
try {
final Field mActivitiesField = LocalActivityManager.class.getDeclaredField("mActivities");
if(mActivitiesField != null){
mActivitiesField.setAccessible(true);
#SuppressWarnings("unchecked")
final Map<String, Object> mActivities = (Map<String, Object>)mActivitiesField.get(manager);
if(mActivities != null){
mActivities.remove(id);
}
final Field mActivityArrayField = LocalActivityManager.class.getDeclaredField("mActivityArray");
if(mActivityArrayField != null){
mActivityArrayField.setAccessible(true);
#SuppressWarnings("unchecked")
final ArrayList<Object> mActivityArray = (ArrayList<Object>)mActivityArrayField.get(manager);
if(mActivityArray != null){
for(Object record : mActivityArray){
final Field idField = record.getClass().getDeclaredField("id");
if(idField != null){
idField.setAccessible(true);
final String _id = (String)idField.get(record);
if(id.equals(_id)){
mActivityArray.remove(record);
break;
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
return false;
}
now the problem is, this fix is working fine in Android API versions 2.1,2.2 and 2.3 but i tested in 3.0 . but it is failing there. no exceptions.
I want to know in which API version this bug has been fixed.
And also what fix can i make for this so that it will work fine in all the API versions after 2.1 .
Thank u