The implementation of Android Notepad function
- time stamp
- Time stamp of edit box
- Get system time and transform format
- Save the time to the database and update the time every time you modify it
- About the layout of time
- Initialize view
- Time stamp for notepad list
- Query function
- Query through dynamic change of EditText content
- Fuzzy query database data by title
- When the EditText content changes, this method will be called to dynamically query the database data according to the content change, and then assemble the data into the adapter to display the list
- Query by button
- Empty text box
- Insert local pictures and take photos insert pictures
time stamp
The compilation of timestamps includes the time display of Notepad editing area and the time display of Notepad list
Time stamp of edit box
Get system time and transform format
Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Log.v("Time:",sdf.format(date)); tv_now.setText(sdf.format(date));
Save the time to the database and update the time every time you modify it
private void saveNote(){ NoteDataBaseHelper dbHelper = MainActivity.getDbHelper(); ContentValues values = new ContentValues(); values.put(Note.title,et_title.getText().toString()); values.put(Note.content,et_content.getText().toString()); values.put(Note.time,tv_now.getText().toString()); if (insertFlag){ Note.insertNote(dbHelper,values); }else{ Note.updateNote(dbHelper,Integer.parseInt(currentNote.getId()),values); } }
About the layout of time
<TextView android:id="@+id/tv_now" android:layout_width="match_parent" android:layout_height="30dp" android:background="#A5BECE" android:textAlignment="textEnd" android:gravity="end|center_vertical" android:paddingRight="8dp"/>
Initialize view
private void initView(){ btn_save = findViewById(R.id.btn_save); btn_return = findViewById(R.id.btn_return); tv_now = findViewById(R.id.tv_now); et_content = findViewById(R.id.edit_content); et_title = findViewById(R.id.edit_title); //Here is the test code Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Log.v("Time:",sdf.format(date)); tv_now.setText(sdf.format(date)); }
Time stamp for notepad list
Time to get each note from the database
//Read all notes from the database and encapsulate them into a list < noteinfo > private void getNoteList(){ noteList.clear(); Cursor allNotes = Note.getAllNotes(dbHelper); for (allNotes.moveToFirst(); !allNotes.isAfterLast(); allNotes.moveToNext()){ NoteInfo noteInfo = new NoteInfo(); noteInfo.setId(allNotes.getString(allNotes.getColumnIndex(Note._id))); noteInfo.setTitle(allNotes.getString(allNotes.getColumnIndex(Note.title))); noteInfo.setContent(allNotes.getString(allNotes.getColumnIndex(Note.content))); noteInfo.setDate(allNotes.getString(allNotes.getColumnIndex(Note.time))); noteList.add(noteInfo); } }
Initialization attempt
public ViewHolder(View itemView) { if (itemView == null){ throw new IllegalArgumentException("item View can not be null!"); } this.itemView = itemView; itemIcon = itemView.findViewById(R.id.rand_icon); itemNoteTitle = itemView.findViewById(R.id.item_note_title); itemNoteDate = itemView.findViewById(R.id.item_note_date); }
Time layout
<TextView android:id="@+id/item_note_date" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textSize="16sp" android:gravity="center_vertical" android:singleLine="true"/>
Query function
Query through dynamic change of EditText content
Fuzzy query database data by title
private void getSelectNoteList(String title){ noteList.clear(); Cursor allNotes = Note.selectNotes(dbHelper,title); for (allNotes.moveToFirst(); !allNotes.isAfterLast(); allNotes.moveToNext()){ NoteInfo noteInfo = new NoteInfo(); noteInfo.setId(allNotes.getString(allNotes.getColumnIndex(Note._id))); noteInfo.setTitle(allNotes.getString(allNotes.getColumnIndex(Note.title))); noteInfo.setContent(allNotes.getString(allNotes.getColumnIndex(Note.content))); noteInfo.setDate(allNotes.getString(allNotes.getColumnIndex(Note.time))); noteList.add(noteInfo); } }
When the EditText content changes, this method will be called to dynamically query the database data according to the content change, and then assemble the data into the adapter to display the list
et_title.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } //This method is called when the EditText content changes @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().equals("")){ search_del.setVisibility(View.GONE); }else{ search_del.setVisibility(View.VISIBLE); } String titleChange=et_title.getText().toString(); Log.v("Change data:",titleChange); getSelectNoteList(titleChange); mListAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable editable) { } });
Query by button
This method is not humanized as the first one, and the user experience is poor
Add a listener to the query button
private void setListener(){ addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,EditActivity.class); startActivity(intent); } }); selectBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String edit_title=et_title.getText().toString(); HashMap<Integer,HashMap<String,Object>> map1=new HashMap<Integer,HashMap<String,Object>>();; map1=Note.getNote(dbHelper,edit_title); Log.v("query",map1.toString()); Intent intent = new Intent(MainActivity.this,SelectActivity.class); intent.putExtra("edit_title",edit_title ); startActivity(intent); //getSelectNoteList(edit_title); } });
Empty text box
Leave EditText empty
search_del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getNoteList();;//Initialization data et_title.setText(""); mListAdapter.notifyDataSetChanged();//Update RecycleView } });
Insert local pictures and take photos insert pictures
There are many ways to insert pictures. Here are two simple ways: getting pictures from the local area and taking photos to insert pictures directly.
First apply for permission
stay AndroidManifest.xml Setting permissions in
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
For Android 7.0 and above, the following code needs to be added to the onCreate() method. Otherwise, the path will be wrong when starting the photo taking function:
// android 7.0 system solves the problem of taking photos StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); builder.detectFileUriExposure();
Insert local picture
Start image related intent by setting the type of intent
//Get pictures from album public void getPhoto() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_OPEN_DOCUMENT); startActivityForResult(intent, PHOTO_FROM_GALLERY); }
Extract image path by using regular expression
private static final String regex="content://com.android.providers.media.documents/" +"document/image%\\w{4}"; private static final String reg="file:///storage/emulated/0/\\d+.jpg";
Take a picture insert a picture
Get permission and start the intent related to photographing
//Take photos public void takeCamera() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[] { Manifest.permission.CAMERA }, PHOTO_FROM_CAMERA); } else { File file=new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg"); try { if(file.exists()){ file.delete(); } file.createNewFile(); }catch (IOException e){ e.printStackTrace(); } imageUri=Uri.fromFile(file); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); startActivityForResult(intent, PHOTO_FROM_CAMERA); } }
Image processing
Convert the picture into the form and add it into the text box. Save the picture into the database when saving
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { ContentResolver resolver = getContentResolver(); super.onActivityResult(requestCode, resultCode, data); //switch on the first floor switch (requestCode) { case PHOTO_FROM_GALLERY: //switch on the second floor switch (resultCode) { case RESULT_OK: if (data != null) { Uri uri = data.getData();//Get Intent uri Bitmap bitmap = null; //Determine whether the path exists try { Bitmap originalBitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = resizeImage(originalBitmap, 200, 200);//Picture zoom } catch (FileNotFoundException e) { e.printStackTrace(); } if(bitmap != null){//If the picture exists //Append the selected picture to the position of the cursor in EditText int index = mText.getSelectionStart(); //Get cursor position Editable edit_text = mText.getEditableText();//Edit text box if(index <0 || index >= edit_text.length()){ edit_text.append(uri.toString()); updateNoteText(mText.getText().toString());//Update to database }else{ edit_text.insert(index,uri.toString()); updateNoteText(mText.getText().toString());//Update to database } }else{ Toast.makeText(NoteEditor.this, "Failed to get picture", Toast.LENGTH_SHORT).show(); } } break; case RESULT_CANCELED: break; } break; case PHOTO_FROM_CAMERA: if (resultCode == RESULT_OK) { Bitmap originalBitmap1=null; //Judge whether the picture exists try{ originalBitmap1=BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); }catch (FileNotFoundException e){ e.printStackTrace(); } if(originalBitmap1 != null){//If the picture has a save URI //Append the selected picture to the position of the cursor in EditText int index = mText.getSelectionStart(); //Get cursor position Editable edit_text = mText.getEditableText();//Edit text box if(index <0 || index >= edit_text.length()){ edit_text.append(imageUri.toString()); updateNoteText(mText.getText().toString());//Update to database }else{ edit_text.insert(index, imageUri.toString()); updateNoteText(mText.getText().toString());//Update to database } }else{ Toast.makeText(NoteEditor.this, "Failed to get picture", Toast.LENGTH_SHORT).show(); } } else { Log.e("result", "is not ok" + resultCode); } break; default: break; } }
Picture zoom
/** * Picture zoom * @param originalBitmap Original Bitmap * @param newWidth Custom width * @return Scaled Bitmap */ private Bitmap resizeImage(Bitmap originalBitmap, int newWidth, int newHeight){ int width = originalBitmap.getWidth(); int height = originalBitmap.getHeight(); //Define the width and height to be converted // int newWidth = 200; // int newHeight = 200; //Calculate the wide and high zoom rates float scanleWidth = (float)newWidth/width; float scanleHeight = (float)newHeight/height; //Create Matrix object matrix for operation picture Matrix matrix = new Matrix(); // Zoom picture action matrix.postScale(scanleWidth,scanleHeight); //Rotate picture action //matrix.postRotate(45); // Create a new picture Bitmap Bitmap resizedBitmap = Bitmap.createBitmap(originalBitmap,0,0,width,height,matrix,true); return resizedBitmap; }
Screenshot of operation effect
Author: Xiao Binyu
Original link