Parceler error passing a Bundle from one Activity to another - java

I decided to use Parceler because it looks like a great library and it is very well supported by the author. I am using Parceler to wrap an object and pass it to another Activity in a Bundle. When I attempt to unwrap the object I am getting the error: android.os.Bundle cannot be cast to org.parceler.ParcelWrapper
My FirstActivity code:
User user = responseData.getUser();
Bundle bundle = new Bundle();
bundle.putParcelable("User", Parcels.wrap(user));
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("User", bundle);
startActivity(intent);
My SecondActivity code:
User user = Parcels.unwrap(this.getIntent().getParcelableExtra("User"));
I suspect this is just a newbie mistake. Any constructive assistance is appreciated!

You just need put wrapped object as argument for putExtra, not Bundle. Here is solution:
User user = responseData.getUser();
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("User", Parcels.wrap(user));
startActivity(intent);
On SecondActivity, in its onCreate() method do:
User user = (User) Parcels.unwrap(getIntent().getParcelableExtra("User"));

In kotlin you can do it as follows:
val user = responseData.getUser()
val bundle = Bundle()
bundle.putParcelable("User", Parcels.wrap(user))
val intent = Intent(this#FirstActivity, SecondActivity::class.java)
intent.putExtra("User", bundle)
startActivity(intent)
and in the second activity, where you are going to get the data you can do it as follows:
val user: User = Parcels.unwrap(data?.getParcelableExtra("User"))
NOTE: When using this library you need to use Parcels.wrap andParcels.unwrap
Although, I would recommend that if you use Kotlin you use #Parcelize annotation, since its implementation is very easy and your code is very clean.
If you want to implement #Parcelize you can do it as follows:
first, in your build.gradle file add the following:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
// ... other codes
// Add this code
androidExtensions {
experimental = true
}
}
second, create your data class User with the necessary properties:
#Parcelize
data class User(
val userId: Int,
val name: String,
// more properties
) : Parcelable

Related

How to call Kotlin class from Java class

I need to pass intent from java activity to Kotlin activity:
Java activity ProfileActivity.class:
Intent selectGameIntent = new Intent(ProfileActivity.this, kotlin.jvm.JvmClassMappingKt.getKotlinClass(CreateNewPollUserActivity.class).getClass());
startActivity(selectGameIntent);
And this is my Kotlin activity:
class CreateNewPollUserActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_new_poll_user)
val max = 45
val min = 10
val total = max - min}}
When i run it i have an error:
cannot find symbol
import com.myvote.Profile.ToolbarOption.CreateNewPollUserActivity;
any ideas how send intent from java activity to Kotlin activity?
add this in build.gradle project
buildscript {
ext.kotlin_version = '1.5.21'
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
And on top of build.gradle module file
apply plugin: 'kotlin-android'
This is the way to use call Kotlin class from Java class
Intent selectGameIntent = new Intent(ProfileActivity.this,
CreateNewPollUserActivity.class);
startActivity(selectGameIntent);
In your code, Probably the problem lays not in the Java-Kotlin relation, but in something else. Please check your code/project.
For this aim, you need to do several steps:
1-build.gradle project
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10'
2- build.gradle app
plugins {
id 'com.android.application'
id 'kotlin-android'
}
3- Introduction the class and fun:
kotlin kt:
class CountTime(val activity: Activity) {
fun seeNext(t: String, c: String, ico: Int, i: Int) {
java MainActivity
CountTime countTime = new CountTime(this);
countTime.seeNext(t,c,ico,i);
and if there is a companion object
.Companion.getInstance();

Unable to retrieve data of type Paint.Cap from a bundle

I have looked everywhere for this and I couldn't find any answer.
I am sending data over an intent like this.
MainActivity.java
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key",Paint.Cap.SQUARE);
startActivity(intent);
My issue is in retrieving it, I don't know which get method to use and I couldn't find any source online that tells me.
SecondActivity.java
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
if(extras.containsKey("key"))
{
Paint.Cap shape = //which method to use here?
}
}
If it's something so silly please tell me, I am still a beginner and tried my best to find it on my own.
Thanks.
The key is that Paint.Cap is an enum and so it implements the interface Serializable.
This means that you called the version of putExtra that takes a Serializable.
To get it out again you can do
Paint.Cap shape = (Paint.Cap) extras.getSerializable("key");

Passing HashMap to other activity throws class cast Exception

I want to pass a HashMap to other Activity my hash map is
HashMap<Integer,float[][]> table;
I use this code to send it to other activity
Intent i = new Intent(this, LineChartActivity.class);
i.putExtra("map",table);
startActivity(i);
when I receive it
Intent intent = getIntent();
table = (HashMap<Integer, float[][]>) intent.getSerializableExtra("map");
the VERY weird thing is that this code works very well in Android 5 and higher but in the previous versions Eg 4.4.4 ,4.1.1 it throw
java.lang.ClassCastException: java.lang.Object[] cannot be cast to
float[][]
Does someone face this problem before ? please I need any solution

Pass data from listview to field in other class

I have a listview in a class that should pass data to another class however it seems I am doing it wrong. Class A contains the listview and through an intent it sends the data back. Class B must receive the data and pass to a field. For that I use a bundle which contain the string and must pass it. However it seems I am doing something wrong. Any hints?
Class A.
public static final String Item = "shop";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item3 = (String)arrayAdapter.getItem(position).toString();
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
intent.putExtra(Item,item3);
startActivity(intent);
//Toast.makeText(getActivity().getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
}
});
Class B.
Bundle argsss = new Bundle();
argsss = getActivity().getIntent().getExtras();
if(argsss != null){
String shop = argsss.getString(ClassA.Item);
testButton.setText(shop);
}
Stacktrace :
Process: nl.boydroid.loyalty4g.app, PID: 27526
android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.boydroid.loyalty4g.app/nl.boydroid.loyalty4g.app.redeempoints.RedeemItemFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1636)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1430)
at android.app.Activity.startActivityForResult(Activity.java:3532)
at android.app.Activity.startActivityForResult(Activity.java:3493)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.Fragment.startActivity(Fragment.java:880)
at nl.boydroid.loyalty4g.app.redeempoints.SearchableShopList$1.onItemClick(SearchableShopList.java:90)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1524)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3531)
at android.widget.AbsListView$3.run(AbsListView.java:4898)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
This should work:
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
Problem with your code it that you're binding String into Intent object directly and not into Bundle. This is reason why your code is not working. Your Bundle is empty.
you have sent data through the intent not bundle so get the data in other activity as intent
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
note: Im not that knowledgeable in android so i dont know about Bundle class nor Intent class just want to share some thoughts.
Try this.
String shop = argsss.getString("shop");
the value of the Item which is your key (shop) because of this.
public static final String Item = "shop";
look at this ,
//you are putting or passing the value of item3 to Item which is your key named "shop"
intent.putExtra(Item,item3);
so you can only get the value using the key you set.
Update
try this
// first create a bundle for you to be able to use it later.
Bundle sampleBundle = new Bundle();
// then set the values you want. with the Item key.
sampleBundle.putString(Item, item3);
// then create the intent
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
// then put your bundle to intent.
intent.putExtras(sampleBundle);
startActivity(intent);
to get this try this.
Bundle bundle = this.getIntent().getExtras();
if(bundle !=null){
//Obtain Bundle
String strdata = bundle.getString("shop");
//do the process
}
note again: i havent compile it i dont have ide for android its just a hint.
or
if you want to use only intent to pass some value
use your code above then on the other class you can get it by :
Intent intent = getIntent();
//this is how you retrieve the data
String shop = intent.getStringExtra("shop");
Additional ref.
Intent
Fragment to Fragment Try this dude. :)
Fragment to Fragment . Look at the last answer it may help you finding some ways on how fragments work.
Another possible solution
Passing data fragment to fragment
Additional info.
I think you cant pass data from fragment to another fragment directly.
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Based on Fragment Documentation.
Question.
//note: not sure about the flow of the program. just want to ask.
ClassA extends Activity ClassB extends Activity
|| ||
ClassA call the FragmentClassA? FragmentClassB startActivity(ClassB)?
|| ||
FragmentClassA you want to pass data --> ? FragmentClassB
after that, you want to start the ClassB Activity class inside FragmentClassB?
Bundle add the object as serializable and send it to another fragment.

How can I open an Activity using the name as string via intent?

I want to use String variable containig the name of an activity, and i want to open the activity via in intent.
For example:
next = "foo.class";
Intent baslat = new Intent(this,next);
"next" is my value. I think using variable is impossible because eclipse don't let me use two arguments.
How can I solve this problem?
Edit: I am trying to go to "foo.class"
Edit: I solve the problem, You are all so nice and pretty :D, kisses for all, thank you very much!
OK, use the method Class.forName()
String myClass = "foo.class";
Intent myIntent = new Intent(getApplicationContext(), Class.forName(myClass));
startActivity(myIntent );
There is a method Intent.putExtra(). You can use this method to add extra variables inside your intent object.
String next = "foo.class";
Intent baslat = new Intent();
baslat.putExtra("my_tag", next);
Intent.putExtra() is what you're looking for.
next = "foo.class";
Intent baslat = new Intent(/*intent action goes here*/);
basalt.putExtra(/*data name*/, next);
If foo.class is where you're headed, then use Intent(Context packageContext, Class cls):
Intent baslat = new Intent(this, foo.class);
startActivity(basalt);

Categories