I have an SQLite database with a table called author. I'm trying to pull the id and name values and pass them to the MainActivity where id will be stored as a variable and name will be displayed in a ListView.
The name side of things is working fine, but I'm unsure how to get the id value in my MainActivity. I've tried the get method of ArrayList on authorList with no luck.
Snippet from DatabaseHelper:
public List<Author> getAllAuthors() {
List<Author> authorList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT * FROM " + AUTHORS + " ORDER BY name_alphabetic";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
// create new author object
Author author = new Author();
// set ID and name of author object
author.setID(Integer.parseInt(cursor.getString(0)));
author.setName(cursor.getString(1));
// pass author object to authorList array
authorList.add(author);
} while (cursor.moveToNext());
}
// return author list
return authorList;
}
Author class:
public class Author {
int id;
String name;
String name_alphabetic;
#Override
public String toString() {
return name;
}
public Author() {
}
public Author(int id, String name, String name_alphabetic) {
this.id = id;
this.name = name;
this.name_alphabetic = name_alphabetic;
}
// getters
public int getID() {
return this.id;
}
public String getName() {
return this.name;
}
public String getNameAlphabetic() {
return this.name_alphabetic;
}
// setters
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setNameAlphabetic(String name_alphabetic) {
this.name_alphabetic = name_alphabetic;
}
}
Snippet from MainActivity:
// connect authorsListView variable to XML ListView
authorsListView = (ListView) findViewById(R.id.authors_list_view);
// create new database helper
DatabaseHelper db = new DatabaseHelper(this);
// create new list through getAllAuthors method (in DatabaseHelper class)
List authorList = db.getAllAuthors();
Log.i("authors", authorList.toString());
// create new Array Adapter
ArrayAdapter<Author> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, authorList);
// link ListView and Array Adapter
authorsListView.setAdapter(arrayAdapter);
// onItemClickListener waits for user to tap a ListView item
authorsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String author = authorsListView.getItemAtPosition(i).toString();
//Log.i("click", author);
// new Intent specifies which Activity to move from and to
Intent intent = new Intent(MainActivity.this, StoriesActivity.class);
// adds extra author variable to the Intent
intent.putExtra("author", author);
startActivity(intent);
}
});
EDIT:
I've tried return authorList.get(0) and return authorList.get(id) (although I'm aware id hasn't been set). The purpose of passing this variable is so later in MainActivity I can pass it to another Activity using an Intent extra, i.e. intent.putExtra("author", author_id).
In your code, I see this:
List authorList = db.getAllAuthors();
You should probably define this as List<Author> instead of just List, so that the get() method will return an Author instead of an Object. Once you've made that change, you should be able to access the author's id like this:
List<Author> authorList = db.getAllAuthors();
int id = authorList.get(0).getID(); // the id of the first author in the list
Note that general rules for List apply here, so if the list is empty then get(0) will throw an exception.
Update
You can use the AdapterView.getItemAtPosition(int) method to access the data object that has been clicked on inside your OnItemClickListener. Because you defined your ArrayAdapter as ArrayAdapter<Author>, you're guaranteed that getItemAtPosition() will return an Author instance, so you could write code like this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Author author = (Author) parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, StoriesActivity.class);
intent.putExtra("author_id", author.getID());
intent.putExtra("author_name", author.getName());
startActivity(intent);
}
As you start working with more complex objects, if you find that it gets annoying adding each individual field (like name and id) to the Intent one by one, you could look into implementing the Parcelable interface on your objects: https://developer.android.com/reference/android/os/Parcelable.html
Then you could just add the Author to the Intent directly, instead of adding its fields.
Related
I tried to initialize a custom array in Main Activity. I want to update/edit the element in array from another activity which contains the data and button click. My main activity is Main Activity and my second activity is Display. Can anyone help?
public class MainActivity extends AppCompatActivity {
public Pets[] arrayList=new Pets[]{
new Pets(R.drawable.dog,"Dog","Wolf","The dog is a domesticated descendant of the wolf. Also called the domestic dog"),
new Pets(R.drawable.bird,"Bird","Unknown!","Birds are a group of warm-blooded vertebrates constituting the class Aves characterised by feathers, toothless beaked jaws"),
new Pets(R.drawable.cat,"Cat","Tiger","The cat is a domestic species of small carnivorous mammal"),
};
public class Pets {
private int mPetImage;
private String mPetName;
private String mPetFam;
private String mDesc;
public Pets(int PetImage,String PetName,String PetFam,String Desc) {
this.mPetImage = PetImage;
this.mPetName = PetName;
this.mPetFam = PetFam;
this.mDesc = Desc;
}
public int getmPetImage() {
return mPetImage;
}
public Pets setmPetImage(int mPetImage) {
this.mPetImage = mPetImage;
return this;
}
public String getmPetName() {
return mPetName;
}
public Pets setmPetName(String mPetName) {
this.mPetName = mPetName;
return this;
}
public String getmPetFam() {
return mPetFam;
}
public Pets setmPetFam(String mPetFam) {
this.mPetFam = mPetFam;
return this;
}
public String getmDesc() {
return mDesc;
}
public Pets setmDesc(String mDesc) {
this.mDesc = mDesc;
return this;
}
}
In Display Activity after get data to be changed in the array. Shared Preferences can be used.
SharedPreferences share=getSharedPreferences("myArray",MODE_PRIVATE);
SharedPreferences.Editor editor=share.edit();
editor.putString("desc",textd);
editor.putInt("pos",pos);
editor.putInt("click",click);
editor.apply();
To make changes in the Activity where the array is present
SharedPreferences share=getSharedPreferences("myArray",MODE_PRIVATE);
pos=share.getInt("pos",0);
text=share.getString("desc","");
arrayList[pos]=text;
First of all do not create data inside the MainActivity. Activity is your view, if you separate your data source from view you can update it very easily.
How can I display another field from my object in vigiltime.setText? I want it to display the specific relating value of the time fields wihtin the object from the parishArrayList?
The parent.getItemAtPosition(position) already retrieves the specific object then how can I get it to parse relevant object details within the onItemSelected method?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parishArrayList = new ArrayList<>();
parishArrayList.add(new Parish(1, "Aghyaran", "Termonamongan, N.West Tyrone", "6.30pm", "10.00am"));
parishArrayList.add(new Parish(2, "Castlederg", "Castlederg, N.West Tyrone", "7pm", "11.00am"));
parishArrayList.add(new Parish(3, "Strabane", "Strabane, N.West Tyrone", "8pm", "12.00am"));
Spinner parishSpinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the parishArrayList and a default spinner layout
ArrayAdapter<Parish> parishAdapter = new ArrayAdapter<Parish>(getApplicationContext(), android.R.layout.simple_spinner_item, parishArrayList);
// Specify the layout to use when the list of choices appears
parishAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
parishSpinner.setAdapter(parishAdapter);
parishSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView vigiltime = (TextView) findViewById(R.id.vigiltime);
vigiltime.setText("Spinner selected : ");
vigiltime.setText(vigiltime.getText() + parent.getItemAtPosition(position).toString());
}
Parish.java
public class Parish {
private int parishIdNumber;
private String pName;
private String pAddress;
private String pVigilTimes;
private String pSundayTimes;
public Parish(int id, String name, String address, String vigilTimes, String sundayTimes) {
parishIdNumber = id;
pName = name;
pAddress = address;
pVigilTimes = vigilTimes;
pSundayTimes = sundayTimes;
}
public int getId() {
return parishIdNumber;
}
public void setId(int id) {
parishIdNumber = id;
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getAddress() {
return pAddress;
}
public void setAddress(String address) {
pAddress = address;
}
public String getVigilTimes() {
return pVigilTimes;
}
public String getsundayTimes() {
return pSundayTimes;
}
public int getParishIdNumber() {
return parishIdNumber;
}
public void setParishIdNumber(int parishIdNumber) {
this.parishIdNumber = parishIdNumber;
}
#Override
public String toString() {
return pName;
}
}
You don't need to use toString(). You could simply call the relevant functions or variables of your Parish class:
Parish item = parent.getItemAtPosition(position);
vigilTime.setText("Spinner selected : ");
vigilTime.append(item.getTime() + " "); //append has the same effect as what you're currently doing
vigilTime.append(item.getSomethingElse + " ");
//etc
If you want to simply use toString(), override it in your Parish class:
#Override
public String toString() {
return /* format the String you want returned here */
}
EDIT: to answer your actual question:
ViewAdapter#getItemAtPosition() returns an Object, not your specific class. You need to cast that call to Parish:
Parish item = (Parish) parent.getItemAtPosition(position);
Then you can call item.getVigilTimes();.
Override the toString method in the class that you want to alter the string representation.
#Override
public String toString() {
//TODO - Here.
}
You can access any private variable of an object through a public method of class shown below.
vigiltime.setText(vigiltime.getText() + ((Parish)parent.getItemAtPosition(position)).getVigilTimes());
You can also override toString() method to display VigilTimes and call parent.getItemAtPosition(position).toString().
#Override
public String toString() {
return pVigilTimes;
}
The toString() method is inherited from the Object Class that every other class in java inherits from. The foundational toString() returns this:
getClass().getName() + '#' + Integer.toHexString(hashCode())
The string class if you are creating a new string object like String
first_name = 'someFirstName'
actually creates an instances with the constructor,
String first_name = new String("someFristName")
and this class overrides the object toString() method once more.
The documentation at Oracle says of toString() in the String class,
This object (which is already a string!) is itself returned.
Every single class that is created or built is directly or indirectly inherited from the Object class which has the foundational toString() which one can override within the current class. It's as simple as...
#Override
public String toString(){
//to do logic here
}
Your overrided toString() is nothing more than your getName() method. Consider if it is necessary.
I have an class IntegrationWithDB in which i have to method getConnection()and selectFromDB().
In the selectFromDb() i have a result set , i want to get the result
set vales in another class method
Actually it did but it only shows the last value of dataBase table.
Note i have made getter and setter method in IntegrationWithDB class and use in selectFromDB() method.
public void selectFromDB() {
try {
if (this.conn == null) {
this.getConnection();
}
if (this.stmt == null) {
this.stmt = this.conn.createStatement();
}
int success = 0;
this.query = "select * from contacts order by node_id";
this.rs = this.stmt.executeQuery(query);
// something is wrong in the while loop
while (rs.next()) {
setId(rs.getInt("node_id")); // i made getter and setter for id, name, parent and for level
setNam(rs.getString("node_name"));
setParnt(rs.getString("node_parent"));
setLvl(rs.getInt("node_parent"));
}
if (success == 0) {
this.conn.rollback();
} else {
this.conn.commit();
}
} catch (Exception ex) {
ex.printStackTrace();
}
and in another class test i have method displayList() in this method i write the following code
public class test {
IntegrationWithDbClass qaz = new IntegrationWithDbClass();
public void displayList ( ) {
qaz.getConnection();
qaz.selectFromDB();
for(int i = 0; i< 5; i++){
System.out.println(" "+qaz.getId());
System.out.println(" "+qaz.getNam());
}
}
when i initilize the displayList() method in the main method , it shows the following result
5
red
how can i get all the five values?
First of all you have to create what is commonly referred to as an Entity class. This is the class that represents a single row in your database. This should ideally be separate from the code that interacts with the database connection.
So first step, create a class named Contact, and in it put the 4 fields you have, id, name, parent and level, with the respective getter methods. If you do not expect these to change by your program make them immutable, it is the good practice to ensure consistency. So something like:
public class Contact {
private final int id;
private final String name;
private final String parent;
private final String level;
public Contact(String id, String name, String parent, String level) {
this.id = id;
this.name = name;
this.parent = parent;
this.level = level;
}
public int getId() {
return id;
}
//... put the rest of the getter methods
}
Then in your IntegrationWithDB class (I would rename this to something more meaningful like ContactRepository) you can change that method you have to:
public List<Contact> getContacts() {
// ... your database connection and query code here
this.rs = this.stmt.executeQuery(query);
List<Contact> contacts = new LinkedList<Contact>();
while (rs.next()) {
int id = rs.getInt("node_id");
String name = rs.getString("node_name");
String parent = rs.getString("node_parent");
String level = setLvl(rs.getInt("level"));
contacts.add(new Contact(id, name, parent, level));
}
//... the rest of your database handling code, don't forget to close the connection
return contacts;
}
Then from displayList() you just have to call getContacts() which gives you a list of Contact objects to iterate through.
I assume that currently you're storing those properties in int/string variables. In every iteration of the loop you're overwriting the values. What you need to do is to store them in some collection like ArrayList and in each iteration add() to this collection.
I am trying to pass this ArrayList to another activity.
So far my efforts have been a failure.
I know that I am not understanding how to pass it correctly.
Here is the arrayList code that I have:
public static ArrayList<Movie> getMovieItems() {
if(mItems == null) {
mItems = new ArrayList<>();
Movie movie1 = new Movie();
movie1.setId(1);
movie1.setTitle("Title1");
movie1.setStudio("studio1");
movie1.setDescription("description1");
movie1.setCardImageUrl("http://3.bp.blogspot.com/-ZKjKucsPdzI/TudWC99CE_I/AAAAAAAAAD8/qvWdDtw5IW0/s1600/%2528393%2529.jpg");
//movie1.setVideoUrl("http://corochann.com/wp-content/uploads/2015/07/MVI_0949.mp4");
/* Google sample app's movie */
//movie1.setVideoUrl("http://www.youtube.com/embed/VopbGPJVkzM");
//movie1.setVideoUrl("http://live.gph.gov.sa/makkahlive/");
//movie1.setVideoUrl("http//livestreaming2.itworkscdn.net/squranlive/squran_7200p");
/// --- try this
//String url = "http://www.youtube.com/embed/VopbGPJVkzM";
//movie1.setVideoUrl("http://commondatastorage.googleapis.com/android-tv/Sample%20videos/Demo%20Slam/Google%20Demo%20Slam_%2020ft%20Search.mp4");
movie1.setVideoUrl("http//livestreaming2.itworkscdn.net/squranlive/squran_360p");
mItems.add(movie1);
Movie movie2 = new Movie();
movie2.setId(2);
movie2.setTitle("Title2");
movie2.setStudio("studio2");
movie2.setDescription("description2");
movie2.setCardImageUrl("http://www.questionsonislam.com/sites/default/files/mescid-i-nebevi.jpg");
//movie2.setVideoUrl("http://corochann.com/wp-content/uploads/2015/07/MVI_0962.mp4");
/* Google sample app's movie */
movie2.setVideoUrl("http://www.youtube.com/embed/4OoKpZWJASY");
mItems.add(movie2);
Movie movie3 = new Movie();
movie3.setId(3);
movie3.setTitle("Title3");
movie3.setStudio("studio3");
movie3.setDescription("description3");
movie3.setCardImageUrl("http://2.bp.blogspot.com/-ju9FXyjDFqI/TgY7uVabgxI/AAAAAAAAADw/-qSdxfyHosM/s1600/masjid+qiblatain+%25283%2529.gif");
//movie3.setVideoUrl("http://corochann.com/wp-content/uploads/2015/07/MVI_1112.mp4");
movie3.setVideoUrl("http://www.youtube.com/embed/4OoKpZWJASY");
mItems.add(movie3);
}
return mItems;
}
mItems is the ArrayList that I want to pass to another activity.
I tried this "template"
ArrayList<Movie> chanList= new ArrayList<>();
Then I realized that I don't have it correct.
Can someone help me out with some insight tutelage and help me understand how to do this correctly?
Thanks!
ironmantis7x
You'll have to make your Movie class implement Parcelable or Serializable in order to pass it through Activities using intents.
EDIT: An example of your class implementing Parcelable:
public class Movie implements Parcelable {
// I'm assuming that's what you have inside your class.
private int id;
private String title;
private String studio;
private String description;
private String imageURL;
private String videoURL;
public Movie() { }
// Getters and Setters here
//...
// Read the Parcel in the same order you wrote it.
public Movie(Parcel in) {
this.id = in.readInt();
this.title = in.readString();
this.studio = in.readString();
this.description = in.readString();
this.imageURL = in.readString();
this.videoURL = in.readString();
}
// Some dumb method, just leave it as it is.
#Override
public int describeContents() {
return 0;
}
// Write your data to Parcel, remember, you'll have to read in the same order you wrote here.
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(title);
out.writeString(studio);
out.writeString(description);
out.writeString(imageURL);
out.writeString(videoURL);
}
public static final Creator<Movie> CREATOR = new Creator() {
#Override
public Movie createFromParcel(Parcel parcel) {
return new Movie(parcel);
}
#Override
public Movie[] newArray(int i) {
return new Movie[i];
}
};
}
After you do that, you can check this question, this this tutorial and this one, for further information.
TL;DR: You'll have to use Intent#putParcelableArrayListExtra on the sender Activity, and Intent#getParcelableArrayListExtra on the second Activity.
First step is to make your model Parcelable, check here for instructions.
Next is to put your array list in the intent.
Intent intent = new Intent(this, YourNextActivity.class);
intent.putParcelableArrayListExtra("some string identifier", yourArrayList);
startActivity(intent)
Then in your next activity, get the array list using this:
ArrayList<Movie> chanList = getIntent().getParcelableExtra("some string identifier");
You need to make your movie class Parcelable. If your movie class is a POJO you can easily do it using http://www.parcelabler.com/
Then you can do directly put it in intent and pass it through :
Intent intent = new Intent(this, NextActivity.class);
intent.putParcelableArrayListExtra("key_string", movieArrayList);
startActivity(intent);
you can use Sharedprefrence to store list
SharedPreferences sharedPreferences =context.getSharedPreferences("MyPrefrence", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
String movie_data = gson.toJson(mItems);
editor.putString("MovieDatas", task_data);
editor.commit()
and for access
SharedPreferences sharedPreferences = context.getSharedPreferences("MyPrefrence", 0);
String json=sharedPreferences.getString("MovieDatas","");
Type type=new TypeToken<ArrayList<Movie>>(){}.getType();
mItems = new ArrayList<Movie>();
mItems=New Gson().fromjson(json,type);
For this solution what I did was:
I wrote a class file to pull the youTubeID of the stream.
I then made the YouTubeID of the stream a variable that I put into the ArrayList. Now I can chose the yoyTubeID of the stream as a variable and all works now!
I have started with parse to store the data of my class. I have followed parse guide and tutorials and tried to implement the code. Unfortunately, the objects of class are not getting saved in parse data browser. When I see the data in browser just one object id is shown not the columns of name, desc and qty of my item class. I have created class in dashboard also created columns respective to my data. Unable to get the solution as I am new to android and parse.
Here is my code
Item class
package com.example.owner.newstock;
import com.parse.ParseClassName;
import com.parse.ParseObject;
#ParseClassName("Item")
public class Item extends ParseObject {
public int id;
public String item_name;
public String item_desc;
public String item_qty;
public Item(){}
public Item(int id, String item_name, String item_desc, String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public Item(String item_name, String item_desc, String item_qty){
this.item_name = item_name;
this.item_desc=item_desc;
this.item_qty = item_qty;
}
public int getID(){
return id;
}
public void setID(int id){
this.id= id;
}
public String getItem_name(){
return getString(item_name);
}
public void setItem_name(String item_name)
{
put("item_name", item_name);
}
public String getItem_desc()
{
return getString(item_desc);
}
public void setItem_desc(String item_desc)
{
put("item_desc", item_desc);
}
public String getItem_qty()
{
return getString (item_qty);
}
public void setItem_qty(String item_qty){
put("item_qty", item_qty);
}
}
code of parse in main activity
ParseObject.registerSubclass(Item.class);
Parse.initialize(this, "Kw0dyUgLoqv24QdLE30mvFBVclEzLHRGtR2hQVHA", "5BWc3bAd60EgqU0sFIj31mMYYg7OIX9WKgC0a6oP");
ParseAnalytics.trackAppOpened(getIntent());
code to save the objects
Item i = new Item();
i.setItem_name(item_name);
i.setItem_desc(item_desc);
i.setItem_qty(item_qty);
i.saveInBackground();
Am I missing something?
Rather than creating an item class that extends ParseObject, set up a ParseObject variable, as follows:
ParseObject item = new ParseObject("Item");
Then put data in as follows:
item.put("quantity", yourQuantityVariable);
item.put("description", yourDescriptionVariable);
item.put("name", yourNameVariable);
To save:
item.saveInBackground();
To retrieve data, make use of querying and the getDataType() methods. Specified on https://parse.com/docs/android/guide#objects and https://parse.com/docs/android/guide#queries