회사는 정말 싫어욧

y/n 혹은 " " 이런식으로 구분하고 null은 쓰지말자


null exception나오면 머리 아파짐 ㅜㅜ

http://pumdaf.tistory.com/entry/Android-Sqlite-데이터베이스-기본-예제


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
SQLiteDatabase db;
EditText editText;
ListView listView;
ArrayAdapter<String> adapter;
List<String> list;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText = findViewById(R.id.et);
listView = findViewById(R.id.listView);
list = new ArrayList<>();
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final int idx = Integer.parseInt(list.get(position).split("\\.")[0]);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("데이터 삭제");
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setMessage(idx+"번 데이터를 삭제하시겠습니까?");
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//실제 데이터 삭제
//내장 클래스에서 지역변수에 접근하려면 반드시 final로 선언되어야함
String sql = "delete from test where idx = " + idx;
db.execSQL(sql);

select();
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});

builder.show(); //다이얼로그 띄우기
return false;
}
});



//파일이름,허용범위,팩토리 사용유무
db = openOrCreateDatabase("testdb.db",MODE_PRIVATE,null);
Log.d("Sqllite","testdb 데이터베이스 생성 완료!");
String sql = "create table if not exists test (idx integer primary key, title varchar(10))";
db.execSQL(sql);
Log.d("Sqllite","test테이블 생성 완료!");

select();

}

public void insert(View view) {
String data = editText.getText().toString();
if (data != null && data.trim().length()>0) {
String sql = "insert into test (title) values ('" + data + "')";
db.execSQL(sql);
Log.d("Sqllite","test테이블에 " + data + " 저장 완료!");
editText.setText("");
editText.requestFocus();//커서 옮기기

select();
}
}

private void select() {
String sql = "select * from test order by idx";
Cursor c1 = db.rawQuery(sql,new String[]{});

list.clear();//리스트 비우기
while (c1.moveToNext()) {
String dbText = c1.getInt(0) + ". "; //idx번호
dbText += c1.getString(c1.getColumnIndex("title"));

list.add(dbText);
}
adapter.notifyDataSetChanged(); //데이터가 변경되었음을 알려줌(리스트 새로고침)
}
}






<xml>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et"
android:layout_weight="10"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="저장"
android:onClick="insert"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />



</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">

</ListView>

</LinearLayout>



<MainActivity>

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
SQLiteDatabase db;
EditText editText;
ListView listView;
ArrayAdapter<String> adapter;
List<String> list;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText = findViewById(R.id.et);
listView = findViewById(R.id.listView);
list = new ArrayList<>();
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
//파일이름,허용범위,팩토리 사용유무
db = openOrCreateDatabase("testdb.db",MODE_PRIVATE,null);
Log.d("Sqllite","testdb 데이터베이스 생성 완료!");
String sql = "create table if not exists test (idx integer primary key, title varchar(10))";
db.execSQL(sql);
Log.d("Sqllite","test테이블 생성 완료!");

select();

}

public void insert(View view) {
String data = editText.getText().toString();
if (data != null && data.trim().length()>0) {
String sql = "insert into test (title) values ('" + data + "')";
db.execSQL(sql);
Log.d("Sqllite","test테이블에 " + data + " 저장 완료!");
editText.setText("");
editText.requestFocus();//커서 옮기기

select();
}
}

private void select() {
String sql = "select * from test order by idx";
Cursor c1 = db.rawQuery(sql,new String[]{});

list.clear();//리스트 비우기
while (c1.moveToNext()) {
String dbText = c1.getInt(0) + ". "; //idx번호
dbText += c1.getString(c1.getColumnIndex("title"));

list.add(dbText);
}
adapter.notifyDataSetChanged(); //데이터가 변경되었음을 알려줌(리스트 새로고침)
}
}


Devide file Explore에서 data/data/패키지이름/databases에 저장되는걸 볼 수 있다






** 테이블이랑 필드이름을 대소문자 구분하는듯 ! 주의하기

** integer 필드에 primary_key만 주면 자동으로 값이 증가한다



ImageView imageView;

private StorageReference mStorageRef;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imageView = findViewById(R.id.iv);
mStorageRef = FirebaseStorage.getInstance().getReference();
}

public void fileUpload(View view) {
//Uri file = Uri.parse(String.format("android.resource://%s/%s/%s",this.getPackageName(),"raw","cat.jpg"));
Uri path = Uri.parse("android.resource://"+getResources().getResourcePackageName(R.raw.cat)+"/"+R.raw.cat);
StorageReference riversRef = mStorageRef.child("images/cat.jpg");

riversRef.putFile(path)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
Uri downloadUrl = taskSnapshot.getDownloadUrl();

}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(getBaseContext(),"업로드 실패염",Toast.LENGTH_SHORT).show();
}
});
}


//raw폴더에 있는 파일을 업로드 할 경우 보라색 표시된 걸로 Uri.parse하면된다

//여기에서 쓰는 mStorageRef.child("images/cat.jpg");

//Uri.parse의 파일을 Firebase storage에 images폴더 안의 cat.jpg라는 파일로 저장한다는 의미


public void fileDownload(View view) {
try {
final File localFile = File.createTempFile("images", "jpg");
StorageReference riversRef = mStorageRef.child("images/smiley.jpg");
riversRef.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmapImage = BitmapFactory.decodeFile(localFile.getPath());
imageView.setImageBitmap(bitmapImage);
Toast.makeText(getApplicationContext(), "다운로드 성공", Toast.LENGTH_LONG).show();

}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(getBaseContext(),"다운 실패염",Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}

//Firebase storage에 있는 파일을 다운로드 할 때는 보라색의 경로 images/smiley.jpg파일을 다운로드 한다

// - 한마디로 storage의 images 폴더 안의 smiley.jpg 파일을 다운로드 한다는 의미 (경로는 사용자에 따라 작성)

//여기에서 쓰는 File.createTempFile("images", "jpg");

//다운로드 한 파일을 images로 시작하고 .jpg로 끝나는 파일을 만든다는 의미

//(중간에 01,02,03 이런식으로 임시파일이 늘어날수록 숫자가 변경됨)



TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = findViewById(R.id.tv);

try { //파일저장
Serializer serializer = new Persister();
Person person = new Person(1,"한사람",22,true);
OutputStream os = openFileOutput("person.xml",MODE_PRIVATE);
serializer.write(person,os);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}


try { //파일읽기
Serializer serializer = new Persister();
InputStream is = openFileInput("person.xml");

Person person = serializer.read(Person.class, is);

textView.setText(person.toString());


} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}



}
}


private List<Food> parseXMLJsoup() {
List<Food> foods = new ArrayList<>();

try {
InputStream is = getAssets().open("food.xml");
Document document = Jsoup.parse(is,"UTF-8","http://example.com");
Elements element = document.select("food");
for (Element e : element) {
Food food = new Food();
food.setName(e.select("name").get(0).text());
food.setDescription(e.select("description").get(0).text());
food.setPrice(e.select("price").get(0).text());
food.setCalories(e.select("calories").get(0).text());
foods.add(food);
}
} catch (IOException e) {
e.printStackTrace();
}
return foods;
}

food.xml을 못찾으면 http://example.com으로 간다함

<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
Two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
Light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
Belgian waffles covered with assorted fresh berries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
Thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
Two eggs, bacon or sausage, toast, and our ever-popular hash browns
</description>
<calories>950</calories>
</food>
</breakfast_menu>
public class Food {
private String name;
private String price;
private String description;
private String calories; //DTO


public class MainActivity extends AppCompatActivity {
List<Food> foodList;
List<String> list = new ArrayList<>();
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = findViewById(R.id.listView);

foodList = parseXML();

for (Food food : foodList) {
list.add(food.getName() + "(" + food.getPrice() + ")");
}

ArrayAdapter<String > adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),foodList.get(position).toString(),Toast.LENGTH_SHORT).show();
}
});
}

private List<Food> parseXML() {
List<Food> foods = new ArrayList<>();
boolean isName = false, isDesc = false, isCalories = false, isPrice = false;
String name, desc, price, calories, tagName;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(getResources().openRawResource(R.raw.food), "UTF-8");

Food food = null;
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
switch (tagName) {
case "food":
food = new Food();
break;
case "name" :
isName = true;
break;
case "description" :
isDesc = true;
break;
case "price" :
isPrice = true;
break;
case "calories" :
isCalories = true;
break;
}
break;
case XmlPullParser.END_TAG:
tagName = parser.getName();
switch (tagName) {
case "food":
foods.add(food);
break;
case "name" :
isName = false;
break;
case "description" :
isDesc = false;
break;
case "price" :
isPrice = false;
break;
case "calories" :
isCalories = false;
break;
}
break;
case XmlPullParser.TEXT:
if (isName) food.setName(parser.getText());
if (isDesc) food.setDescription(parser.getText());
if (isPrice) food.setPrice(parser.getText());
if (isCalories) food.setCalories(parser.getText());
break;
}
eventType = parser.next();
}

} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Log.d("읽은 내용" , foods.toString());
return foods;
}
}


public void start1(View view) {
Button button = (Button) view;

button.setEnabled(false);
}


버튼에 메소드 만들경우 매개변수 view로 버튼 사용가능


Save {

String text = editText.getText().toString();

editText.setText("");

try {

OutputStream os = openFileOutput("data.txt",MODE_PRIVATE);

PrintWriter pw = new PrintWriter(os);

pw.append(text + "\n");

pw.flush();

pw.close();

os.close();


} catch (Exception e) {

}



Load{

try {

InputStream is = openFileInput("data.txt");

Scanner sc = new Scanner(is,"UTF-8");

while (sc.hasNextLine()) {

textView.append(sc.nextLine() +"\n");


}

} catch (Exception e) {

}

private Context context;
private List<데이터타입> flagList;

생성자 만들기


오버라이딩 된 메소드에 내용 채우기


@Override
public int getCount() {
return flagList.size();
}

@Override
public Object getItem(int position) {
return flagList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
Flag data = flagList.get(position);
FlagView flagView = null;

if (convertView == null) {
flagView = new FlagView(context,data);
}
else {
flagView = (FlagView) convertView;
flagView.setFlag(data);
}
return flagView;
}