[Q] How can I create a white list of Apps? - Android Apps and Games

Hi, I am developping a home screen app, and I want only certain apps to be able tu be launched from my home screen.
I want to do it exactly like Surelock:
When the user tries to open an app that doesn't belong to my list of accepted apps, he should receive a toast saying something like example: "com.android.settings blocked by this app".
I need that type of security, I came across a piece of code on the web, but it does not work...
Could you help me out either by suggesting something new or by helping me understand and fix this one?
public class MonitorService extends Service {
private Handler handler;
Runnable runnable;
@override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler = new Handler();
runnable = new Runnable() {
@override
public void run() {
new Thread(new Runnable() {
@override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am
.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
String currentActivityName=componentInfo.getClassName();
String packageName=componentInfo.getPackageName();
if(whitelist.contains(currentActivityName)){
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName(blockActivityPackageName,
blockActivityName));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
}
}
}).start();
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
@override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, MonitorService.class);
startService(intent);
}
@override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}}

Related

help with this code

i wnat to use the random outside the method
plz help
Code:
public class asd2 extends Activity {
private Button Button01;
private Button Button02;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button01 = (Button) findViewById(R.id.Button01);
Button02 = (Button) findViewById(R.id.Button02);
final SeekBar seekBar01 = (SeekBar) findViewById(R.id.SeekBar01);
final Random anyrandom = new Random();
final EditText EditText01 = (EditText) findViewById(R.id.EditText01);
Button01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// i need help to move to other activity in my app with this
// intent
Intent asdintenet = new Intent(this, secjavafile);
startActivity(asdintenet);
// this is the random i want to use (asdrandom)outside this
// method
int asdrandom = anyrandom.nextInt(30) + 1;
seekBar01.setProgress(asdrandom);
}
});
Button02.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
seekBar01
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
/*
* I WANT to use the random here e.g
* EditText01.setText("progress is"+asdrandom);when i
* use progress int the app crash
*/
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
this file contains the project
as u c I'm beginner
i;ve solved one
i used string.valueof(progress)
any help with intent to other activity???

Why can't my GUI return back to recording mode despite having service?

Hi i'm new to android so that's why i come to find help... Hi an introduction to the app i'm doing here, i'm actually doing an car blackbox app..
I had my service run the video recording processes in the background so i should be able to leave the app for a while and come back to the Video recording GUI with the surfaceview but my application was force to close when i return to the app. So is the problem related to onResume() method or something else? If its yes what i should do in order to get my application GUI to return to the video recording surfaceview and still running the background recording using the service rather than giving me an error? Can someone help please...
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My RecordingService.java Service file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
private boolean recordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
camera = CameraTest.camera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
camera.unlock();
}
catch(Exception e){
camera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordingStatus = false;
}
}

[Q] How do i capped my maximum directory storage space in SD? PLEASE HELP!!!

Question 1: Presumingly i wanted to allocate only 1GB of space to store my videos in a particular self declared directory how should i do it?
Question 2: And i wanted my directory to capped at 1GB after which how is it going to auto-delete the oldest video file in that directory once its about to reach 1GB?
Sorry i'm kinna new in java and android and currently creating an car blackbox app can someone help me... Thanks
This is what I have tried so far can someone tell me how should i implement the above function into my mainActivity:
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My RecordingService.java Service file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
private boolean recordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
camera = CameraTest.camera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
camera.unlock();
}
catch(Exception e){
camera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordingStatus = false;
}
}
Anyone can help please...
I've tried my best to do my coding but i'm really in a desperate bit to get some help from you guys here... Could someone please help me, not that i'm lazy or what to do the coding myself but its just that i'm really bad in programming and new to android but yet force to do this project so decided to ask for help from you guys here...
I found this online but it seems that it answer part of my question isn't it but i don't seem to know how to integrate it into my codes... Can someone help me with this problem?
Code:
private static long dirSize(File dir) {
long result = 0;
Stack<File> dirlist= new Stack<File>();
dirlist.clear();
dirlist.push(dir);
while(!dirlist.isEmpty())
{
File dirCurrent = dirlist.pop();
File[] fileList = dirCurrent.listFiles();
for (int i = 0; i < fileList.length; i++) {
if(fileList[i].isDirectory())
dirlist.push(fileList[i]);
else
result += fileList[i].length();
}
}
return result;
}
Could someone guide me along with the above codes??

[Q] how call activity.java in other one using button listener

I have two class activity that runs perfectly separately (ArduinoBlinkLEDActivity.java and ObjTrackActivity.java) .. I want to merge the two classes in one slass; i want to call the second class in the first one using the onclick activity buttonListener. i think that need to change layouts
please i need your help
ArduinoBlinkLEDActivity.java:
public class ArduinoBlinkLEDActivity extends Activity {
// TAG is used to debug in Android logcat console
private static final String TAG = "ArduinoAccessory";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
while (connected) {
startService(new Intent(this, ArduinoBlinkLEDActivity.class));
}
iptext = (EditText) findViewById(R.id.ipserveur);
connexion = (Button) findViewById(R.id.button2);
deconnexion = (Button) findViewById(R.id.button1);
}
ObjTrackActivity.java :
public class ObjTrackActivity extends Activity {
private static final String TAG = "ObjTrackActivity";
public ObjTrackActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new ObjTrackView(this));
}
ObjTrackView.java:
class ObjTrackView extends SampleViewBase {
private int mFrameSize;
private Bitmap mBitmap;
private int[] mRGBA;
public ObjTrackView(Context context) {
super(context);
}
my test that doesn't work: ArduinoBlinkLEDActivity.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
iptext = (EditText) findViewById(R.id.ipserveur);
connexion = (Button) findViewById(R.id.button2);
deconnexion = (Button) findViewById(R.id.button1);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
//Listening to button event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Log.i(TAG, "onCreate");
//super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new ObjTrackView(this));
}
});

Is RecyclerView refreshed when AlertDialog's positive button gets pressed

My MainActivity has a RecyclerView adapter, and data to this RecyclerView is added through a AlertDialog which passes the entered text to the MainActivity. The recycler view gets refreshed somehow when the positive button in the dialog is pressed even though I never call notifyItemInserted() or notifyDatasetChange() after passing the new input. I want to know how this happens, my guess is the recyclerview is somehow refreshed after the positive button is pressed in the dialog box.
Custom AlertDialog Code:
Code:
public class CustomDialog extends AppCompatDialogFragment {
OnNoteAddedListener onNoteAddedListener;
public interface OnNoteAddedListener {
public void onClick(String note);
}
public CustomDialog(OnNoteAddedListener onNoteAddedListener) {
this.onNoteAddedListener = onNoteAddedListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogLayout = inflater.inflate(R.layout.dialog_box, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogLayout).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int id) {
EditText addNote = dialogLayout.findViewById(R.id.note_text);
String note = addNote.getText().toString();
onNoteAddedListener.onClick(note);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CustomDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Adapter code:
Code:
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
private static final String TAG = "RecyclerViewAdapter";
private List<String> notesList;
private Context mContext;
private SendPositionConnector sendPositionConnector;
public interface SendPositionConnector
{
public void sendPosition(int position);
}
public RecyclerViewAdapter(List<String> notesList, Context mContext)
{
this.notesList = notesList;
this.mContext = mContext;
this.sendPositionConnector = (MainActivity)mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
{
Log.d(TAG, "onBindViewHandler: called");
viewHolder.noteContent.setText(notesList.get(position));
viewHolder.parentLayout.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View view)
{
Log.d(TAG, "onLongClick: long clicked on");
sendPositionConnector.sendPosition(position);
return false;
}
});
}
@Override
public int getItemCount()
{
return notesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView noteContent;
RelativeLayout parentLayout;
ImageView bullet;
public ViewHolder(@NonNull View itemView)
{
super(itemView);
bullet = itemView.findViewById(R.id.bullet);
noteContent = itemView.findViewById(R.id.text_content);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Main Activity:
Code:
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.SendPositionConnector
{
private static final String TAG = "MainActivity";
private List<String> notesList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private int position;
public AgentAsyncTask agentAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.my_recycler_view);
registerForContextMenu(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
agentAsyncTask = new AgentAsyncTask(notesList, getApplicationContext(), true, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
adapter = new RecyclerViewAdapter(notesList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
agentAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.add_note:
showDialogBox(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStop()
{
super.onStop();
new AgentAsyncTask(notesList, getApplicationContext(), false, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
}
}).execute();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private boolean showDialogBox(MenuItem menuItem)
{
AppCompatDialogFragment dialogFragment = new CustomDialog(new CustomDialog.OnNoteAddedListener(){
@Override
public void onClick(String note)
{
Log.d(TAG, "onClick: "+ note);
notesList.add(note);
}
});
dialogFragment.show(getSupportFragmentManager(),"Adding");
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.delete:
notesList.remove(position);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, notesList.size());
return true;
default:
return false;
}
}
@Override
public void sendPosition(int position)
{
this.position = position;
}
private static class AgentAsyncTask extends AsyncTask<Void, Void, List<String>>
{
private List<String> notesList;
private boolean flag;
OnRead onRead;
Context context;
AppDataBase dataBase;
private static final String TAG = "AgentAsyncTask";
public interface OnRead
{
public void onRead(List<String> notesList);
}
private AgentAsyncTask(List<String> notesList,Context context,boolean flag, OnRead onRead)
{
this.notesList = notesList;
this.onRead = onRead;
this.flag = flag;
this.context = context;
}
@Override
protected List<String> doInBackground(Void... params)
{
dataBase = Room.databaseBuilder(context, AppDataBase.class, "database-name").build();
if(!flag)
{
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {}.getType();
String json = gson.toJson(notesList, type);
Log.d(TAG, "doInBackground: "+json);
Notes notes = new Notes();
notes.setNoteContent(json);
notes.setUid(1);
dataBase.notesDao().insertNotes(notes);
return notesList;
}
else
{
Gson gson = new Gson();
String notesListContent = dataBase.notesDao().getNotes();
if(dataBase.notesDao().getCount() != 0)
{
notesList = gson.fromJson(notesListContent, new TypeToken<List<String>>()
{
}.getType());
}
else
{
return notesList;
}
return notesList;
}
}
@Override
protected void onPostExecute(List<String> notesList)
{
super.onPostExecute(notesList);
if(flag)
onRead.onRead(notesList);
}
}
}

Categories

Resources