How can I print list of objects in android - android

I am using this code to show missed calls in my application while I am using Call class to define an object each time then store it in test how Can I print all objects in test list in my application?
List<Call> callList = new ArrayList<Call>();
while (c.moveToNext()) {
Call call = new Call();
call.setNumber(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)));
/* if (c.getInt(c.getColumnIndex(CallLog.Calls.TYPE)) == CallLog.Calls.OUTGOING_TYPE) {
call.setOut(true);
} else {
call.setOut(false);
}*/
call.setName(c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME)));
call.setTime(c.getLong(c.getColumnIndex(CallLog.Calls.DATE)));
call.setDuration(c.getLong(c.getColumnIndex(CallLog.Calls.DURATION)));
if ( c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME))!= null)
{
continue;
}
callList.add(call);
}
c.close();
}

you can override toString() method on Call class like:
#Override
public String toString() {
return Name+" "+Time+" "+Duration;
}
and print your list in for statement like:
for (int i = 0 ; i < callList.size() ; i++)
Log.d("value is" , callList.get(i).toString());

You can just iterate through the list and print the elements :
List<Call> callList = new ArrayList<Call>();
for(Call call : callList){
System.out.print("Name - " +call.getName() +
"Number - "+call.getNumber() +
"Time - "+call.getTime() +
"Duration - "call.getDuration());
}

you must override toString in your Call class like this
#Override
public String toString() {
return "Call{" +
"Name=" + Name+
", Time='" + Time+ '\'' +
", Duration='" + Duration+ '\'' +
'}';
}
and then use this
System.out.println("callList: " +Arrays.toString(callList.toArray()));

Related

Android recycle view dosen't recognize the ID of object after clicking at chosen position from list

I have a list of Buttons in RecycleView. I have implemented OnClickListener on every Button in list:
#Override
public void onClick(View v) {
int position = getAdapterPosition(); // gets item position
if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
// We can access the data within the views
Toast.makeText(context, position + " " + washLocations.get(position), Toast.LENGTH_SHORT).show();
Log.d("myTag", "This is my message");
Integer isFav = washLocations.get(position).getFav();
WashLocation w = washLocations.get(position);
Integer id = w.getId();
List<WashLocation> washLocation = dataBaseHelper.getWashLocation();
for(WashLocation wash : washLocation){
if(wash.getId().equals(w.getId())){
dataBaseHelper.updateWashLocation(w);
return;
}
}
w.setFav(isFav == 1 ? 0 : 1);
dataBaseHelper.addWashLocationToFav(w);
favorite.setText(w.getFav() == 1 ? "Usuń z ulubionych" : "Dodaj do ulubionych");
}
}
The case is whenever I want to compare wash Id from Wash object which has been already clicked I always get that id is null. But when I print every object from DB every wash object has their own unique ID.
While creating table I add autoincrement:
String CREATE_TABLE = "CREATE TABLE " + TABLE_WASH_LOCATION + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + COL_WASH_NAME + " TEXT,"
+ COL_WASH_CITY + " TEXT," + COL_WASH_STREET + " TEXT," + COL_LAT + " TEXT," + COL_LNG + " TEXT," + COL_FAV + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
Example:
UPDATE:
The list of washLocation in adapter is popualted:
washLocations = new ArrayList<>();
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new MyAdapter(washLocations, this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAsyncTask myAsyncTask = new MyAsyncTask();
try {
JSONObject jsonObject = myAsyncTask.execute(latitude, longitude, radius).get();
String lat;
String lng;
String name = "";
String city = "";
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int n = 0; n < jsonArray.length(); n++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(n);
lat = jsonObject1.getJSONObject("geometry").getJSONObject("location").get("lat").toString();
lng = jsonObject1.getJSONObject("geometry").getJSONObject("location").get("lng").toString();
JSONObject oName = jsonArray.getJSONObject(n);
if (oName.has("name")) {
name = oName.getString("name");
}
JSONObject oVicinity = jsonArray.getJSONObject(n);
if (oVicinity.has("vicinity")) {
city = oVicinity.getString("vicinity");
}
WashLocation w = new WashLocation(name, lat, lng, 0, getCity(city), null);
washLocations.add(w);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
I'm not really sure that I understand what you are trying to do, i cleaned up your code a bit and added comments starting with a Q, can you answer those questions ?
#Override
public void onClick(View v) {
int position = getAdapterPosition(); // gets item position
if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
WashLocation w = washLocations.get(position);
// We can access the data within the views
// Q: Does this show the right WashLocation ?
Toast.makeText(context, position + " " + w, Toast.LENGTH_SHORT).show();
Log.d("myTag", "This is my message");
Integer isFav = w.getFav();
Integer id = w.getId();
// Q: Will this list be different from washLocations ?
List<WashLocation> washLocation = dataBaseHelper.getWashLocation();
for(WashLocation wash : washLocation){
if(wash.getId().equals(id)){
// Q: Why can't you execute this line immediately ?
// Q: What does this line actually do ?
dataBaseHelper.updateWashLocation(w);
return;
}
}
w.setFav(isFav == 1 ? 0 : 1);
dataBaseHelper.addWashLocationToFav(w);
favorite.setText(w.getFav() == 1 ? "Usuń z ulubionych" : "Dodaj do ulubionych");
}
}

Cannot delete last char of StringBuffer String

I am facing a strange(for me) problemm of not being able to delete the last char of a stringbuffer string. I am building an app in which i have many checkboxes and i want to take multiple values so thats why i used the stringbuffer to append the checkboxes names.
Code:
int length = iceCreamPreference.length();
if (length>0){
iceCreamPreference = iceCreamPreference.deleteCharAt(length - 1);
}
Toast.makeText(SweetsLayoutActivity.this,
"Quantity: " + quantityNumberFinal +
"\nIce Cream Flavors: " + iceCreamPreference.toString() +
"\nIce Scream Scoops: " + quantityIceCreamNumberFinal +
"\nSyrups: " + syrupPreference.toString(), Toast.LENGTH_LONG).show();
Where i build the StringBuffer:
private void checkWhatIceCreamSelected() {
iceCreamPreference = new StringBuffer();
if (chocolate.isChecked()){
iceCreamPreference.append(chocolate.getText().toString() + ", ");
}
if (strawberry.isChecked()){
iceCreamPreference.append(strawberry.getText().toString() + ", ");
}
if (vanilla.isChecked()){
iceCreamPreference.append(vanilla.getText().toString() + ", ");
}
if (banana.isChecked()){
iceCreamPreference.append(banana.getText().toString() + ", ");
}
if (cookies.isChecked()){
iceCreamPreference.append(cookies.getText().toString() + ", ");
}
if (pistachio.isChecked()){
iceCreamPreference.append(pistachio.getText().toString() + ", ");
}
if (cheeseCake.isChecked()){
iceCreamPreference.append(cheeseCake.getText().toString() + ", ");
}
if (oreo.isChecked()){
iceCreamPreference.append(oreo.getText().toString() + ", ");
}
if (mango.isChecked()){
iceCreamPreference.append(mango.getText().toString() + ", ");
}
if (caramel.isChecked()){
iceCreamPreference.append(caramel.getText().toString() + ", ");
}
if (pineapple.isChecked()){
iceCreamPreference.append(pineapple.getText().toString() + ", ");
}
if (sorbet.isChecked()){
iceCreamPreference.append(sorbet.getText().toString() + ", ");
}
}
The Result:
HERE
I would like to have the last "," comma removed.
Any suggestions will be highly appreciated!!!
The last char in the your StringBuffer will be a space, so you need to delete the last two characters to get rid of the final comma.
You can use the comma before the name and put a logic so that it doesn't append comma before first data entry. So code will be
Declare a boolean variable
boolean comma=false;
Then do code like following
private void checkWhatIceCreamSelected() {
iceCreamPreference = new StringBuffer();
if (chocolate.isChecked()){
if(comma!=false)
{
iceCreamPreference.append( ", ");
}
iceCreamPreference.append(chocolate.getText().toString());
comma=true;
}
//do same for all other if
}

Creating custom listview from pre-existing arraylist

I'm obviously missing something in making this custom adapter. Basically, I've got code that grabs JSON from the site, then breaks it down into a ArrayList. I can do a .toString() and spit it all out onto a listview just fine, but everything I find on the net for creating a custom adapter creates the list inside of it. Is there a way to just supply your pre-created list? I've yet to make any headway on getting the custom one to work...but, as I said I can get the string to work just fine, so I'll include that code.
Here's my classes:
public class JSONEvents {
String eid;
String bid;
private String bname;
private String valid;
#Override
public String toString() {
return "Events [eid=" + eid + ", bid=" + bid + ", bname=" + bname
+ ", start=" + start + ", end=" + end + ", points=" + points
+ ", title=" + title + ", description=" + description
+ ", cat=" + cat + ", type=" + type + ", subtype=" + subtype
+ ", valid=" + valid + "]";
}
public String getEventInfo(String field){
if("eid".equals(field)){return eid;}
else if("bid".equals(field)){return bid;}
else if("bname".equals(field)){return bname;}
else if("valid".equals(field)){return valid;}
return "none";
}
}
public class JSONAdventures {
private String aid;
private String bid;
private String start;
private String valid;
#Override
public String toString() {
return "Adventures [aid=" + aid + ", bid=" + bid + ", start=" + start
+ ", end=" + end + ", points=" + points + ", title=" + title
+ ", description=" + description + ", cat=" + cat + ", type="
+ type + ", subtype=" + subtype + ", steps_comp=" + steps_comp
+ ", total_steps=" + total_steps + ", valid=" + valid + "]";
}
public String getEventInfo(String field){
if("aid".equals(field)){return aid;}
else if("bid".equals(field)){return bid;}
else if("start".equals(field)){return start;}
else if("valid".equals(field)){return valid;}
return "none";
}
}
public class JSONEandA {
private ArrayList<JSONEvents> events;
private ArrayList<JSONAdventures> adventures;
#Override
public String toString() {
return "ResponseHolder [events=" + events + ", adventures="
+ adventures + "]";
}
public ArrayList<JSONEvents> getJSONEvents() {
return events;
}
public ArrayList<JSONAdventures> getJSONAdventures() {
return adventures;
}
}
For the code in m activity:
List<JSONEvents> eventlist = new ArrayList<JSONEvents>();
try {
Gson googleJson = new Gson();
JSONEandA rh = googleJson.fromJson(example,
JSONEandA.class);
for (JSONEvents e : rh.getJSONEvents()) {
eventlist.add(e);
//eventlist.addAll(e);
// System.out.println(e.toString());
System.out.println(e.getEventInfo("eid"));
System.out.println(e.toString());
}
final ListView listview = (ListView) findViewById(R.id.eventlistview);
String[] values = new String[eventlist.size()];
eventlist.toArray(values);
// String[] values = new String[] {e.toString()};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(
Events.this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
final View view, int position, long id) {
final String item = (String) parent
.getItemAtPosition(position);
list.remove(item);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
"Item Removed", Toast.LENGTH_LONG).show();
});
I've also pieced together an attempt at an adapter from various tutorials and such, but can't figure out how to tie it all together:
class EventAdapter extends ArrayAdapter<JSONEvents> {
private ArrayList<JSONEvents> items;
public EventAdapter(Context context, int textViewResourceId,
ArrayList<JSONEvents> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_events, null);
}
JSONEvents q = items.get(position);
if (q != null) {
TextView nameText = (TextView) v.findViewById(R.id.firstline);
TextView priceText = (TextView) v.findViewById(R.id.secondLine);
if (nameText != null) {
nameText.setText(q.getEventInfo("eid"));
}
if (priceText != null) {
priceText.setText(q.getEventInfo("bid"));
}
}
return v;
}
}
I would appreciate any help, thanks!
Did you put tha data into your adapter?
adapter.addAll(String[] data);
Or you could do it while creating adapter:
EventAdapter adapter = new EventAdapter(this, R.id.some_id, eventlist);

Check if list contains multiple values android

I have searched and found: How to check if a value already exists in the database in Android. The problem I am having is that the toast never shows and the data is still entered in the database when the values that are being entered match what is already in the database. I have seen post about using UNIQUE to make sure data is not duplicated, but it will not work for what I am needing to do. I have tried if (entries.contains(checkDuplicates) == false) and if (!entries.equals(checkDuplicates)), and got the same results with those as well. I know it is something simple that I am missing or not understanding. Will someone help me out and point mes in the right direction please?
private void saveState() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
eventDate = sdf.format(calendar.getTime());
String date = eventDate;
String event = eventTitle.getText().toString();
String empID = fiveAndTwo.getText().toString();
/**
* CRUD Operations
* */
// Inserting entries to DB
// Reading all contacts
Log.d("Reading: ", "Reading all entries..");
List<EventEntries> entries = db.getAllEntries();
for (EventEntries ee : entries) {
String log = "Id: " + ee.getID() + " Date: " + ee.getDate() + " Event Name: " + ee.getEvent() + " Emp ID: " + ee.getempID();
// Writing entries to log
Log.d("Entry: ", log);
}
String checkDuplicates = date + event + empID;
if (!entries.contains(checkDuplicates)) {
Log.d("Insert: ", "Inserting ..");
db.addEntry(new EventEntries(date, event, empID));
String logEntry = "Date: " + date + " Event Name: " + event + " Emp ID: " + empID;
Log.d("Entered to DB:", logEntry);
} else {
Toast.makeText(this,"Employee has already been scanned for this event.", Toast.LENGTH_SHORT).show();
}
}
Edit: I got it to work. Here is what I did:
private void saveState() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
eventDate = sdf.format(calendar.getTime());
String date = eventDate;
String event = eventTitle.getText().toString();
String empID = fiveAndTwo.getText().toString();
/**
* CRUD Operations
* */
// Reading all entries
Log.d("Reading: ", "Reading all entries..");
List<EventEntries> entries = db.getAllEntries();
for (EventEntries ee : entries) {
String log = "Id: " + ee.getID() + " Date: " + ee.getDate() + " Event Name: " + ee.getEvent() + " Emp ID: " + ee.getempID();
// Writing entries to log
Log.d("Entry: ", log);
}
EventEntries checkDuplicates = new EventEntries(date, event, empID);
if (!entries.contains(checkDuplicates)) {
Toast.makeText(this,"Successfully entered.", Toast.LENGTH_SHORT).show();
// Inserting entries to DB
Log.d("Insert: ", "Inserting ..");
db.addEntry(new EventEntries(date, event, empID));
String logEntry = "Date: " + date + " Event Name: " + event + " Emp ID: " + empID;
Log.d("Entered to DB:", logEntry);
} else {
empAlert();
}
}
And here is what I added to the EventEntries class:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_date == null) ? 0 : _date.hashCode());
result = prime * result + ((_empID == null) ? 0 : _empID.hashCode());
result = prime * result + ((_event == null) ? 0 : _event.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventEntries other = (EventEntries) obj;
if (_date == null) {
if (other._date != null)
return false;
} else if (!_date.equals(other._date))
return false;
if (_empID == null) {
if (other._empID != null)
return false;
} else if (!_empID.equals(other._empID))
return false;
if (_event == null) {
if (other._event != null)
return false;
} else if (!_event.equals(other._event))
return false;
return true;
}
entries.contains(checkDuplicates) always returns false because entries is a list of EventEntries object and checkDuplicates is a String. You should call entries.contains using an EventEntries object as the parameter.
One more thing:
// assuming entries is not empty
EventEntries first = entries.get(0);
entries.contains(first); // --> this is TRUE
// create a dupe of "first"
EventEntries firstDupe = new EventEntries(.....);
entries.contains(firstDupe); // --> in *general* this is FALSE
In general, the second case is false. It can be true, if in the EventEntries class you override the equals method so that first.equals(firstDupe) would return true. Only then, the second example will return true.
Here's an example implementation:
public boolean equals(Object obj) {
if (obj instanceof EventEntries) {
EventEntries other = (EventEntries)obj;
if (date.equals(other.date) && event.equals(other.event)
&& empID == other.empID) {
return true;
}
}
return false;
}
(Adjust as necessary.)
Replace:
String checkDuplicates = date + event + empID;
with:
EventEntries checkDuplicates = new EventEntries(date, event, empID);

Retrieve records from sqllite using Array list

I am retrieving all records from database and saving all records in array list.when i show array list records ,repeated data displayed,i don't know what's the prolblem??
Calling this function in view_record class:
public ArrayList<tuple> getdata() { // TODO Auto-generated method stub
tuple obj=new tuple();
Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);
if(c == null) {
return null;
}
ArrayList <tuple> data = new ArrayList<tuple>();
// String result = " ";
int i=0;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
data.add(i, obj);
i++;
}
c.close();
return data; }
My view_record class
public class view_record extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_view);
TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
ImageView img=(ImageView) findViewById(R.id.img_view);
db_handler info=new db_handler(this);
info.open();
// Log.d("abc", "adb");
ArrayList <tuple> data=info.getdata();
Log.d("abc", "adb");
String result="";
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
tv.setText(result);
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
info.close(); } }
I want to view as follows :
" 1 cname sname family location "
" 2 cname sname family location "
But i am getting
" 2 cname sname family location "
" 2 cname sname family location "
Means last record displayed two times.
and one more thing ,i want to get all records where cname=something,getting error while doing it so
you are not making a new project in your for loop. That is whay you are getting same results. just do...
on start of for loop add this line obj=new tuple();
Answer to your Second Question
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
tv.setText(Html.fromHtml(result));

Categories

Resources