I would ask You for a help. Now I am writing an app, which takes current events from Google calendars. But problem is there, when I'm trying to output events from more than one calendar. I know, that I'm doing something wrong, but really, can't get in the problem..
public class Main extends Activity {
//TextView mInfo;
TextView mEvents;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//mInfo = (TextView)findViewById(R.id.info);
mEvents = (TextView)findViewById(R.id.events);
String[] calendarName = {"Calendar1", "Calendar2", "Calendar3", "Calendar4", "Calendar5"};
readCalendars(calendarName);
}
private void readCalendars(String[] calendarName)
{
String[] projection =
new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
CalendarContract.Calendars.ACCOUNT_TYPE};
Cursor calCursor =
getContentResolver().
query(CalendarContract.Calendars.CONTENT_URI,
projection,
CalendarContract.Calendars.VISIBLE + " = 1",
null,
CalendarContract.Calendars._ID + " ASC");
long calId = -1;
//String calendarAccount = "";
for(int i = 0; i 0)
{
if(cursor.moveToFirst())
{
do
{
long eventId = cursor.getLong(3);
events += getEventInfo(eventId,cursor.getLong(1),cursor.getLong(2),cursor.getString(4),cursor.getString(5),cursor.getString(6)) + "\n";
} while(cursor.moveToNext());
}
}
mEvents.setText(events);
}
}
#SuppressLint("SimpleDateFormat")
private String getEventInfo(long eventId,long startTime, long endTime,String description, String location,String title)
{
String eventInfo = "";
{
DateFormat df = new SimpleDateFormat("HH:mm");
String start = df.format( new Date(startTime));
String end = df.format( new Date(endTime));
eventInfo = start + "-" + end + " Class: "+ location + "\nLecture: " + title + "\nLecturer: " + description;
}
return eventInfo;
}
}
Tried to output all events with loop, but does not helps. If I pass in calendarName[i], where i is one of existing calendars, I get output of calendar, which I asked for, but that's only one calendar, but for example, I need to output 5 calendars.
Tried to do anything with ListView - failure again.
Hope, You would help with this problem or help somehow how to resolve it..
The CalendarContract.Calendars.CONTENT_URI can be used to retrieve calendars, but not actual events for those calendars. Once you have the calendar id, you must use either of the following URIs for event information:
CalendarContract.Events.CONTENT_URI
CalendarContract.Instances.CONTENT_URI
Related
I am querying the CalendarContract.Instances table to read all calendar event instances within a time interval (curr_time, next_time), as shown in the code below. This code works when the calendar entries have been around for a while. However, if I add a new entry, change an existing entry, or delete it, I get some old/stale entries (e.g., a new entry is not returned when it should be, or the unmodified/deleted entry is still returned), and this happens consistently. This problem occurs on my phone (Samsung S7) but does not appear to occur on the Android emulator. I am wondering if anyone else has seen this problem, or what I might be doing wrong. Any help is appreciated. Thanks.
try {
Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, curr_time);
ContentUris.appendId(builder, next_time);
String[] INSTANCE_PROJECTION = new String[]{Instances.EVENT_ID,
Instances.TITLE, Instances.BEGIN, Instances.END};
Uri uri = builder.build();
cur = cr.query(uri, INSTANCE_PROJECTION, null, null,null);
if (cur != null) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(Instances.EVENT_ID));
String title = cur.getString(cur.getColumnIndex(Instances.TITLE));
long start = cur.getLong(cur.getColumnIndex(Instances.BEGIN));
long end = cur.getLong(cur.getColumnIndex(Instances.END));
Calendar calendar = Calendar.getInstance();
DateFormat formatter = SimpleDateFormat
.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
calendar.setTimeInMillis(start);
Date start_date = calendar.getTime();
calendar.setTimeInMillis(end);
Date end_date = calendar.getTime();
Log.i(log_tag, "Event: " + id + "\t" + title + "\t" +
start + " " + formatter.format(start_date) + "\t" +
end + " " + formatter.format(end_date));
}
}
} catch (SecurityException e) {
// no permission to read calendars
} finally {
if (cur != null)
cur.close();
}
I have two classes, one class is saving weight, then in the other class/ activity I want a log that appends the weight along with the date and time, then makes a new line and displays the next weight. This way the user can keep track of their daily weight changes.
Problem is I'm brand new to Java and clearly am getting stuck on a silly problem. Each time I try append it instead just overwrites. I probably need to save it and then add it? maybe? I've tried a few different things and nothing is working all that well.
This is day 3 of Java. Apologies.
Tried making a list that is saved with sharedpreferences. Either did it wrong or it didnt work. Also tried just calling for the weight and appending it, but it overwrites it all.
My Logging activity:
public class LogActivity extends AppCompatActivity {
TextView logger;
//TextView more;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button back = findViewById(R.id.btnBack);
logger = findViewById(R.id.txtLog);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
SharedPreferences log = getSharedPreferences("MyPrefsFile", 0);
//Float value = log.getFloat("floatingLog",0);
Float value = log.getFloat("weight", 0);
//more.append(logger + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
logger.append("Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
// Adding back button
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
// SharedPreferences settings7 = getSharedPreferences("PREFS",0);
// String wordsString = settings7.getString("words","");
// String[] itemWords = wordsString.split(",");
// List<String> items = new ArrayList<String>();
// for (int i = 0; i < itemWords.length; i++){
// items.add(itemWords[i]);
// }
// for (int i = 0; i < items.size(); i++){
// Log.d("list", items.get(i));
// }
}
}
This is getting the sharedpreferences from here, in my ProfileActivity:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) findViewById(R.id.txtWeight)).setText(findViewById(R.id.txtNewWeight).toString());
floatingLog = weight.toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
floatingWeight = Float.valueOf(newWeight.getText().toString());
editor.putString("floatingLog", floatingLog);
editor.putFloat("weight", floatingWeight);
editor.apply();
editor.commit();
weight.setText(String.valueOf(floatingWeight));
Hello and welcome to SO!
actually in TextView, you can access to current value via TextView#getText() and after that you can update the text value similarly using TextView#setText(String text)
so you need to write something like this:
String currentText = logger.getText();
String updatedText = currentText + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n";
logger.setText(updatedText)
tada !
UPDATE
I think your problem is with how you save your records in your sharedPrefs
in this line
editor.putFloat("weight", floatingWeight); in this part you are overwriting the existing value,
simplest approach that comes to my mind is that instead of saving weight like this, you create an array of weights and append to end of it every day and store the array.
how ever it will be far more better if you use data base for this which gives you far more flexibility.
to use database take a look at Android official orm Android Room it is very simple and straightforward
I know this question is asked a lot, but I am genuinely stumped, I have looked at other methods, and tried everything...
My coding problem is as follows, I have a public class in java, and I made a string array in the global scope. I tried to add to it using array.add("somestringhere"), but it spits out an error saying (the title)... One more thing to note is this class is inside the main class for the file. so let's see if I can show it here:
public class see_schedule_activity extends AppCompatActivity {
.
..
.
.
.
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxphp";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
try {
// I have a intent passed from teh main class
Bundle extras = getIntent().getExtras();
String[] tasks = extras.getStringArray("tasks");
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("schedule");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
activityid = c.getString("activityid");
String yesno = c.getString("yesno");
String start = c.getString("start");
String stop = c.getString("stop");
String plusminus = c.getString("plusminus");
Log.e("Hash Map", "Routine ID #" + activityid);
if (!TextUtils.isEmpty(activityid) && TextUtils.isDigitsOnly(activityid)) {
routine = hm.get(Integer.valueOf(activityid));
} else {
routine = "";
}
// TODO: Make the PHP work with a variable residentID
//TODO: only make a string if the yes is checked
//TODO: make the routine name
// Log.e(TAG, "Value for yesno:" + yesno);
if (c.getString("yesno").equals("Yes")) {
schedule = routine + " starts at " + start + " and ends at " + stop + " with plusorminus " +
plusminus + " minutes ";
tasks.add(schedule);// This lines yeilds the problem
Log.e(TAG, "" + schedule);
}
// // show the values in our logcat
// Log.e(TAG, "activityid: " + activityid
// + ", yesno: " + yesno
// + ", start: " + start
// + ", stop: " + stop
// + ", plusminus: " + plusminus);
}
Intent intent = new Intent(getApplicationContext(),see_schedule_activity.class);
intent.putExtra("tasks_filled",tasks);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
}
}
I would appreciate any help, I'm a newb to programming and android studio, and php..so yeah thanks in advance, Justin
tasks is an String array as you defined
String[] tasks = extras.getStringArray("tasks");
And Array doesn't have any add method.
You need to convert tasks to a list like following
List<String> list = Arrays.asList(tasks);
Then you can use list.add(schedule)
According to my requirements i should save the events in android calendar like event name, starDate and endDate etc and retrieve lastly saved events, Now everything goes well, instead of fetching last event values i'm getting first event, can anybody tell the logic for this issue please.
Here's my code
private void addEvent2() {
Intent l_intent = new Intent(Intent.ACTION_EDIT);
l_intent.setType("vnd.android.cursor.item/event");
//l_intent.putExtra("calendar_id", m_selectedCalendarId); //this doesn't work
l_intent.putExtra("title", "roman10 calendar tutorial test");
l_intent.putExtra("description", "This is a simple test for calendar api");
l_intent.putExtra("eventLocation", "#home");
l_intent.putExtra("beginTime", System.currentTimeMillis());
l_intent.putExtra("endTime", System.currentTimeMillis() + 1800*1000);
l_intent.putExtra("allDay", 0);
//status: 0~ tentative; 1~ confirmed; 2~ canceled
l_intent.putExtra("eventStatus", 1);
//0~ default; 1~ confidential; 2~ private; 3~ public
l_intent.putExtra("visibility", 3);
//0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
l_intent.putExtra("transparency", 0);
//0~ false; 1~ true
l_intent.putExtra("hasAlarm", 1);
try {
startActivity(l_intent);
} catch (Exception e) {
Toast.makeText(this.getApplicationContext(), "Sorry, no compatible calendar is found!", Toast.LENGTH_LONG).show();
}
}
Retrieving code
private void getLastEvent() {
Uri l_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
String[] l_projection = new String[]{"title", "dtstart", "dtend"};
Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, "calendar_id=" + m_selectedCalendarId, null, "dtstart DESC, dtend DESC");
//Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, null, null, null);
if (l_managedCursor.moveToFirst()) {
int l_cnt = 0;
String l_title;
String l_begin;
String l_end;
StringBuilder l_displayText = new StringBuilder();
int l_colTitle = l_managedCursor.getColumnIndex(l_projection[0]);
int l_colBegin = l_managedCursor.getColumnIndex(l_projection[1]);
int l_colEnd = l_managedCursor.getColumnIndex(l_projection[1]);
do {
l_title = l_managedCursor.getString(l_colTitle);
l_begin = getDateTimeStr(l_managedCursor.getString(l_colBegin));
l_end = getDateTimeStr(l_managedCursor.getString(l_colEnd));
l_displayText.append(l_title + "\n" + l_begin + "\n" + l_end + "\n----------------\n");
++l_cnt;
} while (l_managedCursor.moveToNext() && l_cnt < 1);
m_text_event.setText(l_displayText.toString());
}
l_managedCursor.close();
}
retrieve lastly saved events
As long as you don't save the date where you add the event you can't get last added events.
Looking in Calendar.Contract.Events API I can't find any field to insert this kind of extra data, so you have 2 sol.lutions:
Create a SharedPreferences or DataBase to store basic data to find a calendar event PLUS adding date, then make search in this Preferences or DataBase and retrieve information from calendar according to it.
EASIER, BUT NOT RECOMMENDEDAdd in some String field like DESCRIPTION or ORGANIZER the Timestamp or Date of addition of the event, then when searching just get this part of the event and sort to get last added.
I need to use a for loop, and arrays, to take two inputs and subtract them (input format hh:mm:ss). Then output the difference in a editText. But I can't seem to get to get my code to run.
Sorry if this is a really basic problem. I have spent days looking on the web trying to understand the problem. This is my first attempt at Java.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
end = (EditText) findViewById(R.id.etEnd);
start = (EditText) findViewById(R.id.etStart);
diff = (EditText) findViewById(R.id.etDiff);
calc = (Button) findViewById(R.id.bCalc);
clear = (Button) findViewById(R.id.bClear);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int hh = tot[0];
int mm = tot[1];
int ss = tot[2];
String sGet2 = end.getText().toString(); // end to string
String sGet1 = start.getText().toString(); // start to string
String[] erA = sGet2.split(":"); // end string to end array
String[] srA = sGet1.split(":"); // start string to string array
for (int i = 0; i < srA.length; i++) {
inted = Integer.parseInt(erA[i].trim());
intst = Integer.parseInt(srA[i].trim());
tot[i] = inted - intst;
if (i == 2) {
String mt = ":" + mm;
String st = ":" + ss;
String ht = ":" + hh;
String tota = mt + st;
String total = tota + ht;
out = String.format("%4.4s", total);
diff.setText(out);
} else
return;
It's not surprising your code doesn't work... a lot of it never executes!
for (int i = 0; i < srA.length; i++) {
// bla bla bla
if (i == 2) {
// This code never runs because i is always 0.
} else
return; // What is this doing here!?
}
If this is your first attempt at programming then I think you should start with something a little simpler such as a console program. Also use a debugger to step through the code so that you can see how the control flow works.
You might also want to buy a book that teaches Java. There are many good books you can use that start you off with the basics.
Great code why return in else part. it terminates the execution when i=0. That is as the for loop starts execution.
first time i value is zero and your condition i==2 fails then it execute else part so it terminaes the for loop. then what is the use of for loop?????
use the below code::
String time1 = "22:55:00";
String time2 = "23:05:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
difference is in millis you can convert it to any unit or you can use DurationFormatUtils from apache-commons to pretty format it.
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm:ss"));
apache commons has really nice utility functions, apache-commons (lang)