How to get variables from an object? - java

I am creating image_details in a customlistadapter. During this adapter the variable Answer is set of each item. Through debugger I'm seeing that I have the data in the place where I need it, but I don't know how to access it:
Debugger image:
Here you can see I have 6 questions which each has the variable int Answer (open one is set to 0). I want to request the Answer of each item(All 6) when I press save:
SaveButton = ((Button) rootView.findViewById(R.id.Save));
SaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Object c = image_details.get(1);
}
});
What should I place in the onClick to retrieve this data?
This is my QuestionItem class:
public class QuestionItem {
private String Question;
private String Answer1;
private String Answer2;
private String Answer3;
private String Answer4;
private int Answer;
private String[] Answers;
public String getQuestion() {
return Question;
}
public void setQuestion(String Question) {
this.Question = Question;
}
public String Getanswer1() {
return Answer1;
}
public void setAnswer1(String Answer1) {
this.Answer1 = Answer1;
}
public String Getanswer2() {
return Answer2;
}
public void setAnswer2(String Answer2) {
this.Answer2 = Answer2;
}
public String Getanswer3() {
return Answer3;
}
public void setAnswer3(String Answer3) {
this.Answer3 = Answer3;
}
public String Getanswer4() {
return Answer4;
}
public void setAnswer4(String Answer4) {
this.Answer4 = Answer4;
}
public int GetAnswer() {
return Answer;
}
public void setAnswer(int Answer) {
this.Answer = Answer;
}
}

use instance variables. Heres an example
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

Related

How to change the TextView from an object?

How can I use this to change the profile of a Turtle using Radio buttons? So when user selects a radio button different text should be displayed in the TextView. How can I set these objects? Currently there is no output displaying when the radio button is clicked. So I would like to get the details of the turtle from the object and set it.
//Main Activity
public class MainActivity extends AppCompatActivity {
private RadioGroup group_turtle;
private ImageView image_turtle;
private TextView text_description;
//create an array to store the turtle's profile
ArrayList<Turtle> turtles = new ArrayList<>(4);
//OnCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Load GUI components
loadGUI();
processRadioButtons();
loadTurtles();
}
private void loadTurtles() {
Turtle t1 = new Turtle("Leo","Leo is the heart of the team.",
"Loyal, brave, and responsible, Leonardo is the team leader, but not by choice.",
5);
Turtle t2 = new Turtle("Mike","Mikey is the jokester.",
"Slice of pizza in hand and shouts of \"COWABUNGA!\"",
4);
Turtle t3 = new Turtle("Don","Donny is the thinker.",
"Every team needs a brain, and for the Turtles, that's Donny. He's smart and philosophical.",
5);
Turtle t4 = new Turtle("Raphael","Raphael is fearless.",
"Raphael has the confidence and charisma of a \"D\" personality",
4);
//add the t1-t4 to the turtle list
turtles.add(t1);
turtles.add(t2);
turtles.add(t3);
turtles.add(t4);
/*try to display the turtle details in the logcat
for (Turtle t:turtles) {
Log.d("TURTLE", t.toString());
}*/
}
private void changeTurtle(int index) {
int images[] = {
R.drawable.tmntleo,
R.drawable.tmntmike,
R.drawable.tmntdon,
R.drawable.tmntraph};
//change the turtle image using setImageresource
image_turtle.setImageResource(images[index]);
//change the turtle profile
//I'm trying to change the Turtle's text description in here which is the textview.
String t1 = text_description.getText().toString();
text_description.setText(t1);
}
private void processRadioButtons() {
//set the listener
group_turtle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int id) {
switch (id) {
case R.id.radio_leo:
MainActivity.this.changeTurtle(0);
break;
case R.id.radio_mike:
MainActivity.this.changeTurtle(1);
break;
case R.id.radio_don:
MainActivity.this.changeTurtle(2);
break;
case R.id.radio_raph:
MainActivity.this.changeTurtle(3);
break;
}
}
});
}
private void loadGUI() {
group_turtle = findViewById(R.id.radio_group);
image_turtle = findViewById(R.id.imageView);
text_description = findViewById(R.id.text_description);
}
}
package com.example.ninjaturtle;
// new Turtle class
public class Turtle {
private String name;
private String features;
private String description;
private int rating;
//constructor
/*public Turtle(String name, String features, String description, int rating) {
this.name = name;
this.features = features;
this.description = description;
this.rating = rating;
}*/
//setter & getter
/*public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFeatures() {
return features;
}
public void setFeatures(String features) {
this.features = features;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
//toString method
#Override
public String toString() {
return "Turtle{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}*/
}
Change String t1 = text_description.getText().toString();
to
String desc= turtles.get(index).getDescription();
or to print all data
String desc= turtles.get(index).toString();
in your changeTurtle() method

URL based Movie Streaming App , need help in passing variable strings from one class to another

I would like to call the value of the String streamingLink to
String path1 ="xxxxx"; on MoviePlayerActivity.class (mentioned below)
Instead of xxxx, I need it to be the movie URL
Also, each movie has different URL stored inside an Array of List in DataSources.class
public class Movie {
private String title;
private String description;
private int thumbnail;
private int coverPhoto;
private String imdb;
private String rt;
private String streamingLink;
//Cast Initializing
private int cast1;
private int cast2;
private int cast3;
private String actor1;
private String actor2;
private String actor3;
public Movie(String title, int thumbnail, int coverPhoto, String actor1, int cast1, String actor2, int cast2, String actor3, int cast3, String streamingLink, String imdb, String rt, String description) {
this.title = title;
this.thumbnail = thumbnail;
this.coverPhoto = coverPhoto;
this.description =description;
this.imdb = imdb;
this.rt = rt;
this.streamingLink = streamingLink;
// Cast
this.cast1 = cast1;
this.cast2 = cast2;
this.cast3 = cast3;
this.actor1 = actor1;
this.actor2 = actor2;
this.actor3 = actor3;
}
public int getCoverPhoto() {
return coverPhoto;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public int getThumbnail() {
return thumbnail;
}
public String getImdb() {
return imdb;
}
public String getRt() {
return rt;
}
//Cast get activity
public int getCast1() {
return cast1;
}
public int getCast2() {
return cast2;
}
public int getCast3() {
return cast3;
}
public String getActor1() {
return actor1;
}
public String getActor2() {
return actor2;
}
public String getActor3() {
return actor3;
}
public String getStreamingLink() {
return streamingLink;
}
public void setTitle(String title) {
this.title = title;
}
public void setCoverPhoto(int coverPhoto) {
this.coverPhoto = coverPhoto;
}
public void setDescription(String description) {
this.description = description;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
public void setImdb(String imdb) {
this.imdb = imdb;
}
public void setRt(String rt) {
this.rt = rt;
}
public void setStreamingLink(String streamingLink) {
this.streamingLink = streamingLink;
}
//Cast set activity
public void setCast1(int cast1) {
this.cast1 = cast1;
}
public void setActor1(String actor1) {
this.actor1 = actor1;
}
public void setCast2(int cast2) {
this.cast2 = cast2;
}
public void setActor2(String actor2) {
this.actor2 = actor2;
}
public void setCast3(int cast3) {
this.cast3 = cast3;
}
public void setActor3(String actor3) {
this.actor3 = actor3;
}
}
MoviePlayerActivity:
public class MoviePlayerActivity extends AppCompatActivity {
private PlayerView playerView;
FloatingActionButton play_fab;
private SimpleExoPlayer simpleExoPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setFullScreen();
setContentView( R.layout.activity_movie_player );
hideActionbar();
iniExoPlayer();
}
private void hideActionbar() {
getSupportActionBar().hide();
}
private void setFullScreen() {
requestWindowFeature( Window.FEATURE_NO_TITLE );
getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
}
private void iniExoPlayer() {
playerView=findViewById( R.id.movie_exo_player );
simpleExoPlayer = ExoPlayerFactory.newSimpleInstance( this );
playerView.setPlayer( simpleExoPlayer );
String path1 ="xxxxx";
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory( this,
Util.getUserAgent(this,"appname"));
MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory )
.createMediaSource( Uri.parse( path1) );
simpleExoPlayer.prepare( videoSource );
simpleExoPlayer.setPlayWhenReady( true );
}
#Override
protected void onDestroy() {
super.onDestroy();
simpleExoPlayer.release();
}
}
Here's how the array looks like
this is class DataSource
public static List getEnglishMovies(){
List<Movie> lstMovies = new ArrayList<>();
lstMovies.add( new Movie( "Avengers: Endgame" , R.drawable.avgendgame, R.drawable.avgendgamecp,"Chris Hemsworth",R.drawable.chrishemsworth,"Robert Downey Jr.",R.drawable.downeyjr,"Chris Hemswoth",R.drawable.chrishemsworth,"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4","8.4","NA","After the devastating events of Avengers: Infinity War (2018), the universe is in ruins. With the help of remaining allies, the Avengers assemble once more in order to reverse Thanos' actions and restore balance to the universe.") );
lstMovies.add( new Movie( "Extraction" ,R.drawable.extraction, R.drawable.extractioncp,"Chris Hemswoth",R.drawable.chrishemsworth,"Chris Hemswoth",R.drawable.chrishemsworth,"Chris Hemswoth",R.drawable.chrishemsworth,"http://168.61.51.210/movies/Extraction.mp4","6.8","68%","Tyler Rake, a fearless black market mercenary, embarks on the most deadly extraction of his career when he's enlisted to rescue the kidnapped son of an imprisoned international crime lord.") );
lstMovies.add( new Movie( "The Call Of The Wild" ,R.drawable.thecallofthewildjpg,R.drawable.thecallofthewildcp,"Chris Hemswoth",R.drawable.chrishemsworth,"Chris Hemswoth",R.drawable.chrishemsworth,"Chris Hemswoth",R.drawable.chrishemsworth,"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4","6.8","62%", "Adapted from the beloved literary classic, THE CALL OF THE WILD vividly brings to the screen the story of Buck, a big-hearted dog whose blissful domestic life is turned upside down when he is suddenly uprooted from his California home and transplanted to the exotic wilds of the Alaskan Yukon during the Gold Rush of the 1890s. As the newest rookie on a mail delivery dog sled team--and later its leader--Buck experiences the adventure of a lifetime, ultimately finding his true place in the world and becoming his own master.") );
lstMovies.add( new Movie( "Do Little" ,R.drawable.dolittle, R.drawable.dolittlecp,"Chris Hemswoth",R.drawable.chrishemsworth,"Chris Hemswoth",R.drawable.chrishemsworth,"Chris Hemswoth",R.drawable.chrishemsworth,"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4","5.6","NA","A physician who can talk to animals embarks on an adventure to find a legendary island with a young apprentice and a crew of strange pets.") );
return lstMovies;
}

I want to implent some question randomly but always a new one

I want to create a game with a qestion and the question is randomly but there is a lot of repetition of questions. I want that the question can appear only once. There is the code of all activity for my game
public class Activity extends AppCompatActivity {
private TextView mQuestionTextViewVe;
private QuestionBankVe mQuestionBankVe;
private QuestionVeriter mCurrentQuestionVe;
private Button mbackButton;
private ArrayList<String> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_veriter);
System.out.println("veriterActivity::onCreate()");
mQuestionBankVe = this.generateQuestions();
mQuestionTextViewVe = findViewById(R.id.activity_veriter_question_text);
mCurrentQuestionVe = mQuestionBankVe.getQuestion();
this.displayQuestion(mCurrentQuestionVe);
private void displayQuestion(final QuestionVeriter question) {
mQuestionTextViewVe.setText(question.getQuestion());
}
private QuestionBankVe generateQuestions() {
QuestionVeriter question1 = new QuestionVeriter("Question");
QuestionVeriter question2 = new QuestionVeriter("Question");
QuestionVeriter question3 = new QuestionVeriter("Question");
return new QuestionBankVe(Arrays.asList( question1,
question2
question3
));
}
}
public class QuestionBankVe {
private List<QuestionVeriter> mQuestionListVe;
private int mNextQuestionIndexVe;
public QuestionBankVe(List<QuestionVeriter> questionListVe) {
mQuestionListVe = questionListVe;
// Shuffle the question list
Collections.shuffle(mQuestionListVe);
mNextQuestionIndexVe = 0;
}
public QuestionVeriter getQuestion() {
// Ensure we loop over the questions
if (mNextQuestionIndexVe == mQuestionListVe.size()) {
mNextQuestionIndexVe = 0;
}
// Please note the post-incrementation
return mQuestionListVe.get(mNextQuestionIndexVe++);
}
}
public class QuestionVeriter {
private String mQuestionVe;
public QuestionVeriter(String question) {
this.setQuestion(question);
}
public String getQuestion() {
return mQuestionVe;
}
public void setQuestion(String question) {
mQuestionVe = question;
}
#Override
public String toString() {
return "Question{" +
"mQuestion='" + mQuestionVe + '\'' +
'}';
}
}

Errors when trying to save strings, ints and spinner values to room persistence database in Android Studio

I'm trying to create a database within my step counting program that is able to save a user's details: Name, Age, Gender, Average Stride Length, Weight and Height in Android Studio. However I keep encountering errors that I am unable to locate or solve. Apologies if it is a rookie mistake; I am not in possession of a great deal of experience for Android Studio or the Room Persistence Library. Here is the code in question:
UserDetails.java:
#Entity(tableName = "user details")
public class UserDetails extends AppCompatActivity {
#NonNull
//each value for the primary key will be assigned a unique,
// automatically generated UserID
#PrimaryKey (autoGenerate = true)
#ColumnInfo(name = "ID")
public int UserID;
#ColumnInfo(name = "Name")
public String UserName;
#ColumnInfo(name = "Age")
public int UserAge;
#ColumnInfo(name = "Gender")
public String UserGender;
#ColumnInfo(name = "Average Stride Length")
public int UserAveStride;
#ColumnInfo(name = "Weight")
public int UserWeight;
#ColumnInfo(name = "Height")
public int UserHeight;
public UserDetails() {
}
#Ignore
public UserDetails(String userName, int userAge, String userGender, int
userAveStride, int userWeight, int userHeight) {
UserName = userName;
UserAge = userAge;
UserGender = userGender;
UserAveStride = userAveStride;
UserWeight = userWeight;
UserHeight = userHeight;
}
public int getUserID() {
return UserID;
}
public void setUserID(int userID) {
UserID = userID;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public int getUserAge() {
return UserAge;
}
public void setUserAge(int userAge) {
UserAge = userAge;
}
public String getUserGender() {
return UserGender;
}
public void setUserGender(String userGender) {
UserGender = userGender;
}
public int getUserAveStride() {
return UserAveStride;
}
public void setUserAveStride(int userAveStride) {
UserAveStride = userAveStride;
}
public int getUserWeight() {
return UserWeight;
}
public void setUserWeight(int userWeight) {
UserWeight = userWeight;
}
public int getUserHeight() {
return UserHeight;
}
public void setUserHeight(int userHeight) {
UserHeight = userHeight;
}
#Override
public String toString(){
return new
StringBuilder(UserName).append("\n").append(UserAge).append("\n")
.append(UserGender).append("\n").append(UserAveStride).append("\n")
.append(UserWeight).append("\n").append(UserHeight).toString();
}
DbContent.java
public class DbContent extends AppCompatActivity {
private ListView lstUser;
private FloatingActionButton fab;
//array adapter
List<UserDetails> userList;
ArrayAdapter adapter;
//database
private CompositeDisposable compositeDisposable;
private UserRepository userRepository;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db_content);
//init
compositeDisposable = new CompositeDisposable();
//init view
lstUser = findViewById(R.id.lstUsers);
fab = findViewById(R.id.fab);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
userList);
registerForContextMenu(lstUser);
lstUser.setAdapter(adapter);
//creating database
Database database = Database.getmInstance(this);
userRepository =
UserRepository.getmInstance(UserDataSource.getmInstance(database.userDao()));
//load all data from database
loadData();
//getting values from user inputs
final EditText name = findViewById(R.id.nameInput);
final EditText age = findViewById(R.id.ageInput);
final Spinner gender = findViewById(R.id.genderDropDown);
final EditText aveStride = findViewById(R.id.strideInput);
final EditText weight = findViewById(R.id.weightInput);
final EditText height = findViewById(R.id.heightInput);
//converting to strings
final String nameStr = name.getText().toString();
final String ageStr = age.getText().toString();
final String genderStr = gender.getSelectedItem().toString();
final String aveStrideStr = aveStride.getText().toString();
final String weightStr = weight.getText().toString();
final String heightStr = height.getText().toString();
//converting string to int where needed
final int ageInt = Integer.parseInt(ageStr);
final int aveStrideInt = Integer.parseInt(aveStrideStr);
final int weightInt = Integer.parseInt(weightStr);
final int heightInt = Integer.parseInt(heightStr);
//Event
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Add new
Disposable disposable = (Disposable) io.reactivex
.Observable.create(new ObservableOnSubscribe<Object>() {
#Override
public void subscribe(ObservableEmitter<Object> e) throws
Exception {
UserDetails userDetails = new UserDetails(nameStr,
ageInt,
genderStr, aveStrideInt, weightInt, heightInt);
userRepository.insertUser(userDetails);
e.onComplete();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer() {
#Override
public void accept(Object o) throws Exception {
Toast.makeText(DbContent.this,
"Data added", Toast.LENGTH_SHORT).show();
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(DbContent.this,
"" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
//Refreshing data
}, new Action() {
#Override
public void run() throws Exception {
loadData();
}
}
);
}
});
}
private void loadData() {
//Using RXJava
Disposable disposable = userRepository.getAllDetails()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Consumer<List<UserDetails>>() {
#Override
public void accept(List<UserDetails> userDetails) throws Exception {
OnGetAllDetailsSuccess(userDetails);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(DbContent.this, ""+throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
compositeDisposable.add(disposable);
}
private void OnGetAllDetailsSuccess(List<UserDetails> userDetails) {
userList.clear();
userList.addAll(userDetails);
adapter.notifyDataSetChanged();
}
}
Database.java
#android.arch.persistence.room.Database(entities = {UserDetails.class},
version = DATABASE_VERSION)
public abstract class Database extends RoomDatabase {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME ="Database-Room";
public abstract UserDao userDao();
private static Database mInstance;
public static Database getmInstance(Context context)
{
if (mInstance == null){
mInstance = Room.databaseBuilder(context,Database.class,DATABASE_NAME)
.fallbackToDestructiveMigration()
.build();
}
return mInstance;
}
}
UserDataSource.java
public class UserDataSource implements IUserDataSource {
private UserDao userDao;
private static UserDataSource mInstance;
public UserDataSource(UserDao userDao) {
this.userDao = userDao;
}
public static UserDataSource getmInstance(UserDao userDao) {
if(mInstance == null){
mInstance = new UserDataSource(userDao);
}
return mInstance;
}
#Override
public Flowable<UserDetails> getUserById(int userId) {
return userDao.getUserById(userId);
}
#Override
public Flowable<List<UserDetails>> getAllDetails() {
return userDao.getAllDetails();
}
#Override
public void insertUser(UserDetails... userDetails) {
userDao.insertUser(userDetails);
}
#Override
public void updateUser(UserDetails... userDetails) {
userDao.updateUser(userDetails);
}
#Override
public void deleteUser(UserDetails userDetails) {
userDao.deleteUser(userDetails);
}
}
UserRepository.java
public class UserRepository implements IUserDataSource {
private IUserDataSource mLocalDataSource;
private static UserRepository mInstance;
public UserRepository(IUserDataSource mLocalDataSource) {
this.mLocalDataSource = mLocalDataSource;
}
public static UserRepository getmInstance(IUserDataSource mLocalDataSource) {
if(mInstance == null){
mInstance = new UserRepository(mLocalDataSource);
}
return mInstance;
}
#Override
public Flowable<UserDetails> getUserById(int userId) {
return mLocalDataSource.getUserById(userId);
}
#Override
public Flowable<List<UserDetails>> getAllDetails() {
return mLocalDataSource.getAllDetails();
}
#Override
public void insertUser(UserDetails... userDetails) {
mLocalDataSource.insertUser(userDetails);
}
#Override
public void updateUser(UserDetails... userDetails) {
mLocalDataSource.updateUser(userDetails);
}
#Override
public void deleteUser(UserDetails userDetails) {
mLocalDataSource.deleteUser(userDetails);
}
}
UserDao.java
#Dao
public interface UserDao {
#Query("SELECT * FROM `user details` WHERE id=:userId")
Flowable<UserDetails> getUserById(int userId);
#Query("SELECT * FROM `user details`")
Flowable<List<UserDetails>> getAllDetails();
#Insert
void insertUser(UserDetails... userDetails);
#Update
void updateUser(UserDetails... userDetails);
#Delete
void deleteUser(UserDetails userDetails);
}
IUserDataSource.java
public interface IUserDataSource {
Flowable<UserDetails> getUserById(int userId);
Flowable<List<UserDetails>> getAllDetails();
void insertUser(UserDetails... userDetails);
void updateUser(UserDetails... userDetails);
void deleteUser(UserDetails userDetails);
}
The errors are:
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
Cannot find getter for field.
Cannot find setter for field.
Cannot figure out how to read this field from a cursor.
Cannot find getter for field.
Cannot find setter for field.
I appreciate any help greatly as I have spent a number of hours trying to fix this and this project is one fifth of my grade; it is due in soon and I need to spend time finishing other features and testing it rather than spending hours trying to fix errors. Thank you.
I believe that the errors you are trying to describe are similar to :-
The cause of these would be that you have made your UserDetails a subclass of the AppCompatActivity class by encoding extends AppCompatActivity
Instead of :-
#Entity(tableName = "user details")
public class UserDetails extends AppCompatActivity { ..........
You should have :-
#Entity(tableName = "user details")
public class UserDetails { ........
Note the dots represent the rest of the code, they are not intended to be coded, they are for the sake of brevity.

How can I pass object from ArrayList to new Activity and then receive that? [duplicate]

This question already has answers here:
How to pass ArrayList<CustomeObject> from one activity to another? [duplicate]
(3 answers)
Closed 7 years ago.
I try pass an object to new activity but I have a problem. My ArrayList use another class in this way:
ArrayList<ListData> myList = new ArrayList<>();
All is great, I'm adding to mList a few objects and my listview work fine.
I try pass an object after click in this way:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
ListData listdata = myList.get(position);
ListData dataToSend = new ListData();
dataToSend.setStrefa(listdata.getStrefa());
dataToSend.setDzielnica(listdata.getDzielnica());
dataToSend.setAdres(listdata.getAdres());
dataToSend.setKryteria(listdata.getKryteria());
dataToSend.setTelefon(listdata.getTelefon());
dataToSend.setData(listdata.getData());
Intent intent = new Intent(Zlecenia.this, Zlecenie.class);
intent.putExtra("myData", dataToSend);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.no_animation);
}
});
Here is a problem because "bundle.putParcelableArrayList("listdata", listdata);" is marked on red. This forces on me using extends Parcelable in ListData Class but when I added this extends then my ArrayList is empty. What schould I do?
My ListData:
public class ListData implements Parcelable{
String Strefa;
String Adres;
String Kryteria;
String Telefon;
String Data;
String Dzielnica;
String Ilosc;
/* Zlecenia */
public String getStrefa() {
return Strefa;
}
public void setStrefa(String strefa) {
this.Strefa = strefa;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
this.Adres = adres;
}
public String getKryteria() {
return Kryteria;
}
public void setKryteria(String kryteria) {
this.Kryteria = kryteria;
}
public String getTelefon() {
return Telefon;
}
public void setTelefon(String telefon) {
this.Telefon = telefon;
}
public String getData() {
return Data;
}
public void setData(String data) {
this.Data = data;
}
/* Statystyki */
public String getDzielnica() {
return Dzielnica;
}
public void setDzielnica(String dzielnica) {
this.Dzielnica = dzielnica;
}
public String getIlosc() {
return Ilosc;
}
public void setIlosc(String ilosc) {
this.Ilosc = ilosc;
}
public ListData() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Strefa);
dest.writeString(Dzielnica);
dest.writeString(Adres);
dest.writeString(Kryteria);
dest.writeString(Telefon);
dest.writeString(Data);
}
private ListData(Parcel in) {
Strefa = in.readString();
Dzielnica = in.readString();
Adres = in.readString();
Kryteria = in.readString();
Telefon = in.readString();
Data = in.readString();
}
public static final Parcelable.Creator<ListData> CREATOR
= new Parcelable.Creator<ListData>() {
#Override
public ListData createFromParcel(Parcel in) {
return new ListData(in);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Try this in your class
public class ListData implements Serializable

Categories

Resources