What is the prob with using Bundle extra to string? - java

Here is my code.
In the MainActivity.java, I called this method.
public void doViewRecord(View v){
startActivity(new Intent(this, ActivityView.class));
}
And in the SecondActivity (ActivityView.java).
[This is where I get my error]
tv_id = findViewById(R.id.tvId);
tv_name = findViewById(R.id.tvName);
tv_course = findViewById(R.id.tvCourse);
try{
extra = getIntent().getExtras();
id = extra.getString("id");
tv_id.setText(id);
}catch (Exception e){
e.printStackTrace();
displayError(e.getMessage());
}
The error I get is this.
I already tried the intent then bundle, but still it gives me an error.

You have to put the string early on the intent
public void doViewRecord(View v){
Intent intent = new Intent(this, ActivityView.class);
intent.putExtra("id", "your-id");
startActivity(intent);
}

Related

Consider adding a `<query>` declaration to your manifest when calling this \method;

I am getting this warning on resolveActivity line while using implicit intents and I am unable to open any website because of that.
btnWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String v = et.getText().toString();
Uri uri = Uri.parse(v);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
if (intent.resolveActivity(getPackageManager())!=null){
startActivity(intent);
}
}
});
Get rid of resolveActivity(). Just call startActivity(), but do so in a try/catch, so you can catch the ActivityNotFoundException if there is no Web browser available.

Losing intent extras between activities

I'm having an issue where I'm losing Extras between activites.
I'm sending a ChatObject from a MainActivity Recyclerview to a ChatActivity, and it works fine.
I then send the same ChatObject from the ChatActivity to a GroupSettingsActivity, which also works fine.
My issue is when I try to return from the GroupSettingsActivity to the ChatActivity from my topAppBar home button, I get a nullPointerException trying to getChatId from the ChatObject.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shotgunnot/com.example.shotgunnot.ChatActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.shotgunnot.Chat.ChatObject.getChatId()' on a null object reference
I've tried using onResume, and Navutils but I keep getting the same error, I think it's something in the life cycle im not getting.
Androids built in back nav button works as expected.
Here's my MainActivity recyclerview adapter
#Override
public void onBindViewHolder(#NonNull final ChatListViewHolder holder, final int position) {
ChatObject data = chatList.get(position);
holder.mTitle.setText(data.getChatId());
holder.mGroup.setText(data.getGroupId());
System.out.println("GroupPic" + data.getGroupPic());
Glide.with(context)
.load(data.getGroupPic())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.ic_group_24dp)
.apply(RequestOptions.circleCropTransform().circleCrop())
.into(holder.mGroupPic);
holder.mLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ChatActivity.class);
intent.putExtra("chatObject", chatList.get(holder.getBindingAdapterPosition()));
v.getContext().startActivity(intent);
}
});
}
This is the chatActivity
public class ChatActivity extends AppCompatActivity {
ChatObject mChatObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent(); >>
mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");
BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar);
bottomAppBar.replaceMenu(R.menu.group_menu);
bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(ChatActivity.this, GroupSettingsActivity.class);
intent.putExtra("chatObject", mChatObject);
startActivity(intent);
return true;
case android.R.id.home:
Intent home = new Intent(getApplicationContext(), MainPageActivity.class);
startActivity(home);
}
return false;
}
});
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");
}
}
And finally the GroupSetting Activity
public class GroupSettingsActivity extends AppCompatActivity {
ChatObject mChatObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_settings);
Intent intent = getIntent();
mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");
chatId = mChatObject.getChatId();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra("chatObject", mChatObject);
startActivity(intent);
//NavUtils.navigateUpFromSameTask(this);
finish();
default:
return super.onOptionsItemSelected(item);
}
}
Any help would be much appreciated.
You should check if the value that is arriving in the second activity is different from null before using it. Try to do something like this and put a breakpoint to debug what's coming up in your second activity:
1st Activity:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("user_id", "1234");
i.putExtra("user_name", "John Doe");
startActivity(i);
2nd Activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
Integer id= extras.getInt("user_id");
String username= extras.getString("user_name");
}
Try to add these flags before starting ChatActivity, to clear the stack and make sure you're creating a new ChatActivity rather then recreating an old one:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
I found a workaround using sharedPrefs based off this answer
How do you save/store objects in SharedPreferences on Android?
saving prefs
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(mChatObject);
prefsEditor.putString("mChatObject", json);
prefsEditor.commit();
}
And retrieving them in onCreate
mChatObject = (ChatObject) intent.getSerializableExtra("chatObject");
if(mChatObject != null){
chatId = mChatObject.getChatId();
groupId = mChatObject.getGroupId();
groupPic = mChatObject.getGroupPic();
}else{
Gson gson = new Gson();
String json = mPrefs.getString("mChatObject", "");
mChatObject = (ChatObject) gson.fromJson(json, ChatObject.class);
chatId = mChatObject.getChatId();
groupId = mChatObject.getGroupId();
groupPic = mChatObject.getGroupPic();
}
It feels like a bit of hack though, so if anyone has a better solution that'd be great.
Thanks

Android Studio: Activity only finishes when you call the finish() for second time

So, we're working with intents at school and I'm having trouble with the intents when I try to pass data from the "Activity2" to the "Activity1", when I do the setResult() and stuff. The problem is it won't go back to the first activity when I trigger the event the first time, but it will the second.
I've been working with Android studio only for about 12h so I really lack a lot of understanding.
Here is what I'm doing:
First I call this form the main activity.
public void CheckPassword(View view) {
password = PasswordManagement.getPassword(this);
TextView txtPassword = findViewById(R.id.txtPassword);
if (txtPassword.getText().toString().equals(password)) {
Intent intent;
intent = new Intent(this, WelcomeActivity.class);
intent.putExtra("password", password);
startActivityForResult(intent, 1);
startActivity(intent);
} else {
Intent intent;
intent = new Intent(this, RestrictedActivity.class);
startActivityForResult(intent, 1);
startActivity(intent);
}
}
Then, when I'm done from the second activity I run this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restricted);
lblRestrictedArea = findViewById(R.id.lblRestrictedArea);
lblRestrictedArea.setOnLongClickListener(
new OnLongClickListener() {
public boolean onLongClick(View view) {
intent = new Intent();
intent.putExtra(EXTRA_RESPONSE, true);
setResult(RESULT_OK, intent);
finish();
return false;
}
});
}
And back to the main activity I overwrote this to act according to the response:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if (data.getBooleanExtra(RestrictedActivity.EXTRA_RESPONSE,false)){
LinearLayoutPasswordActivity.setBackgroundColor(getResources().getColor(R.color.red));
}else{
LinearLayoutPasswordActivity.setBackgroundColor(getResources().getColor(R.color.white));
}
}
}
}
If anyone can help I would be very glad, meanwhile I'll try to solve it my own.
Thanks!
Your are calling startActivity twice. So there are two instance of the same Activity and then you have to finish twice.
Keep your startActivityForResult(...) and delete startActivity in CheckPassword(View view)
->
public void CheckPassword(View view) {
password = PasswordManagement.getPassword(this);
TextView txtPassword = findViewById(R.id.txtPassword);
if (txtPassword.getText().toString().equals(password)) {
Intent intent;
intent = new Intent(this, WelcomeActivity.class);
intent.putExtra("password", password);
startActivityForResult(intent, 1);
// startActivity(intent);
} else {
Intent intent;
intent = new Intent(this, RestrictedActivity.class);
startActivityForResult(intent, 1);
//startActivity(intent);
}
}
Plus, note that you are using the same requestCode (1) for two different activities. The requestCode is very important for onActivityResult method.

How to call one activity multiple times based on from which the activity has been called?

I have one activity which is common for all other activities. I want to call this activity and want to set some conditions based on from which activity it has been called. I thought of bundle for this. How can I call a condition based on bundle value? I have another activity in between. I am not calling the activity directly. So how can we pass data by using bundle?
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
GoSendData.instance.addressType = 0;
i.putExtra("type",1);
startActivity(i);
}
});
From this I am calling second activity.
In common activity I have a view I am calling the activity back from this. The activity from which it has been called , it should be called back from this view.
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle extras = intent.getExtras();
activityType = extras.getInt("type");
if(activityType==0) {
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
}
if(activityType == 1)
{
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
}
}
});
How to achieve this...?
How can I do this with shared preferences?
Change
Bundle extras = intent.getExtras();
to
Bundle extras = getIntent().getExtras();
Hope this helps :)
Check the below code
Activity_1. : This will send the data to the Common Activity.
Intent i = new Intent(Activity_1.this, CommonActivity.class);
i.putExtra("type",1);
startActivity(i);
Activity_2. : This will send the data to the Common Activity.
Intent i = new Intent(Activity_2.this, CommonActivity.class);
i.putExtra("type",2);
startActivity(i);
Then on your Common Activity write this code in the onCreate function.
int receivedValue = getIntent().getIntExtra("type", 0);
// here 0 is the default value when there is no data in the particular key.
now you can check the condition like this
if(receivedValue==1)
{
// do something here
}
if(receivedValue==2)
{
// do something here
}
This will definitely work for you. Try it..!!
Happy coding.
Activity1,
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
GoSendData.instance.addressType = 0;
i.putExtra("type",1);
startActivity(i);
}
});
Activity2,
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
GoSendData.instance.addressType = 0;
i.putExtra("type",2);
startActivity(i);
}
});
Common Activity
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = getIntent();
int type = i.getInt("type");
if(type==1) {
Intent intent = new Intent(ChooseFromMapActivity.this, Activity1.class);
startActivity(intent);
}
if(type == 2)
{
Intent intent = new Intent(ChooseFromMapActivity.this, Activity2.class);
startActivity(intent);
}
}
});

Intent putExtra persists

i'm having an issue with Intents and putExtra.
What i want to do is this :
In Activity A(it's not my MainActivity),when i click a button,it will close all my activities, send a string and launch my main activity.For testing purposes it will show a test dialog with my string.All good till now,works as i need it to.
The problem is that if i restart my MainActivity(and i need to do that,it's something like a shopping list,i need to start a new shopping list) the dialog with the putExtra string shows again.
Here are my code snippets :
In Activity A :
#Override
public void onClick(View v) {
Intent intent = new Intent(Gestionarez.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra( "paramName", str );
startActivity( intent );
// TODO Auto-generated method stub
dialog.dismiss();
dialog.cancel();
}
In my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadPref();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myParam = extras.getString("paramName");
ShowAlertMessage(this, "TEST", myParam + "");
} else {
}
}
And this is how i restart my MainActivity when i need to start a new shopping list :
Intent intent = getIntent();
finish();
startActivity(intent);
replace
Intent intent = getIntent();
finish();
startActivity(intent);
with
Intent intent = new Intent(this, ActivityB.class);
finish();
startActivity(intent);

Categories