Getting java.lang.NullPointerException while ArrayList from Sqlite [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm getting error below while on button click
java.lang.NullPointerException
at com.gor.hocam.MainActivity.getListitem(MainActivity.java:329)
at com.gor.hocam.MainActivity$2.onClick(MainActivity.java:222)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
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:5139)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)
My Button that i clicked is (MainActivity.java:222 is the first line below);
getListitem();
System.out.println(dersadilist.size());
String[] arrRecords = dersadilist.toArray(new String[dersadilist.size()]);
int arr[] = new int[derskodulist.size()];
for (int i = 0; i < derskodulist.size(); i++) {
arr[i] = Integer.parseInt(derskodulist.get(i));
}
new MaterialDialog.Builder(MainActivity.this)
.title("Son Çözdüğünüz Dersler:")
.items(arrRecords)
.itemsIds(arr)
.itemsCallback(new MaterialDialog.ListCallback() {
#Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
Toast.makeText(MainActivity.this, which + ": " + text + ", ID = " + view.getId(), Toast.LENGTH_SHORT).show();
}
}).show();
Here my getListitem ( which is = (MainActivity.java:329);
public void getListitem() {
List<Scoredata> score = db.getAllContacts();
for (Scoredata sc : score) {
dersidler = String.valueOf(sc.getId());
dersadlari = sc.getName();
topscore = sc.getScore();
derskodlari = sc.getKodu();
//sc.getScore();
dersidlist.add(dersidler);
dersadilist.add(dersadlari);
scorelist.add(topscore);
derskodulist.add(dersadlari);
}
}
Thats my Scoredata;
public class Scoredata {
int id;
String name, kodu, score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKodu() {
return kodu;
}
public void setKodu(String kodu) {
this.kodu = kodu;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public Scoredata(String name, String kodu, String score) {
super();
this.name = name;
this.kodu = kodu;
this.score = score;
}
public Scoredata() {
super();
// TODO Auto-generated constructor stub
}
}
And getAllContacts on my DbHighestScore;
public List<Scoredata> getAllContacts() {
List<Scoredata> scoreList = new ArrayList<Scoredata>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Scoredata score = new Scoredata();
score.setId(Integer.valueOf(cursor.getString(0)));
score.setName(cursor.getString(1));
score.setKodu(cursor.getString(2));
score.setScore(cursor.getString(3));
scoreList.add(score);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return scoreList;
}

Check if the db object is not null and the collection object score is not null before parsing through it
public void getListitem() {
if(db != null){
List<Scoredata> score = db.getAllContacts();
if(score!= null){
for (Scoredata sc : score) {
dersidler = String.valueOf(sc.getId());
dersadlari = sc.getName();
topscore = sc.getScore();
derskodlari = sc.getKodu();
//sc.getScore();
dersidlist.add(dersidler);
dersadilist.add(dersadlari);
scorelist.add(topscore);
derskodulist.add(dersadlari);
}
}
}
}

Related

What is the error which causes the app to stop when retrieving data from Firebase?

This is an app that uses the Firebase database.
I have added all the data in firebase and now I need to retrieve it and display using listview.
I tried to fetch and show the data in my app from firebase but the app is stopping every time.
Take a look at the screenshot
This is the Country model class
Country.java
public class Country {
private String name;
private String total;
private String newCases;
private String totalDeaths;
private String newDeaths;
private String totalRecovered;
private String activeCases;
private String seriousCases;
public Country() {
}
public Country(String name, String total, String newCases, String totalDeaths, String newDeaths, String totalRecovered, String activeCases, String seriousCases) {
this.name = name;
this.total = total;
this.newCases = newCases;
this.totalDeaths = totalDeaths;
this.newDeaths = newDeaths;
this.totalRecovered = totalRecovered;
this.activeCases = activeCases;
this.seriousCases = seriousCases;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getNewCases() {
return newCases;
}
public void setNewCases(String newCases) {
this.newCases = newCases;
}
public String getTotalDeaths() {
return totalDeaths;
}
public void setTotalDeaths(String totalDeaths) {
this.totalDeaths = totalDeaths;
}
public String getNewDeaths() {
return newDeaths;
}
public void setNewDeaths(String newDeaths) {
this.newDeaths = newDeaths;
}
public String getTotalRecovered() {
return totalRecovered;
}
public void setTotalRecovered(String totalRecovered) {
this.totalRecovered = totalRecovered;
}
public String getActiveCases() {
return activeCases;
}
public void setActiveCases(String activeCases) {
this.activeCases = activeCases;
}
public String getSeriousCases() {
return seriousCases;
}
public void setSeriousCases(String seriousCases) {
this.seriousCases = seriousCases;
}
}
This is the Activity class
Country_List.java
public class Country_List extends AppCompatActivity {
ListView listView;
FirebaseDatabase firebaseDatabase;
DatabaseReference reff;
ArrayList<String> countries;
ArrayAdapter<String> adapter;
Country country;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country__list);
listView = (ListView) findViewById(R.id.listView);
country = new Country();
firebaseDatabase = FirebaseDatabase.getInstance();
reff = firebaseDatabase.getReference().child("country");
countries = new ArrayList<>();
adapter = new ArrayAdapter<>(Country_List.this, R.layout.country_info, R.id.country_info_list, countries);
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
country = ds.getValue(Country.class);
countries.add("Country Name:" + country.getName().toString() + "\n" + "Total Cases:" + country.getTotal().toString() + "\n" + "New Cases:" + country.getNewCases().toString() + "\n" + "Total Deaths:" + country.getTotalDeaths().toString() + "\n" + "New Deaths:" + country.getNewCases().toString() + "Total Recovered:" + country.getTotalRecovered().toString() + "Active Cases:" + country.getActiveCases().toString() + "\n" + "Serious Cases:" + country.getSeriousCases().toString());
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
StackTrace
com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertString(com.google.firebase:firebase-database##19.2.1:425)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##19.2.1:216)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database##19.2.1:178)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database##19.2.1:47)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database##19.2.1:592)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database##19.2.1:562)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##19.2.1:432)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##19.2.1:231)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##19.2.1:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##19.2.1:203)
at com.example.covid_19explorer.Country_List$1.onDataChange(Country_List.java:40)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
To solve this, you please change all the properties in your Country class to be of type long, except the name, which should remain a String. Please also change all the setters and getters. Your class should look like this:
public class Country {
private String name;
private long total, newCases, totalDeaths, newDeaths, totalRecovered, activeCases, seriousCases;
public Country() {}
public Country(String name, long total, long newCases, long totalDeaths, long newDeaths, long totalRecovered, long activeCases, long seriousCases) {
this.name = name;
this.total = total;
this.newCases = newCases;
this.totalDeaths = totalDeaths;
this.newDeaths = newDeaths;
this.totalRecovered = totalRecovered;
this.activeCases = activeCases;
this.seriousCases = seriousCases;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public long getNewCases() {
return newCases;
}
public void setNewCases(long newCases) {
this.newCases = newCases;
}
public long getTotalDeaths() {
return totalDeaths;
}
public void setTotalDeaths(long totalDeaths) {
this.totalDeaths = totalDeaths;
}
public long getNewDeaths() {
return newDeaths;
}
public void setNewDeaths(long newDeaths) {
this.newDeaths = newDeaths;
}
public long getTotalRecovered() {
return totalRecovered;
}
public void setTotalRecovered(long totalRecovered) {
this.totalRecovered = totalRecovered;
}
public long getActiveCases() {
return activeCases;
}
public void setActiveCases(long activeCases) {
this.activeCases = activeCases;
}
public long getSeriousCases() {
return seriousCases;
}
public void setSeriousCases(long seriousCases) {
this.seriousCases = seriousCases;
}
}
There is one more thing that you need to do, which is to change the type for the newCases property in the database this time, to be of type long, as it is a String now. That plus sign (+) is not recommended to be added in the database, you should add it programmatically.

SQLite db isn't created

I have problem with sqlite database adapter in my project.I'm new to android development so I don't have much idea to how can handle this problem. I want to save user information in data base .Although no error while execution,database doesn't create? can any one help.
DatabaseAdapter :
public class DatabaseAdapter {
private final String TAG = "DatabaseAdapter";
private DatabaseOpenHelper openHelper;
public static final String TBL_PERSONS = "persons";
public static final String PERSON_ID = "_id";
public static final String PERSON_USERNAME = "_username";
public static final String PERSON_HEIGHT = "_height";
public static final String PERSON_WEIGHT = "_weight";
public static final String PERSON_AGE = "_age";
public static final String PERSON_GENDER = "_gender";
public static final String PERSON_PA = "_pa";
public static final String PERSON_BMI = "_bmivalue";
public static final String PERSON_INTERPRETATION = "_bmiInterpretation";
public static final String PERSON_IDEALWEIGHT = "_idealweight";
public static final String PERSON_DAILYCALORIES = "_dailycalories";
// ???????????
public DatabaseAdapter(Context context) {
openHelper = new DatabaseOpenHelper(context, "Persons.db", null, 1);
}
// ====================insert in
// database===========================================================
public Long insertPerson(Person person) {
SQLiteDatabase db = null;
Long id = -1L;
try {
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
db = openHelper.getWritableDatabase();
id = db.insert(TBL_PERSONS, null, values);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
if (db != null && db.isOpen())
db.close();
}
return id;
}
// ================delete from
// database=============================================================
public int deletePerson(long id) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
count = db.delete(TBL_PERSONS, PERSON_ID + "=?",
new String[] { String.valueOf(id) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===============update
// database===================================================================
public int updatePerson(Person person) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());
count = db.update(TBL_PERSONS, values, PERSON_ID + "=?",
new String[] { String.valueOf(person.getId()) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===================================================================DATABASEOPENHELPER
// CLASS=========================
class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String
.format("create table %s(%$ integer primary key,%s text,%s text,%s text,%s text,%s text,%s tetx,%s text,%s text,%s text,%s text)",
TBL_PERSONS, PERSON_ID, PERSON_USERNAME,
PERSON_HEIGHT, PERSON_WEIGHT, PERSON_AGE,
PERSON_GENDER, PERSON_PA, PERSON_BMI,
PERSON_INTERPRETATION, PERSON_IDEALWEIGHT,
PERSON_DAILYCALORIES);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
person.java (I pass the user data to person.java)
package Databasedata;
public class Person {
private Long id;
private String username;
private float height;
private int weight;
private int age;
private String gender;
private String pa;
private int bmivalue;
private String bmiInterpretation;
private double idealweight;
private double dailycalories;
public double getIdealweight() {
return idealweight;
}
public void setIdealweight(double idealweight) {
this.idealweight = idealweight;
}
public double getDailycalories() {
return dailycalories;
}
public void setDailycalories(double dailycalories) {
this.dailycalories = dailycalories;
}
public int getBmivalue() {
return bmivalue;
}
public void setBmivalue(int bmivalue) {
this.bmivalue = bmivalue;
}
public String getBmiInterpretation() {
return bmiInterpretation;
}
public void setBmiInterpretation(String bmiInterpretation) {
this.bmiInterpretation = bmiInterpretation;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPa() {
return pa;
}
public void setPa(String pa) {
this.pa = pa;
}
}
MAIN ACTIVITY
public class MainActivity extends Activity {
String gender;
RadioButton maleRadioButton;
RadioButton femaleRadioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maleRadioButton = (RadioButton) findViewById(R.id.maleselected);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleselected);
final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);
genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId) {
selectedId=genderselected.getCheckedRadioButtonId();
RadioButton genderchoosed = (RadioButton) findViewById(selectedId);
gender= genderchoosed.getText().toString();
}
});
Button saveinformation = (Button) findViewById(R.id.saveinformation);
saveinformation.setOnClickListener(new View.OnClickListener() {
EditText weighttext = (EditText) findViewById(R.id.weighttext);
EditText heighttext = (EditText) findViewById(R.id.heighttext);
EditText usernametext = (EditText) findViewById(R.id.usernametext);
EditText agetext = (EditText) findViewById(R.id.agetext);
Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity);
Button saveinformation = (Button) findViewById(R.id.saveinformation);
String pa = activitytext.getSelectedItem().toString();
#Override
public void onClick(View v) {
if(maleRadioButton.isChecked()) {
gender= maleRadioButton.getText().toString();
} else {
gender = femaleRadioButton.getText().toString();
}
int weight = (int) Float.parseFloat(weighttext.getText()
.toString());
float height = Float.parseFloat(heighttext.getText()
.toString());
String username = usernametext.getText().toString();
int age = (int) Float.parseFloat(agetext.getText().toString());
String pa = activitytext.getSelectedItem().toString();
// BMI
// ============================================================================================
int Bmivalue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(Bmivalue);
float idealweight = idealweight(weight, height, gender, pa, age);
double dailycalories=dailycalories(weight,height,gender,pa,age);
// insert in to
// db==================================================================================
Person person = new Person();
person.setUsername(username);
person.setHeight(height);
person.setWeight(weight);
person.setAge(age);
person.setGender(gender);
person.setPa(pa);
person.setBmivalue(Bmivalue);
person.setBmiInterpretation(bmiInterpretation);
person.setIdealweight(idealweight);
person.setDailycalories(dailycalories);
// ?????????????????????????????????????????/
Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter(
MainActivity.this);
dbAdapter.insertPerson(person);
Toast.makeText(getApplicationContext(),
Bmivalue + "and you are" + bmiInterpretation,
Toast.LENGTH_LONG).show();
}
});
}
}
One Problem I see is in your insertPerson() method. Don't include the "" in the values.put()
try replacing below code
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
with
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());

display data from SQLite database to custom listview

I am trying to display data from SQLite database to custom listview but it is not displaying. When I am using simple list view with single data then it's working but not working when I am trying to display on custom listview.
MainActivity.java
package com.example.addressbook;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE";
private ListView lv;
List<Listcollection> collectionlist;
DBHelper mydb;
private Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
mydb = new DBHelper(this);
// CustomListAdapter customListAdapter = new
// CustomListAdapter(MainActivity.this, );
lv.setAdapter(new ViewAdapter(mydb.listfromdb()));
// lv.setAdapter(ViewAdapter);
// adding it to the list view.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.Display.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
List<Listcollection> collectionlist;
public ViewAdapter(List<Listcollection> c) {
collectionlist = c;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return collectionlist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
}
Listcollection o = collectionlist.get(position);
if (o != null) {
TextView idText = (TextView) convertView
.findViewById(R.id.lvid);
TextView nameText = (TextView) convertView
.findViewById(R.id.lvname);
TextView dateText = (TextView) convertView
.findViewById(R.id.lvdate);
TextView phoneText = (TextView) convertView
.findViewById(R.id.lvphone);
if (idText != null) {
idText.setText(Integer.toString(o.getId()));
}
if (nameText != null) {
nameText.setText("Name : "
+ collectionlist.get(position).getName());
}
if (dateText != null) {
dateText.setText("Date: "
+ collectionlist.get(position).getDate());
}
if (phoneText != null) {
phoneText.setText("Phone: "
+ collectionlist.get(position).getPhone());
}
}
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.item1:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.Display.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String C_NAME = "name";
public static final String C_TYPE = "type";
public static final String C_ADDRESS = "address";
public static final String C_DATE = "date";
public static final String C_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table contacts "
+ "(id integer primary key, name text,phone text,type text, address text,date text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact(String name, String phone, String type,
String address, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("type", type);
contentValues.put("address", address);
contentValues.put("date", date);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from contacts where id=" + id + "",
null);
return res;
}
public int numberOfRows() {
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db,
CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact(Integer id, String name, String phone,
String type, String address, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("type", type);
contentValues.put("address", address);
contentValues.put("date", date);
db.update("contacts", contentValues, "id = ? ",
new String[] { Integer.toString(id) });
return true;
}
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<Listcollection> listfromdb() {
SQLiteDatabase db = this.getReadableDatabase();
Listcollection lcollection;
Listcollection list = new Listcollection();
ArrayList<Listcollection> results = new ArrayList<Listcollection>();
Cursor crs = db.rawQuery("select * from contacts", null);
crs.moveToFirst();
list.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
list.setName(crs.getString(crs.getColumnIndex(C_NAME)));
list.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
db.close();
return results;
}
}
enter code here
Listcollection.java
public class Listcollection {
// private variables
int id;
String name;
String type;
String address;
String date;
String phone;
// Empty constructor
public Listcollection(Parcel in) {
}
// constructor
public Listcollection(int id, String name, String type, String address,
String date, String phone) {
this.id = id;
this.name = name;
this.type = type;
this.address = address;
this.phone = phone;
this.date = date;
}
public Listcollection() {
// TODO Auto-generated constructor stub
}
// getting id
public int getId() {
return this.id;
}
// setting id
public void setId(int id) {
this.id = id;
}
// getting name
public String getName() {
return this.name;
}
// setting name
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "Complain [id=" + id + ", name=" + name + ", type=" + type
+ ", address=" + address + ", date=" + date + ", phone="
+ phone + ",";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Listcollection other = (Listcollection) obj;
if (id != other.id)
return false;
return true;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(getId());
parcel.writeString(getName());
parcel.writeString(getType());
parcel.writeString(getAddress());
parcel.writeString(getPhone());
parcel.writeString(getDate());
}
public static final Parcelable.Creator<Listcollection> CREATOR = new Parcelable.Creator<Listcollection>() {
public Listcollection createFromParcel(Parcel in) {
return new Listcollection(in);
}
public Listcollection[] newArray(int size) {
return new Listcollection[size];
}
};
}
You're not actually adding the database records to the results collection in listfromdb().
Should be something like:
public ArrayList<Listcollection> listfromdb() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Listcollection> results = new ArrayList<Listcollection>();
Cursor crs = db.rawQuery("select * from contacts", null);
while (crs.moveToNext()) {
Listcollection item = new Listcollection();
item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
item.setName(crs.getString(crs.getColumnIndex(C_NAME)));
item.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
results.add(item);
}
db.close();
return results;
}

Android saving data from edit texts fields to database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to SQLite. I have an activity in which I have different fields like Name,Email,Date of Birth etc. When user fill the information and clicks the save button I want it to get saved to the database. But I am stuck in mid way and don't know what to do.How to save the data from Edit Text Views to the database on Save Button click.Please help me.
I am sharing my code.
DataBaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "NewUserDb.db";
private static final String TABLE_INFO = "info";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_GOAL = "userGOAL";
public static final String COLUMN_NAME = "userName";
public static final String COLUMN_EMAIL = "userEmail";
public static final String COLUMN_DOB = "userDOB";
public static final String COLUMN_HEIGHT = "userHeight";
public static final String COLUMN_WEIGHT = "userWeight";
public static final String COLUMN_GENGER = "userGender";;
public static final String COLUMN_ZIP = "userZIP";
private static final String[] COLUMNS = { COLUMN_ID, COLUMN_GOAL,
COLUMN_NAME, COLUMN_EMAIL, COLUMN_DOB, COLUMN_HEIGHT,
COLUMN_WEIGHT, COLUMN_GENGER, COLUMN_ZIP };
// http://www.techotopia.com/index.php/An_Android_SQLite_Database_Tutorial
/*
* public DatabaseHelper(Context context, String name, CursorFactory
* factory, int version) { super(context, name, factory, version); // TODO
* Auto-generated constructor stub
*
* }
*/
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_USER_TABLE = "CREATE TABLE User ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "gaol TEXT, "
+ "name TEXT )";
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS users");
// create fresh books table
this.onCreate(db);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void addUser(NewUserDb newuserdb) {
// for logging
// Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(COLUMN_GOAL, newuserdb.getGoal()); // get title
values.put(COLUMN_NAME, newuserdb.getName()); // get author
values.put(COLUMN_EMAIL, newuserdb.getEmail());
values.put(COLUMN_DOB, newuserdb.getDob());
values.put(COLUMN_HEIGHT, newuserdb.getHeight());
values.put(COLUMN_WEIGHT, newuserdb.getWeight());
values.put(COLUMN_GENGER, newuserdb.getGender());
values.put(COLUMN_ZIP, newuserdb.getZip());
// 3. insert
db.insert(TABLE_INFO, // table
null, // nullColumnHack
values); // key/value -> keys = column names/ values = column
// values
// 4. close
db.close();
}
public NewUserDb getNewUserDb(int id) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor = db.query(TABLE_INFO, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
NewUserDb newUserdb = new NewUserDb();
newUserdb.setId(Integer.parseInt(cursor.getString(0)));
newUserdb.setGoal(cursor.getString(1));
newUserdb.setName(cursor.getString(2));
newUserdb.setEmail(cursor.getString(3));
newUserdb.setDob(cursor.getString(4));
newUserdb.setHeight(cursor.getString(5));
newUserdb.setWeight(cursor.getString(6));
newUserdb.setGender(cursor.getString(7));
newUserdb.setZip(cursor.getString(8));
// Log.d("getBook("+id+")", book.toString());
// 5. return book
return newUserdb;
}
// Deleting single book
public void deleteUser(NewUserDb newuserDB) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_INFO, COLUMN_ID + " = ?",
new String[] { String.valueOf(newuserDB.getId()) });
// 3. close
db.close();
Log.d("deleteBook", newuserDB.toString());
}
}
NewUserDb.java
public class NewUserDb {
private int id;
private String goal;
private String name;
private String email;
private String dob;
private String height;
private String weight;
private String gender;
private String zip;
public NewUserDb() {
}
public NewUserDb(int id, String goal, String name, String email,
String dob, String height, String weight, String gender, String zip) {
super();
this.id = id;
this.goal = goal;
this.name = name;
this.email = email;
this.dob = dob;
this.height = height;
this.weight = weight;
this.gender = gender;
this.zip = zip;
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoal() {
return goal;
}
public void setGoal(String goal) {
this.goal = goal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "User [id=" + id + ", goal=" + goal + ", name=" + name
+ ", email=" + email + ", dob=" + dob + ", height=" + height
+ ", weight=" + weight + ", gender=" + gender + ", zip =" + zip
+ "]";
}
}
AccountActivity.java
public class AccountActivity extends Activity {
private EditText et_weight, et_height, et_email, et_dob, et_name;
private Button btn_uploadPhoto, btn_shootPhoto, btn_del, btn_save;
private Switch genderSwitch;
private DatePickerDialog datePickerDialog;
private String year;
private String month;
private String day;
DatabaseHelper dbh = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accounts);
btn_shootPhoto = (Button) findViewById(R.id.button1);
btn_uploadPhoto = (Button) findViewById(R.id.button2);
btn_del = (Button) findViewById(R.id.btn_del);
btn_save = (Button) findViewById(R.id.btn_save);
et_dob = (EditText) findViewById(R.id.et_dob);
genderSwitch = (Switch) findViewById(R.id.mySwitch);
et_name = (EditText) findViewById(R.id.et_name);
et_email = (EditText) findViewById(R.id.et_email);
et_height = (EditText) findViewById(R.id.et_height);
et_height.setInputType(InputType.TYPE_CLASS_NUMBER);
et_weight = (EditText) findViewById(R.id.et_weight);
et_weight.setInputType(InputType.TYPE_CLASS_NUMBER);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//what to do here ??
}
});
}
try .getText() on your EditText
like yourEditText.getText(); and set it into your NewUserDb and pass the NewUserDb object into addUser method of your DatabaseHelper class
First you declare database create table query string in your DatabaseHelper class like this:
private static final String DATABASE_CREATE_USER = "create table UserInfo("
+ "_id VARCHAR(20)," + "userGOAL VARCHAR(20),"
+ "userName VARCHAR(20)," + "userEmail VARCHAR(20),"
+ "userDOB VARCHAR(20)," + "userHeight VARCHAR(10),"
+ "userWeight VARCHAR(10)," + "userGender VARCHAR(10),"
+ "userZIP VARCHAR(10) "+ ")";
Then write inside onCreate method of DatabaseHelper
db.execSQL(DATABASE_CREATE_USER);
Then declare object of SqliteDatabase and DatabseHelper in your AcountActivity like this:
DatabaseHelper dbHelper;
SQLiteDatabase db;
Afer this write following code inside your button onClick method:
dbHelper= new DatabaseHelper(ActountActivity.this);
db = dbHelper.getWritableDatabase();
ContentValues insertValues = new ContentValues();
insertValues.put("_id", "User_Id");
insertValues.put("userGOAL", "User_Goal");
insertValues.put("userName", "User_Name");
insertValues.put("userEmail", "User_Email");
insertValues.put("userDOB", "User_DOB");
insertValues.put("userHeight", "User_Height");
insertValues.put("userWeight", "User_Weight");
insertValues.put("userGender", "User_Gender");
insertValues.put("userZIP", "User_Zip");
db.insert("UserInfo", null, insertValues);
db.close();
May this help you.

Passing ArrayList Object between activities using parcelable

Ill first start this off saying i have seen all the other posts that deal with this and have tried all of them.
Im trying to do the same thing asked in the other posts, which is to pass the values of a ArrayList from one activity to another using Intent.
I feel I have implemented my class(es) correctly. The main class (Route_Class) i am using is below.
```
public class Route_Class implements Parcelable {
private double latitude = 0;
private double longitude = 0;
private double startingLat = 0;
private double startingLong = 0;
private String name = null;
private String routeName = null;
private String GeoPoints = null;
private String layout_width= null;
private String layout_height = null;
private String orientation = null;
private String xmlns = null;
private String id = null;
private boolean clickable = false;
private boolean enabled = false;
private String layout_width2 = null;
private String layout_height2 = null;
private String apiKey = null;
private ArrayList<GeoPoints_Class> geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
public Route_Class() {
System.out.println("crash 110");
}
public Route_Class(String name, double latitude, double longitude, double startingLat, double startingLong, String routeName, String GeoPoints, String layout_width, String layout_height, String orientation, String xmlns, String id, boolean clickable, boolean enabled, String layout_width2, String layout_height2, String apiKey, ArrayList<GeoPoints_Class> geoPoints_arraylist) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.layout_width2 = layout_width2;
this.latitude = latitude;
this.longitude = longitude;
this.startingLat = startingLat;
this.startingLong = startingLong;
this.routeName = routeName;
this.GeoPoints = GeoPoints;
this.layout_width = layout_width;
this.layout_height = layout_height;
this.orientation = orientation;
this.xmlns = xmlns;
this.id = id;
this.clickable = clickable;
this.enabled = enabled;
this.layout_height2 = layout_height2;
this.apiKey = apiKey;
this.geoPoints_arraylist = geoPoints_arraylist;
System.out.println("crash 16");
}
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
System.out.println("crash 17");
return this.hashCode();
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel dest, int flags) {
System.out.println("crash 18");
dest.writeDouble(latitude);
dest.writeDouble(longitude);
dest.writeDouble(startingLat);
dest.writeDouble(startingLong);
dest.writeString(name);
dest.writeString(routeName);
dest.writeString(GeoPoints);
dest.writeString(layout_width);
dest.writeString(layout_height);
dest.writeString(orientation);
dest.writeString(xmlns);
dest.writeString(id);
dest.writeInt(clickable ? 0 : 1 );
dest.writeInt(enabled ? 0 : 1 );
dest.writeString(layout_width2);
dest.writeString(layout_height2);
dest.writeString(apiKey);
dest.writeTypedList(geoPoints_arraylist);
// dest.writeList((List<GeoPoints_Class>)geoPoints_arraylist);
// dest.writeParcelable((Parcelable) geoPoints_arraylist, 0);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Route_Class> CREATOR = new Parcelable.Creator<Route_Class>() {
public Route_Class createFromParcel(Parcel in) {
System.out.println("crash 20");
return new Route_Class(in);
}
public Route_Class[] newArray(int size) {
System.out.println("crash 21");
return new Route_Class[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Route_Class(Parcel in) {
layout_width2 = in.readString();
latitude = in.readDouble();
longitude = in.readDouble();
startingLat = in.readDouble();
startingLong = in.readDouble();
name = in.readString();
routeName = in.readString();
GeoPoints = in.readString();
layout_width = in.readString();
layout_height = in.readString();
orientation = in.readString();
xmlns = in.readString();
id = in.readString();
clickable = in.readInt() == 0;
enabled = in.readInt() == 0;
layout_height2 = in.readString();
apiKey = in.readString();
System.out.println("crash 5");
//geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
if (geoPoints_arraylist == null) {
geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
}
try {
in.readTypedList(geoPoints_arraylist, GeoPoints_Class.CREATOR);
} catch (Exception e) {
System.out.println("Error " + e);
}
// in.readList(geoPoints_arraylist, com.breckbus.app.GeoPoints_Class.class.getClassLoader());
System.out.println("crash 6");
// geoPoints_arraylist = (ArrayList<GeoPoints_Class>)in.readParcelable(com.breckbus.app.Route_Class.GeoPoints_Class. class.getClassLoader());
}
public double getlatitude() {
return latitude;
}
public void setlatitude(double latitude) {
this.latitude = latitude;
}
public double getlongitude() {
return longitude;
}
public void setlongitude(double longitude) {
this.longitude = longitude;
}
public double getstartingLat() {
return startingLat;
}
public void setstartingLat(double startingLat) {
this.startingLat = startingLat;
}
public double getstartingLong() {
return startingLong;
}
public void setstartingLong(double startingLong) {
this.startingLong = startingLong;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getrouteName() {
return routeName;
}
public void setrouteName(String routeName) {
this.routeName = routeName;
}
public String getGeoPoints() {
return GeoPoints;
}
public void setGeoPoints(String GeoPoints) {
this.GeoPoints = GeoPoints;
}
public String getLayout_width() {
return layout_width;
}
public void setLayout_width(String layout_width) {
this.layout_width = layout_width;
}
public String getLayout_height() {
return layout_height;
}
public void setLayout_height(String layout_height) {
this.layout_height = layout_height;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getOrientation() {
return orientation;
}
public void setOrientation(String orientation) {
this.orientation = orientation;
}
public String getXmlns() {
return xmlns;
}
public void setXmlns(String xmlns) {
this.xmlns = xmlns;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isClickable() {
return clickable;
}
public void setClickable(boolean clickable) {
this.clickable = clickable;
}
public String getLayout_width2() {
return layout_width2;
}
public void setLayout_width2(String layout_width2) {
this.layout_width2 = layout_width2;
}
public String getLayout_height2() {
return layout_height2;
}
public void setLayout_height2(String layout_height2) {
this.layout_height2 = layout_height2;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Route Class Details:").append("\n\n");
sb.append("latitude: ").append(getlatitude());
sb.append("\n");
sb.append("longitude: ").append(getlongitude());
sb.append("\n");
sb.append("startingLat: ").append(getstartingLat());
sb.append("\n");
sb.append("startingLong: ").append(getstartingLong());
sb.append("\n");
sb.append("name: ").append(getname());
sb.append("\n");
sb.append("routeName: ").append(getrouteName());
sb.append("\n");
sb.append("GeoPoints: ").append(getGeoPoints());
sb.append("\n");
sb.append("layout_width: ").append(getLayout_width());
sb.append("\n");
sb.append("layout_height: ").append(getLayout_height());
sb.append("\n");
sb.append("orientation: ").append(getOrientation());
sb.append("\n");
sb.append("xmlns: ").append(getXmlns());
sb.append("\n");
sb.append("id: ").append(getId());
sb.append("\n");
sb.append("clickable: ").append(isClickable());
sb.append("\n");
sb.append("enabled: ").append(isEnabled());
sb.append("\n");
sb.append("layout_width2: ").append(layout_width2);
sb.append("\n");
sb.append("layout_height2: ").append(getLayout_height2());
sb.append("\n");
sb.append("apiKey: ").append(getApiKey());
return sb.toString();
}
// public ArrayList<GeoPoints_Class> getGeoPoints_arraylist() {
// return geoPoints_arraylist;
// }
public ArrayList<GeoPoints_Class> getGeoPoints_arraylist() {
return geoPoints_arraylist;
}
public void setGeoPoints_arraylist(ArrayList<GeoPoints_Class> geoPoints_arraylist) {
this.geoPoints_arraylist = geoPoints_arraylist;
}
public GeoPoints_Class getGeoPoints(int i) {
return geoPoints_arraylist.get(i);
}
public void addGeoPoint(double lat, double lon, String location) {
this.geoPoints_arraylist.add(new GeoPoints_Class(lat, lon, location));
}
}
```
Here is my second class (GeoPoints_Class) that is used in Route_Class.
```
package com.breckbus.app;
import android.os.Parcel;
import android.os.Parcelable;
class GeoPoints_Class implements Parcelable {
private double lat;
private double lon;
private String location;
public GeoPoints_Class(){
System.out.println("crash 99");
}
public GeoPoints_Class(double lat, double lon, String location){
System.out.println("crash 7");
this.lat = lat;
this.lon = lon;
this.location = location;
}
public int describeContents() {
return this.hashCode();
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel dest, int flags) {
System.out.println("crash 11");
dest.writeDouble(lat);
dest.writeDouble(lon);
dest.writeString(location);
System.out.println("crash 12");
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<GeoPoints_Class> CREATOR = new Parcelable.Creator<GeoPoints_Class>() {
public GeoPoints_Class createFromParcel(Parcel in) {
System.out.println("crash 28");
return new GeoPoints_Class(in);
}
public GeoPoints_Class[] newArray(int size) {
System.out.println("crash 29");
return new GeoPoints_Class[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private GeoPoints_Class(Parcel in) {
System.out.println("crash 13");
lat = in.readDouble();
lon = in.readDouble();
location = in.readString();
System.out.println("crash 14");
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("GeoPoint Class Details:").append("\n\n");
sb.append("latitude: ").append(getLat());
sb.append("\n");
sb.append("longitude: ").append(getLon());
sb.append("\n");
sb.append("location: ").append(getLocation());
sb.append("\n");
return sb.toString();
}
}
```
Next is where I put the objects using putExtra.
```
Intent i = new Intent("com.breckbus.app.ROUTE");
// i.putParcelableArrayListExtra("route_Classes_temp", route_Classes);
i.putExtra("route_Classes_temp",route_Classes);
System.out.println("crash 1");
```
Then where i get the objects.
```
Bundle extras = getIntent().getExtras();
Intent d = getIntent();
System.out.println("crash 25");
route_Classes = d.getParcelableArrayListExtra("route_Classes_temp");
System.out.println("crash 2");
// route_Classes = getIntent().getParcelableArrayListExtra("route_Classes_temp");
```
You will notice all of my manual debug statements since Eclipse doesnt work with android applications in debug mode (breakpoints and stuff). (Which if you know the solution to that, it would greatly help).
Next is the only error i get and where the manual debug statements i entered in the code stop. I dont know where it is crashing anymore.
Here is the first couple errors:
```
10-26 00:03:50.165: I/System.out(323): crash 13
10-26 00:03:50.165: I/System.out(323): crash 14
10-26 00:03:50.165: I/System.out(323): crash 28
10-26 00:03:50.165: I/System.out(323): crash 13
10-26 00:03:50.165: I/System.out(323): crash 14
10-26 00:03:50.185: I/System.out(323): crash 6
10-26 00:03:50.195: D/AndroidRuntime(323): Shutting down VM
10-26 00:03:50.195: W/dalvikvm(323): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-26 00:03:50.225: E/AndroidRuntime(323): FATAL EXCEPTION: main
10-26 00:03:50.225: E/AndroidRuntime(323): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.breckbus.app/com.breckbus.app.route}: java.lang.RuntimeException: Parcel android.os.Parcel#44edd958: Unmarshalling unknown type code 6553714 at offset 968
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.os.Handler.dispatchMessage(Handler.java:99)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.os.Looper.loop(Looper.java:123)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 00:03:50.225: E/AndroidRuntime(323): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 00:03:50.225: E/AndroidRuntime(323): at java.lang.reflect.Method.invoke(Method.java:521)
```
I hope i provided enough information. Please tell me what i am doing wrong when trying to pass the route_class ArrayList of Object type Route_Class from one activity to another using Intent. These two lines:
i.putExtra("route_Classes_temp",route_Classes);
route_Classes = d.getParcelableArrayListExtra("route_Classes_temp");
Thank you for your help, it is much appreciated.
It is true that you have provided too much information.
However, is this on the same process (i.e. your own app only?) If yes, then avoid doing that entirely. It will be too slow to parcel/unparcel these objects.
Use a singleton where you store your data and just access the singleton from each activity.

Categories