Well I am running a loop to get data...it get's all the data of the month June..but when it comes to 19-June-2019 it skips the record and moves further without adding data into ArrayList.
My code
this.connection = createConnection();
Statement stmt = connection.createStatement();
Calendar last_month_data = Calendar.getInstance();
last_month_data.add(Calendar.MONTH, -1);
n=last_month_data.getActualMaximum(Calendar.DAY_OF_MONTH);
String last_month_year = new SimpleDateFormat("MMM-
yyyy").format(last_month_data.getTime());
String month_name = lastMonth.getText().toString();
for (int i = 1; i <= n; i++) {
String date = i + "-" + last_month_year;
ResultSet resultSet = stmt.executeQuery("Select
ATTN_TYPE,TO_CHAR(ATTN_TIME,'HH24:MI'),REMARK from MATTN_MAS
where ATTN_DATE='" + date + "' and Username='" + Username + "'
ORDER BY TRAN_NO DESC");
String Attn_Type;
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date d=format.parse(date);
SimpleDateFormat fomat1=new SimpleDateFormat("EEEE");
String weekName=fomat1.format(d);
StringBuffer myweekDate=new StringBuffer(weekName+", "+date);
String weekDate=myweekDate.toString();
if (resultSet.next()) {
while (resultSet.next()) {
Attn_Type = resultSet.getString(1);
String Time = resultSet.getString(2);
String Reason = resultSet.getString(3);
if (Attn_Type.equals("I")) {
String Attn_Type_In = "In";
String Attn_Type_Out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
weekDate, Reason, i, date_no, month_name,Time));
} else{
String Attn_Type_Out = "Out";
String Attn_Type_In = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_Out,
weekDate, Reason, i, date_no, month_name,Time));
}
}
}else {
Attn_Type = "Absent";
String out = null;
String Reason=null;
String Time=null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type, weekDate,
Reason, i, date_no, month_name,Time));
}
}
}catch (Exception e){
System.out.println("My Error"+e);
}
}
I want all the data of June from date 1 to date 30 but if there are no records of the given date it should insert Absent in ArrayList, Above code is working fine for all the date but the problem is it is not adding data for 19-Jun-2019 in ArrayList even no error is been shown I am not getting what exactly the problem is please help me out.
Please Check this Screenshot for more details...after Thursday,20 it skips 19, Wednesday and displaying data for Tuesday
Ok I got the answer thanks...
We have to use do....while instead of just while....it was
just skipping single data each time.....bcoz while is not
going to check second time if data is available or not....below is
the code...
.
if (resultSet.next()) {
do {
Attn_Type = resultSet.getString(1);
String Time = resultSet.getString(2);
String Reason = resultSet.getString(3);
if (Attn_Type.equals("I")) {
String Attn_Type_In = "In";
String Attn_Type_Out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
weekDate, Reason, i, date_no, month_name, Time));
} else {
String Attn_Type_Out = "Out";
String Attn_Type_In = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_Out,
weekDate, Reason, i, date_no, month_name, Time));
}
} while (resultSet.next());
} else {
Attn_Type = "Absent";
String out = null;
String Reason = null;
String Time = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type, weekDate,
Reason, i, date_no, month_name, Time));
}
}
}
..Output of above code is in below image..
Related
I have a string which i need to split at the first empty space.
Somehow I can not get it to split, the string stays untouched.
Could somebody help?
String in question:
https://test.com/info/dsfs76/933/TT Maps 2015.12
https://test.com/info/dsfs76/933/TT and Maps 2015.12 need to be 2 seperate parts which are added to an arraylist.
My code attempt:
if (str.contains(linkElem.getLinkAddress() + " ")) {
String[] temp = str.split(" ");
for (String temp : Arrays.asList(temp)) {
arraytest.add(temp);
}
}
From the code you provided, there is no such String strtemp
Maybe you should be splitting str instead?
String[] temp = str.split(" ");
You can use String tokenizer to do that like this:
StringTokenizer st = new StringTokenizer(linkElem.getLinkAddress(), " ");
String a = st.nextToken();//string before " "
String b = st.nextToken();//string after " "
i know it is completely unelegant and dumb but it works %)
String string = "https://test.com/info/dsfs76/933/TT Maps 2015.12";
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> list = new ArrayList<>();
boolean whiteSpaceFound = false;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == ' ' && !whiteSpaceFound) {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
whiteSpaceFound = true;
} else {
stringBuilder.append(string.charAt(i));
}
}
if (whiteSpaceFound || list.isEmpty()) {
list.add(stringBuilder.toString());
}
I set a column data type to CURRENT_TIMESTAMP in my table . It successfully saved current time.
2016-06-28 11:00:44 // it's actual mysql data
But when i parse it from Using GSON android i got the date string like
2016-06-28T06:09:54.000Z // parsed from json
That means space is alter with T & Z . how i remove these two field ?
My parsing Data is Like
Gson gson = new Gson();
String json = gson.toJson(args);
JSONArray test = new JSONArray(json);
Log.i("user registration", json);
//JSONArray jsonArray = new JSONArray(args);
//String aa = jsonArray.getString(0).toString();
//String aa = jsonArray.getString(0).toString();
// Log.i("user registration", aa);
String aa = test.getString(0).toString();
JSONObject jsonObject = test.getJSONObject(0);
JSONArray valueArrays = jsonObject.getJSONArray("values");
// // // // Log.e("email",newArr.getJSONObject(0).getString("email"));
for (int i = 0; i < valueArrays.length(); i++) {
JSONObject jo = valueArrays.getJSONObject(i);
String nvp = jo.getString("nameValuePairs");
jo = new JSONObject(nvp);
User user = new User();
String name = jo.getString("user_name");
user.setUserName(name);
if (name.equalsIgnoreCase(mUsername)) {
Log.i("user_matched", "I am " + mUsername);
continue;
}
user.setEmail(jo.getString("email"));
user.setSocket_id(jo.getString("socket_id"));
user.setLastSeen(jo.getString("last_seen"));
if (jo.getString("status") == "1") {
user.setStatus("online");
} else
user.setStatus("offline");
mUserList.add(user);
}
I just replace the Extra character from Date String .
Date rightFormatDateFromList(String formatted_date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
try {
Log.e("Wrong Format", "" + formatted_date);
formatted_date = formatted_date.replace('T', ' ');
formatted_date = formatted_date.replace(".000Z", "");
Log.e("Right Format", "" + formatted_date);
return dateFormat.parse(formatted_date);
} catch (Exception w) {
return null;
}
}
the Log Wrong Format: 2016-06-29T09:11:34.000Z
Right Format: 2016-06-29 09:11:34
i am confused why my code isn't capitalizing my first letter, i am getting the name of the user from the database with all letters lower case.
here is the code:
String email = null;
String name = null;
StringBuilder nameSB = new StringBuilder();
nameSB.append(name);
nameSB.setCharAt(0, Character.toUpperCase(nameSB.charAt(0)));
name = nameSB.toString();
try {
email = ((User) ParseUser.getCurrentUser()).getEmail();
name = ((User) ParseUser.getCurrentUser()).getFirstName() + " " + ((User) ParseUser.getCurrentUser()).getLastName();
} catch (NullPointerException npe) {
}
Just summarising as answer
String email = null;
String name = null;
StringBuilder nameSB = new StringBuilder();
try {
email = ((User) ParseUser.getCurrentUser()).getEmail();
name = ((User) ParseUser.getCurrentUser()).getFirstName() + " " + ((User) ParseUser.getCurrentUser()).getLastName();
nameSB.append(name);
nameSB.setCharAt(0, Character.toUpperCase(nameSB.charAt(0)));
name = nameSB.toString();
} catch (NullPointerException npe) {
}
My JSON File is returning only the first four values stored in it and rest it returns as null.
Here is my JSON File writing code
JSONArray data = new JSONArray();
JSONObject object = new JSONObject();
try
{
object.put("Event Name: ", Event);
object.put("College Name: ", College);
object.put("Category: ", Category);
object.put("Sub-Category: ", Sub);
object.put("Date From: ", Dfrom);
object.put("Date to :", Dto);
object.put("City: ", City);
object.put("State: ", State);
object.put("Venue: ", Venue);
object.put("Website: ", URL);
object.put("Registration Form Link: ", Form);
object.put("Contact Number: ", Number);
object.put("E-mail Id: ", Email);
data.put(object);
String text = data.toString();
FileOutputStream fos = openFileOutput("event.json", MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(fos);
writer.write(text);
writer.flush();
writer.close();
Toast.makeText(getApplicationContext(), "Event Successfully Submitted", Toast.LENGTH_SHORT)
.show();
}
Where Dfrom and Dto are dates chosen by DatePicker.
and this is my JSON File read coding
public void readForm()
{
String path = getFilesDir().getAbsolutePath() +"\n"+ "/event.json";
File f = new File(path);
f.setReadable(true, false);
try
{
FileInputStream fis = openFileInput("event.json");
BufferedInputStream bis = new BufferedInputStream(fis);
StringBuffer b = new StringBuffer();
while (bis.available()!=0)
{
char c = (char) bis.read();
b.append(c);
}
bis.close();
fis.close();
JSONArray data = new JSONArray(b.toString());
event1 = data.getJSONObject(0).getString("Event Name: ");
college1 = data.getJSONObject(0).getString("College Name: ");
category1 = data.getJSONObject(0).getString("Category: ");
sub1 = data.getJSONObject(0).getString("Sub-Category: ");
dfrom1 = data.getJSONObject(0).getString("Date From:");
dto1 = data.getJSONObject(0).getString("Date To: ");
city1 = data.getJSONObject(0).getString("City: ");
state1 = data.getJSONObject(0).getString("State: ");
venue1 = data.getJSONObject(0).getString("Venue: ");
url1 = data.getJSONObject(0).getString("Website: ");
form1 = data.getJSONObject(0).getString("Registration Form Link: ");
number1 = data.getJSONObject(0).getString("Contact Number: ");
email1 = data.getJSONObject(0).getString("E-mail Id: ");
}
after this i am passing these values to TextViews and only first four return values and rest are null.
DatePicker coding
DatePickerDialog.OnDateSetListener from_dateListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
abcd = (new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" ")).toString();
from.setText(abcd);
Dfrom = abcd;
// set selected date into datepicker also
}
};
and even if i try to show values from Dfrom to email all are returned null
Please Help
I think issue is with key value miss match
for example
You are setting
object.put("Date From: ", Dfrom);
object.put("Date to :", Dto);
And trying to get
dfrom1 = data.getJSONObject(0).getString("Date From:");
dto1 = data.getJSONObject(0).getString("Date To: ");
Do difference beetween "Date From: " and "Date From:" is space after ":"
so please cross check for all.
There may be some issue with your key because key is not matching in json :
Try below code :
public static final String KEY_EVENT = "event";
public static final String KEY_COLLEGE = "college";
public static final String KEY_CATEGORY = "category";
public static final String KEY_SUB_CATEGORY = "sub-category";
public static final String KEY_DATE_TO = "dateto";
public static final String KEY_DATE_FROM = "datefrom";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_VENUE = "venue";
public static final String KEY_WEBSITE = "website";
public static final String KEY_LINK_REGISTRATION = "registration";
public static final String KEY_CONTACT = "contact";
public static final String KEY_EMAIL = "email";
public void writeFile() {
JSONArray data = new JSONArray();
JSONObject object = new JSONObject();
try {
object.put(KEY_EVENT, "name");
object.put(KEY_COLLEGE, "college");
object.put(KEY_CATEGORY, "category");
object.put(KEY_SUB_CATEGORY, "sub");
object.put(KEY_DATE_FROM, "dfrom");
object.put(KEY_DATE_TO, "dto");
object.put(KEY_CITY, "city");
object.put(KEY_STATE, "state");
object.put(KEY_VENUE, "venue");
object.put(KEY_WEBSITE, "url");
object.put(KEY_LINK_REGISTRATION, "form");
object.put(KEY_CONTACT, "number");
object.put(KEY_EMAIL, "email");
data.put(object);
String text = data.toString();
FileOutputStream fos = openFileOutput("event.json", MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(fos);
writer.write(text);
writer.flush();
writer.close();
Toast.makeText(getApplicationContext(), "Event Successfully Submitted", Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readFile() {
String path = getFilesDir().getAbsolutePath() + "\n" + "/event.json";
File f = new File(path);
f.setReadable(true, false);
try {
FileInputStream fis = openFileInput("event.json");
BufferedInputStream bis = new BufferedInputStream(fis);
StringBuffer b = new StringBuffer();
while (bis.available() != 0) {
char c = (char) bis.read();
b.append(c);
}
bis.close();
fis.close();
JSONArray data = new JSONArray(b.toString());
String event1 = data.getJSONObject(0).getString(KEY_EVENT);
String college1 = data.getJSONObject(0).getString(KEY_COLLEGE);
String category1 = data.getJSONObject(0).getString(KEY_CATEGORY);
String sub1 = data.getJSONObject(0).getString(KEY_SUB_CATEGORY);
String dfrom1 = data.getJSONObject(0).getString(KEY_DATE_FROM);
String dto1 = data.getJSONObject(0).getString(KEY_DATE_TO);
String city1 = data.getJSONObject(0).getString(KEY_CITY);
String state1 = data.getJSONObject(0).getString(KEY_STATE);
String venue1 = data.getJSONObject(0).getString(KEY_VENUE);
String url1 = data.getJSONObject(0).getString(KEY_WEBSITE);
String form1 = data.getJSONObject(0).getString(KEY_LINK_REGISTRATION);
String number1 = data.getJSONObject(0).getString(KEY_CONTACT);
String email1 = data.getJSONObject(0).getString(KEY_EMAIL);
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks>!!
I have an html file in assets, aaa.html.
I want to read the contents of html file and replace it from another string.
Is this way is right or is there any other option.
my code:
File f = new File("file:///android_asset/aaa.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
But its giving file not found, where as loading in web view loads the file.
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("old string", "new string");
If you want to load file in webview then use this
mWebView.loadUrl("file:///android_asset/myfile.html");
you want to replace content inside Html file tags so the solution class code is here..
public class CardDetail {
public static String newHtmlString = "";
// private Context context;
#SuppressWarnings("rawtypes")
public String getNewHtmlString(String htmlString, HashMap hm) {
try {
StringTokenizer st = new StringTokenizer(htmlString, "##");
CardDetail.newHtmlString = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
CardDetail.newHtmlString += token;
if (st.hasMoreTokens()) {
String token2 = st.nextToken();
if (token2.equals("NAME") || token2.equals("POSITION") || token2.equals("COMPANY") || token2.equals("PHOTOURL"))
CardDetail.newHtmlString += hm.get(token2);
if (token2.equals("SKYPE_CONTAINER1")
|| token2.equals("TWITTER_CONTAINER1")
|| token2.equals("PHONENUMBER_CONTAINER1")
|| token2.equals("EMAIL_CONTAINER1")
|| token2.equals("ADDRESS_CONTAINER1")) {
String replaceString = st.nextToken();
String tokenMiddle = (String) hm.get(st.nextToken());
if (!tokenMiddle.equals("")) {
replaceString += tokenMiddle;
CardDetail.newHtmlString += replaceString + st.nextToken();
st.nextElement();
} else {
st.nextElement();
st.nextElement();
}
}
}
}
// Log.i("convertedHTMLString", newHtmlString);
return CardDetail.newHtmlString;
// htmlString = "<img src='" + hm.get("PHOTOURL") + "' width=80 height=80>";
// return htmlString;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
public HashMap<?, ?> getProfileHashMap(JSONObject jsonObject) {
#SuppressWarnings("rawtypes")
HashMap hm = new HashMap();
jsonObject = (new JSONConverterClass()).convertJsonObjectToCardDetail(jsonObject);
try {
hm.put("EMAIL", jsonObject.getString("email"));
hm.put("NAME", jsonObject.getString("firstname") + " " + jsonObject.getString("lastname"));
hm.put("COMPANY", jsonObject.getString("company_name"));
hm.put("POSITION", jsonObject.getString("position"));
hm.put("WEBSITE", jsonObject.getString("website"));
hm.put("PHONENUMBER", jsonObject.getString("phonenumber"));
hm.put("PHOTOURL", jsonObject.getString("picture_url"));
hm.put("SKYPE", jsonObject.getString("skype_username"));
hm.put("TWITTER", jsonObject.getString("twitter_username"));
hm.put("ADDRESS", jsonObject.getString("generic_location"));
} catch (Exception e) {
e.printStackTrace();
}
return hm;
}
}
convertJsonObjectToCardDetail this class just replace string with values from Json
hope this solves your problem ....