치춘짱베리굿나이스
졸업작품 (Application) 본문
package com.example.gradproject2020; | |
import androidx.fragment.app.Fragment; | |
import android.app.AlertDialog; | |
import android.bluetooth.BluetoothAdapter; | |
import android.bluetooth.BluetoothDevice; | |
import android.bluetooth.BluetoothSocket; | |
import android.content.DialogInterface; | |
import android.content.Intent; | |
import android.content.SharedPreferences; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.os.Looper; | |
import android.os.Message; | |
import android.os.SystemClock; | |
import android.text.InputType; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.CompoundButton; | |
import android.widget.EditText; | |
import android.widget.ImageView; | |
import android.widget.Switch; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.bumptech.glide.Glide; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.BufferedReader; | |
import java.io.BufferedWriter; | |
import java.io.DataInputStream; | |
import java.io.DataOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.FileReader; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.net.Socket; | |
import java.nio.file.Files; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Set; | |
import java.util.UUID; | |
import static android.content.Context.MODE_PRIVATE; | |
public class BTScreen extends Fragment { | |
//View | |
TextView txt_blton, txt_paired; | |
Button btn_pairing, btn_measure, btn_alertcancel, btn_unpair; | |
View view; | |
ImageView img_sugar; | |
TextView txt_sugar; | |
Switch swi_straw; | |
Intent Scr_BT; | |
//View_alert | |
View alertview, alertsendview, alertaddview; | |
TextView txt_alert, txt_alertsend; | |
Button btn_alertsendcancel, btn_addcancel, btn_addok; | |
ImageView img_alert, img_alert_send; | |
//flag | |
boolean bltonflag = false, pairedflag = false, strawflag = false, measureflag = false, alertflag = false; | |
boolean sendflag = false, threadflag = false, alertclosedflag = true, sendfinalresult = false; | |
int gradflag = 0, dataindex = 0, todayindex = 0, lastbevrep; | |
final int req_BT = 1; | |
//variables | |
String username; | |
float userkcal, userkcal_today, usersugar, usersugar_today; | |
String anddir, jsondir, filename, datelastupdate, lastbev; | |
String[] dataarr, dataarr1; | |
//Class | |
connectBT bt; | |
ConnectFTP ftp; | |
jsonclass js; | |
Socket socket; | |
DataInputStream dis; | |
//bluetooth variables | |
BluetoothAdapter BTAdapter; | |
Set<BluetoothDevice> pairedDevices; | |
List<String> listDevices; | |
Handler BTHandler, alerthandler, sendhandler, sockethandler; | |
BluetoothDevice BTdevice; | |
BluetoothSocket BTsocket; | |
AlertDialog.Builder builder, builder2, builder3; | |
final static int BT_REQUEST_ENABLE = 1; | |
final static int BT_MESSAGE_READ = 2; | |
final static int BT_CONNECTING_STATUS = 3; | |
final static UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); | |
boolean btconnect = false; | |
boolean saveflag = false; | |
FileOutputStream fos = null; | |
public BTScreen() { | |
//empty constructor | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
view = inflater.inflate(R.layout.activity_btscreen, container, false); | |
txt_blton = view.findViewById(R.id.txt_blton); | |
txt_paired = view.findViewById(R.id.txt_paired); | |
btn_pairing = view.findViewById(R.id.btn_pairing); | |
btn_measure = view.findViewById(R.id.btn_measure); | |
btn_unpair = view.findViewById(R.id.btn_unpair); | |
img_sugar = view.findViewById(R.id.img_sugar); | |
txt_sugar = view.findViewById(R.id.txt_sugar); | |
swi_straw = view.findViewById(R.id.swi_straw); | |
alertview = inflater.inflate(R.layout.alert_bt, container, false); | |
alertsendview = inflater.inflate(R.layout.alert_send, container, false); | |
alertaddview = inflater.inflate(R.layout.alert_adddata, container, false); | |
txt_alert = alertview.findViewById(R.id.txt_alert); | |
txt_alertsend = alertsendview.findViewById(R.id.txt_alert_send); | |
img_alert = alertview.findViewById(R.id.img_alert); | |
img_alert_send = alertsendview.findViewById(R.id.img_alert_send); | |
btn_alertcancel = alertview.findViewById(R.id.btn_alertcancel); | |
btn_alertsendcancel = alertsendview.findViewById(R.id.btn_alertsendcancel); | |
btn_addcancel = alertaddview.findViewById(R.id.btn_cancel); | |
btn_addok = alertaddview.findViewById(R.id.btn_ok2); | |
String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); | |
jsondir = getContext().getExternalFilesDir("/json").getAbsolutePath(); //폰 | |
filename = "/" + now + ".json"; | |
Handler handler = new Handler(Looper.getMainLooper()); | |
anddir = getActivity().getExternalFilesDir("/resources").getAbsolutePath(); //폰 | |
File file = new File(anddir + "/temp.bin"); | |
builder = new AlertDialog.Builder(getActivity()); | |
builder2 = new AlertDialog.Builder(getActivity()); | |
builder.setView(alertview) | |
.setCancelable(false); | |
AlertDialog alert = builder.create(); | |
builder3 = new AlertDialog.Builder(getActivity()); | |
builder3.setTitle("음료수를 찾는 중입니다...") | |
.setMessage("서버에서 데이터 수신 중입니다") | |
.setNegativeButton("예", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).create(); | |
bt = new connectBT(); | |
BTAdapter = BluetoothAdapter.getDefaultAdapter(); | |
ftp = new ConnectFTP(); | |
js = new jsonclass(); | |
js.load_pref(); | |
Glide.with(getContext()).load(R.drawable.loadingscreen2).into(img_alert); | |
Glide.with(getContext()).load(R.drawable.loadingscreen2).into(img_alert_send); | |
txt_alert.setText("컵을 기울여 음료를 마시세요"); | |
txt_alertsend.setText("음료수 측정 중..."); | |
btn_pairing.setOnClickListener(new Button.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
if (bt.bluetoothOn()) { | |
txt_blton.setText("ON"); | |
bltonflag = true; | |
bt.connectSelectedDevice("HC-06"); | |
if (btconnect) { | |
txt_paired.setText("YES"); | |
pairedflag = true; | |
} else { | |
txt_paired.setText("NO"); | |
pairedflag = false; | |
} | |
} else { | |
txt_blton.setText("OFF"); | |
bltonflag = false; | |
} | |
} | |
}); | |
btn_unpair.setOnClickListener(new Button.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
bt.bluetoothOff(); | |
txt_blton.setText("OFF"); | |
txt_paired.setText("NO"); | |
} | |
}); | |
btn_measure.setOnClickListener(new Button.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
try { | |
fos = new FileOutputStream(file); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
if (!bltonflag) { | |
Toast.makeText(getContext().getApplicationContext(), "블루투스 연결을 확인하세요.", Toast.LENGTH_SHORT).show(); | |
} else { | |
if (!pairedflag) { | |
Toast.makeText(getContext().getApplicationContext(), "기기 연결을 확인하세요.", Toast.LENGTH_SHORT).show(); | |
} else { | |
alert.show(); | |
alertclosedflag = false; | |
btn_alertcancel.setOnClickListener(new Button.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
saveflag = false; | |
measureflag = false; | |
alertflag = false; | |
alert.cancel(); | |
if(sendflag) { | |
sendhandler.sendEmptyMessage(3); | |
} | |
} | |
}); | |
alertflag = true; | |
txt_alert.setText("컵을 기울여 음료를 마시세요"); | |
alerthandler = new Handler() { | |
public void handleMessage(Message msg) { | |
if (msg.what == 1) { | |
if (measureflag) { | |
txt_alert.setText("마시는 동작 감지됨"); | |
alertview.invalidate(); | |
if (saveflag) { | |
try { | |
fos.close(); | |
txt_alert.setText("파일 저장 완료, 창을 닫아주세요"); | |
sendflag = true; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} else { | |
alerthandler.sendEmptyMessage(1); | |
} | |
} else if(strawflag){ | |
txt_alert.setText("빨대 모드 사용 중입니다"); | |
measureflag = true; | |
alertview.invalidate(); | |
new Handler().postDelayed(new Runnable() {// 1 초 후에 실행 | |
@Override | |
public void run() { | |
try { | |
fos.close(); | |
txt_alert.setText("파일 저장 완료, 창을 닫아주세요"); | |
sendflag = true; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
}, 5000); | |
} | |
else { | |
alerthandler.sendEmptyMessage(1); | |
} | |
} | |
} | |
}; | |
alerthandler.sendEmptyMessage(1); | |
} | |
} | |
} | |
}); | |
swi_straw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { | |
@Override | |
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { | |
if (isChecked) { | |
Toast.makeText(getContext().getApplicationContext(), "빨대 모드로 변경합니다.", Toast.LENGTH_SHORT).show(); | |
strawflag = true; | |
} else { | |
Toast.makeText(getContext().getApplicationContext(), "빨대 모드를 종료합니다.", Toast.LENGTH_SHORT).show(); | |
strawflag = false; | |
} | |
} | |
}); | |
BTHandler = new Handler() { | |
public void handleMessage(android.os.Message msg) { | |
if (msg.what == BT_MESSAGE_READ) { //BT Message obtained | |
try { | |
if (alertflag) { | |
js.gradientcheck((byte[]) msg.obj); | |
} | |
if (measureflag && !saveflag) { | |
js.rgbsave((byte[]) msg.obj); | |
} | |
else if(measureflag && strawflag){ | |
js.rgbsave((byte[]) msg.obj); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}; | |
sendhandler = new Handler(Looper.getMainLooper()){ | |
public void handleMessage(android.os.Message msg){ | |
if(msg.what == 3) { | |
js.sendfile("temp.bin", 3); | |
if (!threadflag) { | |
handler.postDelayed(new Runnable(){ | |
@Override | |
public void run(){ | |
sendhandler.sendEmptyMessage(3); | |
} | |
}, 500); | |
} | |
} | |
else if(msg.what == 4) { | |
builder3.show(); | |
handler.postDelayed(new Runnable() { | |
@Override | |
public void run() { | |
js.trainresult(); | |
} | |
}, 10000); | |
} | |
else if(msg.what == 5){ | |
js.sendfile(lastbev + "_0.bin", 5); | |
if (!threadflag) { | |
handler.postDelayed(new Runnable(){ | |
@Override | |
public void run(){ | |
sendhandler.sendEmptyMessage(5); | |
} | |
}, 500); | |
} | |
} | |
else if(msg.what == 6){ | |
js.sendfile(lastbev + "_" + lastbevrep + ".bin", 6); | |
if (!threadflag) { | |
handler.postDelayed(new Runnable(){ | |
@Override | |
public void run(){ | |
sendhandler.sendEmptyMessage(6); | |
} | |
}, 500); | |
} | |
} | |
} | |
}; | |
return view; | |
} | |
public class bev { | |
private int index; | |
private String name; | |
private double kcal; | |
private double sugar; | |
private int repeat; | |
public int getIndex(){ | |
return index; | |
} | |
public String getName() { | |
return name; | |
} | |
public double getKcal() { | |
return kcal; | |
} | |
public double getSugar() { | |
return sugar; | |
} | |
public int getRepeat(){ | |
return repeat; | |
} | |
public void setIndex(int index){ | |
this.index = index; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public void setKcal(double kcal) { | |
this.kcal = kcal; | |
} | |
public void setSugar(double sugar) { | |
this.sugar = sugar; | |
} | |
public void setRepeat(int repeat){ | |
this.repeat = repeat; | |
} | |
} | |
public class jsonclass { | |
public JSONObject loadJSON(String path) { | |
try { | |
File jsonfile = new File(path); | |
if (!jsonfile.exists()) { | |
JSONArray tempary = new JSONArray(); | |
JSONObject tempobj = new JSONObject(); | |
try{ | |
tempobj.put("Beverages", tempary); | |
} catch(JSONException e){ | |
e.printStackTrace(); | |
} | |
String str = tempobj.toString(); | |
FileWriter filewriter = new FileWriter(jsonfile); | |
BufferedWriter bufferedWriter = new BufferedWriter(filewriter); | |
bufferedWriter.write(str); | |
bufferedWriter.close(); | |
} | |
FileReader filereader = new FileReader(jsonfile); | |
BufferedReader bufferedReader = new BufferedReader(filereader); | |
StringBuilder stringBuilder = new StringBuilder(); | |
String line = bufferedReader.readLine(); | |
while (line != null) { | |
stringBuilder.append(line).append("\n"); | |
line = bufferedReader.readLine(); | |
} | |
bufferedReader.close(); | |
String responce = stringBuilder.toString(); | |
try{ | |
JSONObject obj = new JSONObject(responce); | |
return obj; | |
} catch (JSONException e){ | |
e.printStackTrace(); | |
return null; | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
void load_pref() { | |
//load preferences - today's data | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
userkcal = data_personal.getFloat("kcal", 1500); | |
userkcal_today = data_personal.getFloat("kcal_today", 0); | |
usersugar = data_personal.getFloat("sugar", 1000); | |
usersugar_today = data_personal.getFloat("sugar_today", 0); | |
datelastupdate = data_personal.getString("lastdate", "1970-01-01"); | |
dataindex = data_personal.getInt("index", 0); | |
todayindex = data_personal.getInt("todayindex", 0); | |
} | |
void json_save(String path, bev Bev) { | |
//all beverages : anddir + "/allbev.json" | |
//today beverages : jsondir + "/(date).json" | |
JSONObject oldobj = loadJSON(path); | |
JSONObject newobj = new JSONObject(); | |
try { | |
JSONArray newarr = oldobj.getJSONArray("Beverages"); | |
newobj.put("index", Integer.toString(Bev.index)); | |
newobj.put("name", Bev.name); | |
newobj.put("kcal", Float.toString((float) Bev.kcal)); | |
newobj.put("sugar", Float.toString((float) Bev.sugar)); | |
newobj.put("repeat", Integer.toString(Bev.repeat)); | |
newarr.put(newobj); | |
oldobj.put("Beverages", newarr); | |
}catch (JSONException e){ | |
e.printStackTrace(); | |
} | |
writeJsonFile(path, oldobj.toString()); | |
} | |
public void writeJsonFile(String path, String json) { | |
File file = new File(path); | |
BufferedWriter bufferedWriter = null; | |
try { | |
if (!file.exists()) { | |
file.createNewFile(); | |
} | |
FileWriter fileWriter = new FileWriter(file); | |
bufferedWriter = new BufferedWriter(fileWriter); | |
bufferedWriter.write(json); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
try { | |
if (bufferedWriter != null) { | |
bufferedWriter.close(); | |
} | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
} | |
void gradientcheck(byte[] obj) { | |
//calculate accX, accY, accZ, ... to start identifying bev | |
short m_AcX, m_AcY, m_AcZ; | |
m_AcX = (short) ((obj[2] << 8) | (obj[1])); | |
m_AcY = (short) ((obj[4] << 8) | (obj[3])); | |
m_AcZ = (short) ((obj[6] << 8) | (obj[5])); | |
System.out.println("X :" + Short.toString(m_AcX) + ", Y :" + Short.toString(m_AcY) + ", Z :" + Short.toString(m_AcZ)); | |
if (alertflag) { //AlertDialog opened | |
if (!measureflag) { | |
if ((m_AcY < -2000) || (m_AcY > 10000)) { | |
if (gradflag == 0) gradflag = 1; | |
else if (gradflag == 1) gradflag = 2; | |
else if (gradflag == 2) measureflag = true; | |
} | |
} else if (measureflag) { | |
if ((m_AcY > 250) && (m_AcY < 5000)) { | |
if (gradflag == 3) gradflag = 2; | |
else if (gradflag == 2) gradflag = 1; | |
else if (gradflag == 1) gradflag = 0; | |
else if (gradflag == 0) saveflag = true; | |
} | |
} | |
} | |
} | |
void rgbsave(byte[] obj) { | |
try { | |
fos.write(0x02); //start of the obj | |
fos.write(obj[17]); | |
fos.write(obj[18]); | |
fos.write(obj[19]); | |
fos.write(obj[20]); | |
fos.write(obj[21]); | |
fos.write(obj[22]); | |
fos.write(obj[23]); | |
fos.write(obj[24]); | |
fos.write(0x03); //end of the obj | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
void sendfile(String filen, int msg){ | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
if (!ftp.ftpConnect("<IP ADDRESS HERE>", "<ID HERE>", "<PW HERE>", 21)) { | |
threadflag = false; | |
} else { | |
String dir = ftp.ftpGetDirectory(); | |
if (!ftp.ftpUploadFile(anddir + "/temp.bin", filen, dir)) { | |
threadflag = false; | |
} else { | |
threadflag = true; | |
if(msg == 3) sendhandler.sendEmptyMessage(4); | |
} | |
} | |
} | |
}).start(); | |
} | |
void trainresult(){ | |
sockethandler = new Handler(Looper.getMainLooper()); | |
Thread socketthread = new Thread() { | |
public void run() { | |
try { | |
socket = new Socket("<IP ADDRESS HERE>", 9999); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
try { | |
DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); | |
dos.writeUTF("안드로이드에서 서버로 연결요청"); | |
} catch (IOException e) { | |
} | |
try { | |
byte[] byteArr = new byte[1000]; | |
InputStream is = socket.getInputStream(); | |
int readByteCount = is.read(byteArr); | |
String data = new String(byteArr, 0, readByteCount, "UTF-8"); | |
dataarr = data.split("/"); | |
System.out.println(data); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}; | |
socketthread.start(); | |
builder2.setTitle("예측된 음료수 목록") | |
.setItems(dataarr, new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
String nm = dataarr[which].split(" ")[0]; | |
JSONObject obj = js.findinjson(nm, "name", anddir + "/allbev.json"); //from allbev | |
try { | |
bev Bev = new bev(); | |
Bev.setIndex(Integer.parseInt(String.valueOf(obj.get("index")))); | |
Bev.setKcal(Float.parseFloat(String.valueOf(obj.get("kcal")))); | |
Bev.setSugar(Float.parseFloat(String.valueOf(obj.get("sugar")))); | |
Bev.setName(String.valueOf(obj.get("name"))); | |
Bev.setRepeat(Integer.parseInt(String.valueOf(obj.get("repeat")))); | |
lastbev = Bev.getName(); | |
lastbevrep = Bev.getRepeat(); | |
if(!changejson(nm, "name", Bev, true)){ | |
bev Bev2 = new bev(); | |
Bev2.setIndex(Bev.getIndex()); | |
Bev2.setKcal(Bev.getKcal() * 2.5); | |
Bev2.setName(Bev.getName()); | |
Bev2.setSugar(Bev.getSugar() * 2.5); | |
Bev2.setRepeat(Bev.getRepeat()); | |
js.json_save(jsondir + filename, Bev); | |
} | |
changejson(nm, "name", Bev, false); | |
todayindex++; | |
dataindex++; | |
userkcal_today += (float) Bev.getKcal() * 2.5; | |
usersugar_today += (float) Bev.getSugar() * 2.5; | |
datelastupdate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); | |
js.saveindex(todayindex, dataindex, userkcal_today, usersugar_today, datelastupdate); | |
Toast.makeText(getContext(), "저장 완료했습니다", Toast.LENGTH_SHORT).show(); | |
dialog.dismiss(); | |
dialog.dismiss(); | |
sendhandler.sendEmptyMessage(6); | |
}catch(JSONException e){ | |
e.printStackTrace(); | |
} | |
} | |
}) | |
.setPositiveButton("목록에 없음", new DialogInterface.OnClickListener(){ | |
@Override | |
public void onClick(DialogInterface dialog, int which){ | |
AlertDialog.Builder dataadd = new AlertDialog.Builder(getActivity()); | |
final EditText edit_kcal = alertaddview.findViewById(R.id.edit_kcal); | |
final EditText edit_sugar = alertaddview.findViewById(R.id.edit_sugar); | |
final EditText edit_name = alertaddview.findViewById(R.id.edit_name); | |
edit_kcal.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); | |
edit_sugar.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); | |
dataadd.setTitle("데이터 추가") | |
.setView(alertaddview); | |
AlertDialog addalert = dataadd.create(); | |
btn_addok.setOnClickListener(new Button.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
bev Bev = new bev(); | |
Bev.setIndex(dataindex); | |
Bev.setKcal(Float.parseFloat(edit_kcal.getText().toString())); | |
Bev.setSugar(Float.parseFloat(edit_sugar.getText().toString())); | |
Bev.setName(edit_name.getText().toString()); | |
lastbev = Bev.getName(); | |
Bev.setRepeat(0); | |
js.json_save(anddir + "/allbev.json", Bev); | |
Bev.setIndex(todayindex); | |
Bev.setKcal(Float.parseFloat(edit_kcal.getText().toString()) * 2.5); | |
Bev.setSugar(Float.parseFloat(edit_sugar.getText().toString()) * 2.5); | |
js.json_save(jsondir + filename, Bev); | |
todayindex++; | |
dataindex++; | |
userkcal_today += (float)Bev.getKcal(); | |
usersugar_today += (float)Bev.getSugar(); | |
datelastupdate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); | |
js.saveindex(todayindex, dataindex, userkcal_today, usersugar_today, datelastupdate); | |
Toast.makeText(getContext(), "저장 완료했습니다", Toast.LENGTH_SHORT).show(); | |
addalert.cancel(); | |
dialog.dismiss(); | |
sendhandler.sendEmptyMessage(5); | |
} | |
}); | |
btn_addcancel.setOnClickListener(new Button.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
Toast.makeText(getContext(), "저장 취소되었습니다", Toast.LENGTH_SHORT).show(); | |
addalert.cancel(); | |
} | |
}); | |
addalert.show(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
threadflag = false; | |
} | |
}) | |
.setCancelable(false); | |
AlertDialog alertdata = builder2.create(); | |
alertdata.show(); | |
} | |
void saveindex(int todayindex, int dataindex, Float kcal_today, Float sugar_today, String datelastupdate){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putInt("todayindex", todayindex); | |
edit.putInt("index", dataindex); | |
edit.putFloat("kcal_today", kcal_today); | |
edit.putFloat("sugar_today", sugar_today); | |
edit.putString("lastdate", datelastupdate); | |
edit.apply(); | |
} | |
JSONObject findinjson(String bevname, String find, String path){ | |
JSONObject searchObject = null; | |
String name; | |
JSONObject obj = loadJSON(path); | |
try { | |
JSONArray array = obj.getJSONArray("Beverages"); | |
for(int i = 0; i<array.length(); i++) { | |
JSONObject currobject = array.getJSONObject(i); | |
name = currobject.getString(find); | |
if(name.equals(bevname)){ | |
searchObject = currobject; | |
System.out.println("Found"); | |
break; | |
} | |
} | |
return searchObject; | |
}catch (JSONException e){ | |
e.printStackTrace(); | |
} | |
System.out.println("not found"); | |
return null; | |
} | |
boolean changejson(String bevname, String find, bev Bev, boolean bool){ | |
JSONObject searchObject = null; | |
String name; | |
if(bool) { //save for today json | |
JSONObject obj = loadJSON(jsondir + filename); | |
try { | |
JSONArray array = obj.getJSONArray("Beverages"); | |
for (int i = 0; i < array.length(); i++) { | |
JSONObject currobject = array.getJSONObject(i); | |
name = currobject.getString(find); | |
if (name.equals(bevname)) { | |
searchObject = currobject; | |
currobject.put("kcal", Float.parseFloat(String.valueOf(searchObject.get("kcal"))) + Bev.getKcal() * 2.5); | |
currobject.put("sugar", Float.parseFloat(String.valueOf(searchObject.get("sugar"))) + Bev.getSugar() * 2.5); | |
currobject.put("repeat", Integer.parseInt(String.valueOf(searchObject.get("repeat"))) + 1); | |
array.put(i, currobject); | |
obj.put("Beverages", array); | |
writeJsonFile(jsondir + filename, obj.toString()); | |
return true; | |
} | |
} | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
else{ | |
JSONObject obj = loadJSON(anddir + "/allbev.json"); | |
try { | |
JSONArray array = obj.getJSONArray("Beverages"); | |
for (int i = 0; i < array.length(); i++) { | |
JSONObject currobject = array.getJSONObject(i); | |
name = currobject.getString(find); | |
if (name.equals(bevname)) { | |
searchObject = currobject; | |
currobject.put("repeat", Integer.parseInt(String.valueOf(searchObject.get("repeat"))) + 1); | |
array.put(i, currobject); | |
obj.put("Beverages", array); | |
writeJsonFile(anddir + "/allbev.json", obj.toString()); | |
return true; | |
} | |
} | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
return false; | |
} | |
} | |
public class connectBT { | |
boolean bluetoothOn() { | |
if (BTAdapter == null) { | |
Toast.makeText(getContext(), "블루투스를 지원하지 않는 기기입니다.", Toast.LENGTH_SHORT).show(); | |
return false; | |
} else { | |
if (BTAdapter.isEnabled()) { | |
Toast.makeText(getContext(), "블루투스가 이미 활성화 되어 있습니다.", Toast.LENGTH_SHORT).show(); | |
return true; | |
} else { | |
Toast.makeText(getContext(), "블루투스 기능을 켭니다.", Toast.LENGTH_SHORT).show(); | |
Intent intentBluetoothEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); | |
getActivity().startActivityForResult(intentBluetoothEnable, BT_REQUEST_ENABLE); | |
return true; | |
} | |
} | |
} | |
void bluetoothOff() { | |
if (BTAdapter.isEnabled()) { | |
BTAdapter.disable(); | |
Toast.makeText(getContext(), "블루투스가 비활성화 되었습니다.", Toast.LENGTH_SHORT).show(); | |
} | |
else { | |
Toast.makeText(getContext(), "블루투스가 이미 비활성화 되어 있습니다.", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
void connectSelectedDevice(String selectedDeviceName) { | |
pairedDevices = BTAdapter.getBondedDevices(); | |
for (BluetoothDevice tempDevice : pairedDevices) { | |
if (selectedDeviceName.equals(tempDevice.getName())) { | |
BTdevice = tempDevice; | |
break; | |
} | |
} | |
try { | |
BTsocket = BTdevice.createRfcommSocketToServiceRecord(BT_UUID); | |
BTsocket.connect(); | |
connectBT.ConnectedBluetoothThread thread = new connectBT.ConnectedBluetoothThread(BTsocket); | |
thread.start(); | |
BTHandler.obtainMessage(BT_CONNECTING_STATUS, 1, -1).sendToTarget(); | |
btconnect = true; | |
} catch (IOException e) { | |
btconnect = false; | |
Toast.makeText(getContext(), "블루투스 연결 중 오류가 발생했습니다.", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
private class ConnectedBluetoothThread extends Thread { | |
private final BluetoothSocket mmSocket; | |
private final InputStream mmInStream; | |
private final OutputStream mmOutStream; | |
public ConnectedBluetoothThread(BluetoothSocket socket) { | |
mmSocket = socket; | |
InputStream tmpIn = null; | |
OutputStream tmpOut = null; | |
try { | |
tmpIn = socket.getInputStream(); | |
tmpOut = socket.getOutputStream(); | |
} catch (IOException e) { | |
Toast.makeText(getContext(), "소켓 연결 중 오류가 발생했습니다.", Toast.LENGTH_SHORT).show(); | |
} | |
mmInStream = tmpIn; | |
mmOutStream = tmpOut; | |
float pct = (userkcal_today/userkcal)*100; | |
if(pct <= 70) write("2"); | |
else write("0"); | |
} | |
public void run() { | |
byte[] buffer = new byte[26]; | |
int bytes; | |
while (true) { | |
try { | |
bytes = mmInStream.available(); | |
if (bytes != 0) { | |
SystemClock.sleep(100); | |
bytes = mmInStream.available(); | |
bytes = mmInStream.read(buffer, 0, bytes); | |
BTHandler.obtainMessage(BT_MESSAGE_READ, bytes, -1, buffer).sendToTarget(); | |
} | |
} catch (IOException e) { | |
break; | |
} | |
} | |
} | |
public void write(String str) { | |
byte[] bytes = str.getBytes(); | |
try { | |
mmOutStream.write(bytes); | |
} catch (IOException e) { | |
Toast.makeText(getContext(), "데이터 전송 중 오류가 발생했습니다.", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
public void cancel() { | |
try { | |
mmSocket.close(); | |
} catch (IOException e) { | |
Toast.makeText(getContext().getApplicationContext(), "소켓 해제 중 오류가 발생했습니다.", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
} | |
} | |
} |
package com.example.gradproject2020; | |
import android.util.Log; | |
import org.apache.commons.net.ftp.FTP; | |
import org.apache.commons.net.ftp.FTPClient; | |
import org.apache.commons.net.ftp.FTPFile; | |
import org.apache.commons.net.ftp.FTPReply; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
public class ConnectFTP { | |
private final String TAG = "Connect FTP"; | |
public FTPClient mFTPClient = null; | |
public ConnectFTP(){ | |
mFTPClient = new FTPClient(); | |
} | |
public boolean ftpConnect(String host, String username, String password, int port) { | |
boolean result = false; | |
try{ | |
mFTPClient.connect(host, port); | |
if(FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { | |
result = mFTPClient.login(username, password); | |
mFTPClient.enterLocalPassiveMode(); | |
} | |
}catch (Exception e){ | |
Log.d(TAG, "Couldn't connect to host"); | |
} | |
return result; | |
} | |
public boolean ftpDisconnect() { | |
boolean result = false; | |
try { | |
mFTPClient.logout(); | |
mFTPClient.disconnect(); | |
result = true; | |
} catch (Exception e) { | |
Log.d(TAG, "Failed to disconnect with server"); | |
} | |
return result; | |
} | |
public String ftpGetDirectory(){ | |
String directory = null; | |
try{ | |
directory = mFTPClient.printWorkingDirectory(); | |
} catch (Exception e){ | |
Log.d(TAG, "Couldn't get current directory"); | |
} | |
return directory; | |
} | |
public boolean ftpChangeDirctory(String directory) { | |
try{ | |
mFTPClient.changeWorkingDirectory(directory); | |
return true; | |
}catch (Exception e){ | |
Log.d(TAG, "Couldn't change the directory"); | |
} | |
return false; | |
} | |
public String[] ftpGetFileList(String directory) { | |
String[] fileList = null; | |
int i = 0; | |
try { | |
FTPFile[] ftpFiles = mFTPClient.listFiles(directory); | |
fileList = new String[ftpFiles.length]; | |
for(FTPFile file : ftpFiles) { | |
String fileName = file.getName(); | |
if (file.isFile()) { | |
fileList[i] = "(File) " + fileName; | |
} else { | |
fileList[i] = "(Directory) " + fileName; | |
} | |
i++; | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return fileList; | |
} | |
public boolean ftpCreateDirectory(String directory) { | |
boolean result = false; | |
try { | |
result = mFTPClient.makeDirectory(directory); | |
} catch (Exception e){ | |
Log.d(TAG, "Couldn't make the directory"); | |
} | |
return result; | |
} | |
public boolean ftpDeleteDirectory(String directory) { | |
boolean result = false; | |
try { | |
result = mFTPClient.removeDirectory(directory); | |
} catch (Exception e) { | |
Log.d(TAG, "Couldn't remove directory"); | |
} | |
return result; | |
} | |
public boolean ftpDeleteFile(String file) { | |
boolean result = false; | |
try{ | |
result = mFTPClient.deleteFile(file); | |
} catch (Exception e) { | |
Log.d(TAG, "Couldn't remove the file"); | |
} | |
return result; | |
} | |
public boolean ftpRenameFile(String from, String to) { | |
boolean result = false; | |
try { | |
result = mFTPClient.rename(from, to); | |
} catch (Exception e) { | |
Log.d(TAG, "Couldn't rename file"); | |
} | |
return result; | |
} | |
public boolean ftpDownloadFile(String srcFilePath, String desFilePath) { | |
boolean result = false; | |
try{ | |
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); | |
mFTPClient.setFileTransferMode(FTP.BINARY_FILE_TYPE); | |
FileOutputStream fos = new FileOutputStream(desFilePath); | |
result = mFTPClient.retrieveFile(srcFilePath, fos); | |
fos.close(); | |
} catch (Exception e){ | |
Log.d(TAG, "Download failed"); | |
} | |
return result; | |
} | |
public boolean ftpUploadFile(String srcFilePath, String desFileName, String desDirectory) { | |
boolean result = false; | |
try { | |
FileInputStream fis = new FileInputStream(srcFilePath); | |
if(ftpChangeDirctory(desDirectory)) { | |
result = mFTPClient.storeFile(desFileName, fis); | |
} | |
fis.close(); | |
} catch(Exception e){ | |
Log.d(TAG, "Couldn't upload the file"); | |
} | |
return result; | |
} | |
} |
package com.example.gradproject2020; | |
import android.os.Bundle; | |
public interface FragmentCallback { | |
void onChangedFragment(int position, Bundle bundle); | |
} |
package com.example.gradproject2020; | |
import androidx.appcompat.app.AppCompatActivity; | |
import android.content.Intent; | |
import android.content.res.Resources; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.os.Looper; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import com.bumptech.glide.Glide; | |
public class LoadingScreen extends AppCompatActivity { | |
//class for function call | |
private ConnectFTP ConnectFTP; | |
Resources res; | |
//flags | |
int quitflag = 0; | |
//directions | |
String cpudir, anddir; | |
//etc resources | |
TextView txt_loading; | |
ImageView img_loading1, img_loading2; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_loading_screen); | |
ConnectFTP = new ConnectFTP(); | |
res = getResources(); | |
txt_loading = findViewById(R.id.txt_loading); | |
img_loading1 = findViewById(R.id.img_loading1); | |
img_loading2 = findViewById(R.id.img_loading2); | |
anddir = getIntent().getStringExtra("anddir"); | |
Glide.with(this).load(R.drawable.loadingscreen).into(img_loading1); | |
Glide.with(this).load(R.drawable.loading2).into(img_loading2); | |
Loadingh5(); | |
} | |
private void Loadingh5(){ | |
new Thread(new Runnable() { | |
@Override | |
public void run() {/* | |
txt_loading.setText("서버에 연결 중..."); | |
if(!ConnectFTP.ftpConnect("114.70.22.242", "ubuntu", "wjswk!105", 21)){ | |
txt_loading.setText("연결에 실패했습니다."); | |
quitflag = 1; | |
Loading(); | |
} | |
cpudir = ConnectFTP.ftpGetDirectory() + "/L1105/CJY/gradproj"; //컴퓨터 | |
txt_loading.setText("데이터 업데이트 중..."); | |
if(!ConnectFTP.ftpDownloadFile(cpudir+"/model.h5", anddir+"/model.h5")){ | |
txt_loading.setText("파일 다운로드에 실패했습니다."); | |
quitflag = 1; | |
Loading(); | |
} | |
*/ | |
txt_loading.setText("로딩 완료"); | |
Loading(); | |
} | |
}).start(); | |
} | |
private void Loading(){ | |
Handler handler = new Handler(Looper.getMainLooper()); | |
handler.postDelayed(new Runnable(){ | |
@Override | |
public void run(){ | |
Intent Scr_main = new Intent(); | |
Scr_main.putExtra("quitflag", quitflag); | |
setResult(RESULT_OK, Scr_main); | |
finish(); | |
} | |
}, 2000); | |
} | |
} |
package com.example.gradproject2020; | |
import androidx.annotation.NonNull; | |
import androidx.annotation.Nullable; | |
import androidx.appcompat.app.ActionBarDrawerToggle; | |
import androidx.appcompat.app.AppCompatActivity; | |
import androidx.appcompat.widget.Toolbar; | |
import androidx.core.app.ActivityCompat; | |
import androidx.core.view.GravityCompat; | |
import androidx.drawerlayout.widget.DrawerLayout; | |
import androidx.fragment.app.Fragment; | |
import androidx.fragment.app.FragmentManager; | |
import androidx.fragment.app.FragmentTransaction; | |
import android.Manifest; | |
import android.app.AlertDialog; | |
import android.content.DialogInterface; | |
import android.content.Intent; | |
import android.content.SharedPreferences; | |
import android.content.pm.PackageManager; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.text.InputType; | |
import android.view.Menu; | |
import android.view.MenuItem; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.bumptech.glide.Glide; | |
import com.google.android.material.navigation.NavigationView; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.ResourceBundle; | |
public class MainActivity extends AppCompatActivity implements FragmentCallback{ | |
//sources | |
Intent Scr_Loading; | |
Toolbar toolbar; | |
Fragment frg_main, frg_BT, frg_result, frg_setting; | |
DrawerLayout drawer; | |
NavigationView navigationView; | |
//request code for Intents | |
final int req_Loading = 0; | |
//flags | |
int quitflag = 0; //1: force quit (fail to load FTP) | |
boolean backflag = false; //back button flag | |
//directions | |
String anddir; //android folder direction | |
//etc resources | |
TextView nav_name, nav_txt_kcalpct; | |
String username; | |
pref Pref; | |
float userkcal, userkcal_today, usersugar, usersugar_today;; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
toolbar = findViewById(R.id.toolbar); | |
setSupportActionBar(toolbar); | |
getSupportActionBar().setTitle(null); | |
drawer = findViewById(R.id.drawer_layout); | |
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( | |
this, drawer, toolbar, R.string.blank, R.string.blank); | |
drawer.addDrawerListener(toggle); | |
toggle.syncState(); | |
Pref = new pref(); | |
Pref.load_pref(); | |
frg_main = new MainScreen(); | |
frg_BT = new BTScreen(); | |
frg_result = new ResultScreen(); | |
frg_setting = new SettingScreen(); | |
FragmentManager fm = getSupportFragmentManager(); | |
FragmentTransaction fragmentTransaction = fm.beginTransaction(); | |
fragmentTransaction.add(R.id.frg_border, frg_main); | |
fragmentTransaction.commit(); | |
anddir = MainActivity.this.getExternalFilesDir("/resources").getAbsolutePath(); //폰 | |
Scr_Loading = new Intent(this, LoadingScreen.class); | |
Scr_Loading.putExtra("anddir", anddir); | |
startActivityForResult(Scr_Loading, req_Loading); | |
navigationView = findViewById(R.id.nav_view); | |
View navView = navigationView.getHeaderView(0); | |
nav_name = navView.findViewById(R.id.nav_txt_name); | |
nav_txt_kcalpct = navView.findViewById(R.id.nav_txt_kcalpct); | |
nav_name.setText(username); | |
float pct = (userkcal_today/userkcal)*100; | |
nav_txt_kcalpct.setText(String.valueOf(pct)); | |
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { | |
@Override | |
public boolean onNavigationItemSelected(@NonNull MenuItem item) { | |
switch (item.getItemId()) { | |
case R.id.nav_main: | |
onChangedFragment(1, null); | |
break; | |
case R.id.nav_blt: | |
onChangedFragment(2, null); | |
break; | |
case R.id.nav_result: | |
onChangedFragment(3, null); | |
break; | |
case R.id.nav_setting: | |
onChangedFragment(4, null); | |
break; | |
case R.id.nav_reset: | |
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); | |
alert.setTitle("저장된 json 데이터를 삭제하시겠습니까?") | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
String p = MainActivity.this.getExternalFilesDir("/json").getAbsolutePath(); | |
Pref.deletepath(p); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert.create(); | |
alertDialog.show(); | |
break; | |
} | |
DrawerLayout drawer = findViewById(R.id.drawer_layout); | |
drawer.closeDrawer(GravityCompat.START); | |
return true; | |
} | |
}); | |
} | |
@Override | |
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){ | |
super.onActivityResult(requestCode, resultCode, data); | |
if(requestCode == req_Loading){ | |
quitflag = data.getIntExtra("quitflag", quitflag); | |
if(quitflag == 1){ | |
finishAffinity(); | |
System.runFinalization(); | |
System.exit(0); | |
finish(); | |
} | |
} | |
} | |
@Override | |
public void onBackPressed() { | |
DrawerLayout drawer = findViewById(R.id.drawer_layout); | |
if (drawer.isDrawerOpen(GravityCompat.START)) { | |
drawer.closeDrawer(GravityCompat.START); | |
} else { | |
if(backflag){ | |
super.onBackPressed(); | |
finishAffinity(); | |
System.runFinalization(); | |
System.exit(0); | |
finish(); | |
} | |
backflag = true; | |
Toast.makeText(MainActivity.this,"뒤로가기를 한번 더 누르면 종료됩니다", Toast.LENGTH_SHORT).show(); | |
new Handler().postDelayed(new Runnable(){ | |
@Override | |
public void run(){ | |
backflag = false; | |
} | |
}, 2000); | |
} | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
getMenuInflater().inflate(R.menu.navi_menu, menu); | |
return true; | |
} | |
@Override | |
public void onChangedFragment(int position, Bundle bundle) { | |
Fragment fragment = null; | |
switch (position){ | |
case 1: | |
fragment = frg_main; | |
break; | |
case 2: | |
fragment = frg_BT; | |
break; | |
case 3: | |
fragment = frg_result; | |
break; | |
case 4: | |
fragment = frg_setting; | |
break; | |
default: | |
break; | |
} | |
FragmentManager fm = getSupportFragmentManager(); | |
FragmentTransaction fragmentTransaction = fm.beginTransaction(); | |
fragmentTransaction.replace(R.id.frg_border, fragment); | |
fragmentTransaction.commit(); | |
} | |
public void checkPermission(){ | |
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ | |
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); | |
} | |
} | |
void WriteFile(String filen, String content){ | |
File dir = MainActivity.this.getExternalFilesDir("/json"); | |
try{ | |
BufferedWriter writer = new BufferedWriter(new FileWriter(dir.getAbsolutePath()+"/"+filen+".json", true)); | |
writer.write(content); | |
writer.close(); | |
}catch(IOException e){ | |
e.printStackTrace(); | |
} | |
} | |
class pref{ | |
void load_pref(){ | |
SharedPreferences data_personal = getSharedPreferences("data_personal", MODE_PRIVATE); | |
username = data_personal.getString("name", "김건국"); | |
userkcal = data_personal.getFloat("kcal", 1500); | |
userkcal_today = data_personal.getFloat("kcal_today", 1000); | |
usersugar = data_personal.getFloat("sugar", 30); | |
usersugar_today = data_personal.getFloat("sugar_today", 10); | |
} | |
void deletepath(String path){ | |
File dir = new File(path); | |
File[] childFileList = dir.listFiles(); | |
if(dir.exists()){ | |
for(File childFile : childFileList){ | |
if(childFile.isDirectory()){ | |
deletepath(childFile.getAbsolutePath()); | |
} | |
else{ | |
childFile.delete(); | |
} | |
} | |
} | |
} | |
} | |
} |
package com.example.gradproject2020; | |
import androidx.fragment.app.Fragment; | |
import android.content.Context; | |
import android.content.SharedPreferences; | |
import android.os.Bundle; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import com.bumptech.glide.Glide; | |
import com.github.mikephil.charting.charts.PieChart; | |
import com.github.mikephil.charting.components.Description; | |
import com.github.mikephil.charting.components.MarkerView; | |
import com.github.mikephil.charting.data.Entry; | |
import com.github.mikephil.charting.data.PieData; | |
import com.github.mikephil.charting.data.PieDataSet; | |
import com.github.mikephil.charting.data.PieEntry; | |
import com.github.mikephil.charting.highlight.Highlight; | |
import com.github.mikephil.charting.utils.ColorTemplate; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.BufferedReader; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileReader; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.text.SimpleDateFormat; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import static android.content.Context.MODE_PRIVATE; | |
public class MainScreen extends Fragment { | |
//function | |
pref Pref; | |
View view; | |
ImageView img_sugar; | |
TextView txt_sugar, txt_pct; | |
Button btn_graph; | |
float pct; | |
//variables | |
String username, datelastupdate; | |
float userkcal, userkcal_today, usersugar, usersugar_today; | |
String jsondir; //android folder direction | |
String filename; //android .json file name | |
boolean graphflag = false; //false: sugar, true: kcal | |
int dataindex = 0, todayindex = 0; | |
public MainScreen() { | |
//empty constructor | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
view = inflater.inflate(R.layout.activity_main_screen, container, false); | |
View marker = inflater.inflate(R.layout.tvcontent, container, false); | |
TextView tvContent = marker.findViewById(R.id.tvContent); | |
String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); | |
Pref = new pref(); | |
Pref.load_pref(); | |
if (!now.equals(datelastupdate)) { | |
todayindex = 0; | |
Pref.change_date(); | |
} | |
/* | |
//for debugging reset | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putInt("todayindex", 0); | |
edit.putInt("index", 0); | |
edit.putFloat("kcal_today", 0); | |
edit.putFloat("sugar_today", 0); | |
edit.putString("lastdate", "1970-01-01"); | |
edit.apply(); | |
*/ | |
jsondir = getContext().getExternalFilesDir("/json").getAbsolutePath(); //폰 | |
filename = "/" + now + ".json"; | |
img_sugar = view.findViewById(R.id.img_sugar); | |
txt_sugar = view.findViewById(R.id.txt_sugar); | |
btn_graph = view.findViewById(R.id.btn_graph); | |
txt_pct = view.findViewById(R.id.txt_pct); | |
PieChart chart = view.findViewById(R.id.chart); | |
Description description = new Description(); | |
description.setTextSize(15); | |
ArrayList<PieEntry> array_kcal = new ArrayList<PieEntry>(); | |
array_kcal = Pref.load_today(); | |
ArrayList<PieEntry> array_sugar = new ArrayList<PieEntry>(); | |
array_sugar = Pref.load_sugar(); | |
PieDataSet dataset_kcal = new PieDataSet(array_kcal, "kcal"); | |
dataset_kcal.setColors(ColorTemplate.PASTEL_COLORS); | |
PieDataSet dataset_sugar = new PieDataSet(array_sugar, "sugar"); | |
dataset_sugar.setColors(ColorTemplate.PASTEL_COLORS); | |
PieData data_kcal = new PieData((dataset_kcal)); | |
PieData data_sugar = new PieData((dataset_sugar)); | |
description.setText("오늘 섭취 칼로리"); //라벨 | |
chart.setDescription(description); | |
chart.setData(data_kcal); | |
chart.setTouchEnabled(true); | |
pct = (userkcal_today / userkcal) * 100; | |
txt_pct.setText(Float.toString(userkcal_today) + " kcal / " + Float.toString(userkcal) + " kcal, " + pct + "% 섭취"); | |
if (pct <= 50) { | |
Glide.with(getContext()).load(R.drawable.icon_smile).into(img_sugar); | |
txt_sugar.setText("열량 섭취량이 적당해요"); | |
} else if (pct >= 50 && pct <= 100) { | |
Glide.with(getContext()).load(R.drawable.icon_neut).into(img_sugar); | |
txt_sugar.setText("열량 섭취량이 보통이에요"); | |
} else { | |
Glide.with(getContext()).load(R.drawable.icon_bad).into(img_sugar); | |
txt_sugar.setText("열량 섭취량이 위험해요"); | |
} | |
btn_graph.setOnClickListener(new Button.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
if (!graphflag) { | |
pct = (userkcal_today / userkcal) * 100; | |
if (pct <= 50) { | |
Glide.with(getContext()).load(R.drawable.icon_smile).into(img_sugar); | |
txt_sugar.setText("열량 섭취량이 적당해요"); | |
} else if (pct >= 50 && pct <= 100) { | |
Glide.with(getContext()).load(R.drawable.icon_neut).into(img_sugar); | |
txt_sugar.setText("열량 섭취량이 보통이에요"); | |
} else { | |
Glide.with(getContext()).load(R.drawable.icon_bad).into(img_sugar); | |
txt_sugar.setText("열량 섭취량이 위험해요"); | |
} | |
description.setText("오늘 섭취 칼로리"); //라벨 | |
chart.setDescription(description); | |
chart.setData(data_kcal); | |
chart.setTouchEnabled(true); | |
chart.invalidate(); | |
btn_graph.setText("당분 그래프 확인"); | |
txt_pct.setText(Float.toString(userkcal_today) + " kcal / " + Float.toString(userkcal) + " kcal, " + pct + "% 섭취"); | |
graphflag = true; | |
} else { | |
float pct = (usersugar_today / usersugar) * 100; | |
if (pct <= 50) { | |
Glide.with(getContext()).load(R.drawable.icon_smile).into(img_sugar); | |
txt_sugar.setText("적당량의 당분을 먹고 있어요"); | |
} else if (pct >= 50 && pct <= 100) { | |
Glide.with(getContext()).load(R.drawable.icon_neut).into(img_sugar); | |
txt_sugar.setText("당분 섭취를 가급적 자제하세요"); | |
} else { | |
Glide.with(getContext()).load(R.drawable.icon_bad).into(img_sugar); | |
txt_sugar.setText("당분 섭취를 줄이세요"); | |
} | |
description.setText("오늘 섭취 당분"); //라벨 | |
chart.setDescription(description); | |
chart.setData(data_sugar); | |
chart.setTouchEnabled(true); | |
chart.invalidate(); | |
btn_graph.setText("열량 그래프 확인"); | |
txt_pct.setText(Float.toString(usersugar_today) + " g / " + Float.toString(usersugar) + " g, " + pct + "% 섭취"); | |
graphflag = false; | |
} | |
} | |
}); | |
return view; | |
} | |
class pref { | |
void load_pref() { | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
username = data_personal.getString("name", "김건국"); | |
userkcal = data_personal.getFloat("kcal", 1500); | |
userkcal_today = data_personal.getFloat("kcal_today", 0); | |
usersugar = data_personal.getFloat("sugar", 30); | |
usersugar_today = data_personal.getFloat("sugar_today", 0); | |
datelastupdate = data_personal.getString("lastdate", "1970-01-01"); | |
dataindex = data_personal.getInt("index", 0); | |
todayindex = data_personal.getInt("todayindex", 0); | |
} | |
void change_date(){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
float temp_k, temp_s; | |
temp_k = data_personal.getFloat("kcal_6", 0); | |
edit.putFloat("kcal_7", temp_k); | |
temp_k = data_personal.getFloat("kcal_5", 0); | |
edit.putFloat("kcal_6", temp_k); | |
temp_k = data_personal.getFloat("kcal_4", 0); | |
edit.putFloat("kcal_5", temp_k); | |
temp_k = data_personal.getFloat("kcal_3", 0); | |
edit.putFloat("kcal_4", temp_k); | |
temp_k = data_personal.getFloat("kcal_2", 0); | |
edit.putFloat("kcal_3", temp_k); | |
temp_k = data_personal.getFloat("kcal_1", 0); | |
edit.putFloat("kcal_2", temp_k); | |
temp_k = data_personal.getFloat("kcal_today", 0); | |
edit.putFloat("kcal_1", temp_k); | |
edit.putFloat("kcal_today", 0); | |
temp_s = data_personal.getFloat("sugar_6", 0); | |
edit.putFloat("sugar_7", temp_s); | |
temp_s = data_personal.getFloat("sugar_5", 0); | |
edit.putFloat("sugar_6", temp_s); | |
temp_s = data_personal.getFloat("sugar_4", 0); | |
edit.putFloat("sugar_5", temp_s); | |
temp_s = data_personal.getFloat("sugar_3", 0); | |
edit.putFloat("sugar_4", temp_s); | |
temp_s = data_personal.getFloat("sugar_2", 0); | |
edit.putFloat("sugar_3", temp_s); | |
temp_s = data_personal.getFloat("sugar_1", 0); | |
edit.putFloat("sugar_2", temp_s); | |
temp_k = data_personal.getFloat("sugar_today", 0); | |
edit.putFloat("sugar_1", temp_k); | |
edit.putFloat("sugar_today", 0); | |
userkcal_today = 0; | |
usersugar_today = 0; | |
} | |
public JSONObject loadJSON(String path) { | |
try { | |
File jsonfile = new File(path); | |
if (!jsonfile.exists()) { | |
JSONArray tempary = new JSONArray(); | |
JSONObject tempobj = new JSONObject(); | |
try { | |
tempobj.put("Beverages", tempary); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
String str = tempobj.toString(); | |
FileWriter filewriter = new FileWriter(jsonfile); | |
BufferedWriter bufferedWriter = new BufferedWriter(filewriter); | |
bufferedWriter.write(str); | |
bufferedWriter.close(); | |
} | |
FileReader filereader = new FileReader(jsonfile); | |
BufferedReader bufferedReader = new BufferedReader(filereader); | |
StringBuilder stringBuilder = new StringBuilder(); | |
String line = bufferedReader.readLine(); | |
while (line != null) { | |
stringBuilder.append(line).append("\n"); | |
line = bufferedReader.readLine(); | |
} | |
bufferedReader.close(); | |
String responce = stringBuilder.toString(); | |
try { | |
JSONObject obj = new JSONObject(responce); | |
return obj; | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
ArrayList<PieEntry> load_today() { | |
ArrayList<PieEntry> arr = new ArrayList<>(); | |
try { | |
JSONObject jsonObject = loadJSON(jsondir + filename); | |
JSONArray array = jsonObject.getJSONArray("Beverages"); | |
for (int i = 0; i < array.length(); i++) { | |
JSONObject object = array.getJSONObject(i); | |
arr.add(new PieEntry(Float.parseFloat(String.valueOf(object.get("kcal"))), String.valueOf(object.get("name")))); | |
} | |
} catch (JSONException e) { | |
//e.printStackTrace(); | |
arr.add(new PieEntry(1, "Null")); | |
} | |
return arr; | |
} | |
ArrayList<PieEntry> load_sugar() { | |
ArrayList<PieEntry> arr = new ArrayList<>(); | |
try { | |
JSONObject jsonObject = loadJSON(jsondir + filename); | |
JSONArray array = jsonObject.getJSONArray("Beverages"); | |
for (int i = 0; i < array.length(); i++) { | |
JSONObject object = array.getJSONObject(i); | |
arr.add(new PieEntry(Float.parseFloat(String.valueOf(object.get("sugar"))), String.valueOf(object.get("name")))); | |
} | |
} catch (JSONException e) { | |
//e.printStackTrace(); | |
arr.add(new PieEntry(1, "Null")); | |
} | |
return arr; | |
} | |
} | |
} |
package com.example.gradproject2020; | |
import androidx.annotation.NonNull; | |
import androidx.fragment.app.Fragment; | |
import android.app.AlertDialog; | |
import android.content.SharedPreferences; | |
import android.graphics.Color; | |
import android.os.Bundle; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.Toast; | |
import com.github.mikephil.charting.charts.BarChart; | |
import com.github.mikephil.charting.charts.PieChart; | |
import com.github.mikephil.charting.components.Description; | |
import com.github.mikephil.charting.data.BarData; | |
import com.github.mikephil.charting.data.BarDataSet; | |
import com.github.mikephil.charting.data.BarEntry; | |
import com.github.mikephil.charting.data.PieData; | |
import com.github.mikephil.charting.data.PieDataSet; | |
import com.github.mikephil.charting.data.PieEntry; | |
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet; | |
import com.github.mikephil.charting.utils.ColorTemplate; | |
import com.prolificinteractive.materialcalendarview.CalendarDay; | |
import com.prolificinteractive.materialcalendarview.DayViewDecorator; | |
import com.prolificinteractive.materialcalendarview.DayViewFacade; | |
import com.prolificinteractive.materialcalendarview.MaterialCalendarView; | |
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; | |
import com.prolificinteractive.materialcalendarview.spans.DotSpan; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.BufferedReader; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileReader; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.text.DateFormat; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.ArrayList; | |
import java.util.Calendar; | |
import java.util.Collection; | |
import java.util.Date; | |
import java.util.HashSet; | |
import static android.content.Context.MODE_PRIVATE; | |
public class ResultScreen extends Fragment { | |
View view, alert_graph; | |
String jsondir; //android folder direction | |
String filename; //android .json file name | |
Load load; | |
Button btn_chart, btn_graph; | |
PieChart piechart; | |
MaterialCalendarView materialCalendarView; | |
ArrayList<PieEntry> array_kcal_p, array_sugar_p; | |
float day7_s, day6_s, day5_s, day4_s, day3_s, day2_s, day1_s, today_s; | |
float day7_k, day6_k, day5_k, day4_k, day3_k, day2_k, day1_k, today_k; | |
Button btn_ok; | |
boolean graphflag = false, alertgraphflag = false; | |
public ResultScreen() { | |
//empty constructor | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
view = inflater.inflate(R.layout.activity_result_screen, container, false); | |
alert_graph = inflater.inflate(R.layout.alert_graph, container, false); | |
materialCalendarView = view.findViewById(R.id.calendarView); | |
btn_graph = alert_graph.findViewById(R.id.btn_graph1); | |
btn_ok = alert_graph.findViewById(R.id.btn_ok1); | |
btn_chart = view.findViewById(R.id.btn_chart); | |
piechart = alert_graph.findViewById(R.id.chartview); | |
BarChart chart = view.findViewById(R.id.chartview); | |
jsondir = getContext().getExternalFilesDir("/json").getAbsolutePath(); //폰 | |
final DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); | |
load = new Load(); | |
load.load_weekly(); | |
day5_k = (float)1423.8; | |
day6_k = (float)1017.1; | |
day3_k = (float)1658.7; | |
day2_k = (float)1514.2; | |
day1_k = (float)1217.7; | |
day5_s = (float)346.8; | |
day6_s = (float)457.1; | |
day3_s = (float)131.1; | |
day2_s = (float)134.8; | |
day1_s = (float)589.4; | |
Description description = new Description(); | |
description.setTextSize(15); | |
ArrayList<BarEntry> array_kcal = new ArrayList<BarEntry>(); | |
array_kcal = load.load_kcal(); | |
ArrayList<BarEntry> array_sugar = new ArrayList<BarEntry>(); | |
array_sugar = load.load_sugar(); | |
BarDataSet dataset_kcal = new BarDataSet(array_kcal, "kcal"); | |
dataset_kcal.setColors(ColorTemplate.PASTEL_COLORS); | |
BarDataSet dataset_sugar = new BarDataSet(array_sugar, "sugar"); | |
dataset_sugar.setColors(ColorTemplate.PASTEL_COLORS); | |
BarData data_kcal = new BarData((dataset_kcal)); | |
BarData data_sugar = new BarData((dataset_sugar)); | |
data_kcal.setBarWidth(1f); | |
data_sugar.setBarWidth(1f); | |
description.setText("일주일간 섭취 칼로리"); | |
chart.setDescription(description); | |
chart.setData(data_kcal); | |
chart.setTouchEnabled(true); | |
ArrayList<CalendarDay> array = load.getdates(); | |
materialCalendarView.addDecorators(new EventDecorator(Color.RED, array)); | |
btn_chart.setOnClickListener(new Button.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
if (graphflag) { | |
description.setText("일주일간 섭취 칼로리"); //라벨 | |
chart.setDescription(description); | |
chart.setData(data_kcal); | |
chart.setTouchEnabled(true); | |
chart.invalidate(); | |
btn_chart.setText("당분 그래프 확인"); | |
graphflag = false; | |
} else { | |
description.setText("일주일간 섭취 당분"); //라벨 | |
chart.setDescription(description); | |
chart.setData(data_sugar); | |
chart.setTouchEnabled(true); | |
chart.invalidate(); | |
btn_chart.setText("열량 그래프 확인"); | |
graphflag = true; | |
} | |
} | |
}); | |
materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() { | |
@Override | |
public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) { | |
String dat = FORMATTER.format(date.getDate()); | |
File jsonfile = new File(jsondir + "/" + dat + ".json"); | |
if (!jsonfile.exists()) { | |
Toast.makeText(getContext(), "해당 날짜의 자료가 존재하지 않습니다", Toast.LENGTH_SHORT).show(); | |
} else { | |
ArrayList<PieEntry> array_kcal_p = new ArrayList<PieEntry>(); | |
array_kcal_p = load.load_kcal_pi(jsondir + "/" + dat + ".json"); | |
ArrayList<PieEntry> array_sugar_p = new ArrayList<PieEntry>(); | |
array_sugar_p = load.load_sugar_pi(jsondir + "/" + dat + ".json"); | |
PieDataSet dataset_kcal_p = new PieDataSet(array_kcal_p, "kcal"); | |
dataset_kcal_p.setColors(ColorTemplate.PASTEL_COLORS); | |
PieDataSet dataset_sugar_p = new PieDataSet(array_sugar_p, "sugar"); | |
dataset_sugar_p.setColors(ColorTemplate.PASTEL_COLORS); | |
PieData data_kcal_p = new PieData((dataset_kcal_p)); | |
PieData data_sugar_p = new PieData((dataset_sugar_p)); | |
description.setText("오늘 섭취 칼로리"); //라벨 | |
piechart.setDescription(description); | |
piechart.setData(data_kcal_p); | |
piechart.setTouchEnabled(true); | |
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); | |
if (alert_graph.getParent() != null) | |
((ViewGroup) alert_graph.getParent()).removeView(alert_graph); | |
builder.setView(alert_graph) | |
.setCancelable(false); | |
AlertDialog alert = builder.create(); | |
btn_graph.setOnClickListener(new Button.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
if(alertgraphflag){ | |
description.setText("섭취 칼로리"); //라벨 | |
btn_graph.setText("당분 보기"); | |
piechart.setDescription(description); | |
piechart.setData(data_kcal_p); | |
piechart.setTouchEnabled(true); | |
piechart.invalidate(); | |
alertgraphflag = false; | |
} | |
else{ | |
description.setText("섭취 당분"); //라벨 | |
btn_graph.setText("칼로리 보기"); | |
piechart.setDescription(description); | |
piechart.setData(data_sugar_p); | |
piechart.setTouchEnabled(true); | |
piechart.invalidate(); | |
alertgraphflag = true; | |
} | |
} | |
}); | |
btn_ok.setOnClickListener(new Button.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
alert.cancel(); | |
} | |
}); | |
alert.show(); | |
} | |
if (date == null) { | |
System.out.println("no selection"); | |
} | |
} | |
}); | |
materialCalendarView.addDecorators(); | |
return view; | |
} | |
class Load { | |
void load_weekly() { | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
day7_k = data_personal.getFloat("kcal_7", 0); | |
day6_k = data_personal.getFloat("kcal_6", 0); | |
day5_k = data_personal.getFloat("kcal_5", 0); | |
day4_k = data_personal.getFloat("kcal_4", 0); | |
day3_k = data_personal.getFloat("kcal_3", 0); | |
day2_k = data_personal.getFloat("kcal_2", 0); | |
day1_k = data_personal.getFloat("kcal_1", 0); | |
today_k = data_personal.getFloat("kcal_today", 0); | |
day7_s = data_personal.getFloat("sugar_7", 0); | |
day6_s = data_personal.getFloat("sugar_6", 0); | |
day5_s = data_personal.getFloat("sugar_5", 0); | |
day4_s = data_personal.getFloat("sugar_4", 0); | |
day3_s = data_personal.getFloat("sugar_3", 0); | |
day2_s = data_personal.getFloat("sugar_2", 0); | |
day1_s = data_personal.getFloat("sugar_1", 0); | |
today_s = data_personal.getFloat("sugar_today", 0); | |
} | |
ArrayList<BarEntry> load_kcal() { | |
ArrayList<BarEntry> arr = new ArrayList<>(); | |
arr.add(new BarEntry(0, day7_k)); | |
arr.add(new BarEntry(1, day6_k)); | |
arr.add(new BarEntry(2, day5_k)); | |
arr.add(new BarEntry(3, day4_k)); | |
arr.add(new BarEntry(4, day3_k)); | |
arr.add(new BarEntry(5, day2_k)); | |
arr.add(new BarEntry(6, day1_k)); | |
arr.add(new BarEntry(7, today_k)); | |
return arr; | |
} | |
ArrayList<BarEntry> load_sugar() { | |
ArrayList<BarEntry> arr = new ArrayList<>(); | |
arr.add(new BarEntry(0, day7_s)); | |
arr.add(new BarEntry(1, day6_s)); | |
arr.add(new BarEntry(2, day5_s)); | |
arr.add(new BarEntry(3, day4_s)); | |
arr.add(new BarEntry(4, day3_s)); | |
arr.add(new BarEntry(5, day2_s)); | |
arr.add(new BarEntry(6, day1_s)); | |
arr.add(new BarEntry(7, today_s)); | |
return arr; | |
} | |
ArrayList<CalendarDay> getdates() { | |
ArrayList<CalendarDay> arr = new ArrayList<>(); | |
File jsonfile = new File(jsondir); | |
String[] str = jsonfile.list(); | |
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd"); | |
for (int i = 0; i < str.length; i++) { | |
try { | |
Date d = transFormat.parse(str[i].split(".json")[0]); | |
arr.add(CalendarDay.from(d)); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
} | |
return arr; | |
} | |
public JSONObject loadJSON(String path) { | |
try { | |
File jsonfile = new File(path); | |
if (!jsonfile.exists()) { | |
JSONArray tempary = new JSONArray(); | |
JSONObject tempobj = new JSONObject(); | |
try { | |
tempobj.put("Beverages", tempary); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
String str = tempobj.toString(); | |
FileWriter filewriter = new FileWriter(jsonfile); | |
BufferedWriter bufferedWriter = new BufferedWriter(filewriter); | |
bufferedWriter.write(str); | |
bufferedWriter.close(); | |
} | |
FileReader filereader = new FileReader(jsonfile); | |
BufferedReader bufferedReader = new BufferedReader(filereader); | |
StringBuilder stringBuilder = new StringBuilder(); | |
String line = bufferedReader.readLine(); | |
while (line != null) { | |
stringBuilder.append(line).append("\n"); | |
line = bufferedReader.readLine(); | |
} | |
bufferedReader.close(); | |
String responce = stringBuilder.toString(); | |
try { | |
JSONObject obj = new JSONObject(responce); | |
return obj; | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
ArrayList<PieEntry> load_kcal_pi(String path) { | |
ArrayList<PieEntry> arr = new ArrayList<>(); | |
try { | |
JSONObject jsonObject = loadJSON(path); | |
JSONArray array = jsonObject.getJSONArray("Beverages"); | |
for (int i = 0; i < array.length(); i++) { | |
JSONObject object = array.getJSONObject(i); | |
arr.add(new PieEntry(Float.parseFloat(String.valueOf(object.get("kcal"))), String.valueOf(object.get("name")))); | |
} | |
} catch (JSONException e) { | |
//e.printStackTrace(); | |
arr.add(new PieEntry(1, "Null")); | |
} | |
return arr; | |
} | |
ArrayList<PieEntry> load_sugar_pi(String path) { | |
ArrayList<PieEntry> arr = new ArrayList<>(); | |
try { | |
JSONObject jsonObject = loadJSON(path); | |
JSONArray array = jsonObject.getJSONArray("Beverages"); | |
for (int i = 0; i < array.length(); i++) { | |
JSONObject object = array.getJSONObject(i); | |
arr.add(new PieEntry(Float.parseFloat(String.valueOf(object.get("sugar"))), String.valueOf(object.get("name")))); | |
} | |
} catch (JSONException e) { | |
//e.printStackTrace(); | |
arr.add(new PieEntry(1, "Null")); | |
} | |
return arr; | |
} | |
} | |
public class EventDecorator implements DayViewDecorator { | |
private final int color; | |
private final HashSet<CalendarDay> dates; | |
public EventDecorator(int color, Collection<CalendarDay> dates) { | |
this.color = color; | |
this.dates = new HashSet<>(dates); | |
} | |
@Override | |
public boolean shouldDecorate(CalendarDay day) { | |
return dates.contains(day); | |
} | |
@Override | |
public void decorate(DayViewFacade view) { | |
view.addSpan(new DotSpan(5, color)); | |
} | |
} | |
} |
package com.example.gradproject2020; | |
import androidx.appcompat.app.AppCompatActivity; | |
import androidx.fragment.app.Fragment; | |
import android.app.Activity; | |
import android.app.AlertDialog; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
import android.content.Intent; | |
import android.content.SharedPreferences; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.text.InputType; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.TextView; | |
import static android.content.Context.MODE_PRIVATE; | |
public class SettingScreen extends Fragment { | |
public SettingScreen(){ | |
//empty constructor | |
} | |
//View | |
Button btn_name, btn_gender, btn_height, btn_weight, btn_activ, btn_age; | |
TextView txt_name, txt_gender, txt_height, txt_weight, txt_kcal, txt_age, txt_activity; | |
//Functions | |
Intent Scr_Setting; | |
pref Pref; | |
//Resources | |
String username; | |
boolean usergender; //false : 남, true : 여 | |
float userweight, userheight, userkcal, useractiv, usersugar; | |
int userage; | |
View view; | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ | |
view = inflater.inflate(R.layout.activity_setting_screen, container, false); | |
btn_name = view.findViewById(R.id.btn_name); | |
btn_gender = view.findViewById(R.id.btn_gender); | |
btn_height = view.findViewById(R.id.btn_height); | |
btn_age = view.findViewById(R.id.btn_age); | |
btn_weight = view.findViewById(R.id.btn_weight); | |
btn_activ = view.findViewById(R.id.btn_activ); | |
txt_name = view.findViewById(R.id.txt_name); | |
txt_gender = view.findViewById(R.id.txt_gender); | |
txt_height = view.findViewById(R.id.txt_height); | |
txt_age = view.findViewById(R.id.txt_age); | |
txt_weight = view.findViewById(R.id.txt_weight); | |
txt_kcal = view.findViewById(R.id.txt_kcal); | |
txt_activity = view.findViewById(R.id.txt_activity); | |
Pref = new pref(); | |
Pref.load_personal(); | |
txt_name.setText(username); | |
txt_height.setText(Float.toString(userheight)); | |
txt_weight.setText(Float.toString(userweight)); | |
txt_age.setText(Integer.toString(userage)); | |
if(usergender) txt_gender.setText("여성"); | |
else txt_gender.setText("남성"); | |
if(useractiv == 1.2f) txt_activity.setText("활동 없음"); | |
else if (useractiv == 1.3f) txt_activity.setText("약간의 활동"); | |
else if (useractiv == 1.5f) txt_activity.setText("정상 활동"); | |
else txt_activity.setText("격렬한 운동"); | |
txt_kcal.setText(Float.toString(userkcal)); | |
btn_name.setOnClickListener(new View.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
AlertDialog.Builder alert_correct = new AlertDialog.Builder(getActivity()); | |
final EditText name = new EditText(getActivity()); | |
alert_correct.setTitle("이름 변경") | |
.setView(name) | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
username = name.getText().toString(); | |
Pref.save_name(username); | |
txt_name.setText(username); | |
txt_kcal.setText(Float.toString(userkcal)); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert_correct.create(); | |
alertDialog.show(); | |
} | |
}); | |
btn_gender.setOnClickListener(new View.OnClickListener(){ | |
boolean choice; | |
@Override | |
public void onClick(View view){ | |
final String[] items = new String[] {"남성", "여성"}; | |
AlertDialog.Builder alert_correct = new AlertDialog.Builder(getActivity()); | |
alert_correct.setTitle("성별 변경") | |
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
if(which == 0) choice = false; | |
else choice = true; | |
} | |
}) | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
usergender = choice; | |
Pref.save_gender(usergender); | |
if(usergender) txt_gender.setText("여성"); | |
else txt_gender.setText("남성"); | |
txt_kcal.setText(Float.toString(userkcal)); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert_correct.create(); | |
alertDialog.show(); | |
} | |
}); | |
btn_height.setOnClickListener(new View.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
AlertDialog.Builder alert_correct = new AlertDialog.Builder(getActivity()); | |
final EditText height = new EditText(getActivity()); | |
height.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); | |
alert_correct.setTitle("키 변경") | |
.setView(height) | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
userheight = Float.parseFloat(height.getText().toString()); | |
Pref.save_height(userheight); | |
txt_height.setText(Float.toString(userheight)); | |
txt_kcal.setText(Float.toString(userkcal)); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert_correct.create(); | |
alertDialog.show(); | |
} | |
}); | |
btn_weight.setOnClickListener(new View.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
AlertDialog.Builder alert_correct = new AlertDialog.Builder(getActivity()); | |
final EditText weight = new EditText(getActivity()); | |
weight.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); | |
alert_correct.setTitle("몸무게 변경") | |
.setView(weight) | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
userweight = Float.parseFloat(weight.getText().toString()); | |
Pref.save_weight(userweight); | |
txt_weight.setText(Float.toString(userweight)); | |
txt_kcal.setText(Float.toString(userkcal)); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert_correct.create(); | |
alertDialog.show(); | |
} | |
}); | |
btn_age.setOnClickListener(new View.OnClickListener(){ | |
@Override | |
public void onClick(View view){ | |
AlertDialog.Builder alert_correct = new AlertDialog.Builder(getActivity()); | |
final EditText age = new EditText(getActivity()); | |
age.setInputType(InputType.TYPE_CLASS_NUMBER); | |
alert_correct.setTitle("나이 변경") | |
.setView(age) | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
userage = Integer.parseInt(age.getText().toString()); | |
Pref.save_age(userage); | |
txt_age.setText(Float.toString(userage)); | |
txt_kcal.setText(Float.toString(userkcal)); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert_correct.create(); | |
alertDialog.show(); | |
} | |
}); | |
btn_activ.setOnClickListener(new View.OnClickListener(){ | |
int index; | |
@Override | |
public void onClick(View view){ | |
final String[] items = new String[] {"활동 없음", "약간의 활동", "정상 활동", "격렬한 운동"}; | |
AlertDialog.Builder alert_correct = new AlertDialog.Builder(getActivity()); | |
alert_correct.setTitle("활동량 변경") | |
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
index = which; | |
} | |
}) | |
.setPositiveButton("확인", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
switch(index){ | |
case 0: | |
useractiv = 1.2f; | |
break; | |
case 1: | |
useractiv = 1.3f; | |
break; | |
case 2: | |
useractiv = 1.5f; | |
break; | |
case 3: | |
useractiv = 1.75f; | |
break; | |
} | |
Pref.save_activ(useractiv); | |
if(useractiv == 1.2f) txt_activity.setText("활동 없음"); | |
else if (useractiv == 1.3f) txt_activity.setText("약간의 활동"); | |
else if (useractiv == 1.5f) txt_activity.setText("정상 활동"); | |
else txt_activity.setText("격렬한 운동"); | |
txt_kcal.setText(Float.toString(userkcal)); | |
dialog.dismiss(); | |
} | |
}) | |
.setNegativeButton("취소", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.dismiss(); | |
} | |
}).setCancelable(false); | |
AlertDialog alertDialog = alert_correct.create(); | |
alertDialog.show(); | |
} | |
}); | |
return view; | |
} | |
class pref{ | |
float calc_kcal(){ | |
float kcal = 0; //final kcal | |
float weight_avg = 0; //average weight | |
float weight_ = 0; //modified weight with average | |
if(usergender){ | |
weight_avg = userheight*userheight*21/10000; | |
weight_ = weight_avg + ((userweight - weight_avg)*0.25f); | |
kcal = 665 + (9.6f*weight_) + (1.8f*userheight) - (4.7f*userage); | |
} | |
else{ | |
weight_avg = userheight*userheight*22/10000; | |
weight_ = weight_avg + ((userweight - weight_avg)*0.25f); | |
kcal = 664 + (13.7f*weight_) + (5f*userheight) - (6.8f*userage); | |
} | |
return kcal*useractiv; | |
} | |
void save_name(String name){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putString("name", name); | |
edit.apply(); | |
} | |
void save_gender(Boolean gender){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putBoolean("gender", gender); | |
userkcal = calc_kcal(); | |
usersugar = userkcal/40; | |
edit.putFloat("kcal", userkcal); | |
edit.putFloat("sugar", usersugar); | |
edit.apply(); | |
} | |
void save_height(float height){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putFloat("height", height); | |
userkcal = calc_kcal(); | |
usersugar = userkcal/40; | |
edit.putFloat("kcal", userkcal); | |
edit.putFloat("sugar", usersugar); | |
edit.apply(); | |
} | |
void save_weight(float weight){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putFloat("weight", weight); | |
userkcal = calc_kcal(); | |
usersugar = userkcal/40; | |
edit.putFloat("kcal", userkcal); | |
edit.putFloat("sugar", usersugar); | |
edit.apply(); | |
} | |
void save_activ(float activ){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putFloat("activity", activ); | |
userkcal = calc_kcal(); | |
usersugar = userkcal/40; | |
edit.putFloat("kcal", userkcal); | |
edit.putFloat("sugar", usersugar); | |
edit.apply(); | |
} | |
void save_age(int age){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
SharedPreferences.Editor edit = data_personal.edit(); | |
edit.putInt("age", age); | |
userkcal = calc_kcal(); | |
usersugar = userkcal/40; | |
edit.putFloat("kcal", userkcal); | |
edit.putFloat("sugar", usersugar); | |
edit.apply(); | |
} | |
void load_personal(){ | |
SharedPreferences data_personal = getContext().getSharedPreferences("data_personal", MODE_PRIVATE); | |
username = data_personal.getString("name", "김건국"); | |
userheight = data_personal.getFloat("height", 170f); | |
userweight = data_personal.getFloat("weight", 60f); | |
usergender = data_personal.getBoolean("gender", false); | |
useractiv = data_personal.getFloat("activity", 1.5f); | |
userage = data_personal.getInt("age", 20); | |
userkcal = data_personal.getFloat("kcal", 0); | |
usersugar = data_personal.getFloat("sugar", 0); | |
} | |
} | |
} |



하드웨어 (AVR 아두이노 코딩) + 안드로이드 어플리케이션 + 서버용 프로그램으로 구성됨
이건 그중 어플리케이션 코드였다
앱으로 만들어본거라곤 자바 뷰 리로드 이용한 슈팅게임이 전부였던지라 완전 맨땅에 헤딩식으로 만든 기억이 난다
LoadingScreen은 내부 파일들 불러오는 동안 표시되는 화면
MainScreen이 로딩 후에 표시되는 첫 화면 (칼로리랑 당분 섭취량 + 경고이미지 표시)
BTScreen이 하드웨어랑 블루투스 통신하면서 센서값 받아오고 서버랑 통신해서 음료수 Classification해오는 부분
ResultScreen이 지금까지 먹은 음료수 칼로리랑 설탕량 (json으로 저장됨) 날짜별 그래프로 표시해주는 곳
SettingScreen이 사용자 설정 설정하고 json 저장 / 불러오는 부분 (일일권장칼로리 등)
그외는 FTP 통신이나 블루투스 통신용 함수
자세한 내용은 Github 링크에 유튜브 영상을 걸어놨다
다시 꺼내보고싶진 않다
이거 만들면서 나는 자바랑 안맞는다는 생각 많이했다
왜냐면 졸작하면서 가장 시간 오래걸렸던 부분이기때문... 요즘 누가 앱을 자바로 짜냐 코틀린이나 리액트쓰지..
그래서 차라리 취미로 앱을 만들더라도 다른 언어를 쓰겠다 하고 자바랑 사회적거리두기 시작한 기억이 난다
블로그에 적는건 지금까지 했던 것들 정리하면서 겸사겸사...
지금생각해봐도 하드웨어 졸업작품 제작주제에 안드로이드 앱까지 만드는건 무리수였던거같음
겨우 갈아넣어서 완성했는데 공모전에서 아무런 주목 못받은것도 현타오고.. 두번다시 이런 프로젝트는 하기싫다
'기타공부 > Android' 카테고리의 다른 글
191211 안드로이드 슈팅게임 (최종과제) (0) | 2021.02.08 |
---|---|
191008 가위바위보 게임 (0) | 2021.02.08 |
190917 초간단 시간표앱 (0) | 2021.02.08 |
191029 안드로이드 수업과제 (0) | 2021.02.08 |
191119 안드로이드 수업과제 (0) | 2021.02.08 |