how to make a service for locking applications in android? - java

I am making an Android application to lock applications.
I have selected the applications I want to lock and saved them in SharedPreferences, but I don't know how to make the service which will detect every application which will be launched on the mobile and compare that package name with the package names saved in SharedPreferences and display my lock activity instead of that application.
This is the code I have written in my service.
public class DetectorService extends Service {
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
String foregroundTaskPackageName;
RunningTaskInfo foregroundTaskInfo;
try {
Thread.sleep(100);
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
foregroundTaskInfo = am.getRunningTasks(1).get(0);
foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
PackageManager pm = getBaseContext().getPackageManager();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
String[] abc = AppLockerPreference.getInstance(getApplicationContext()).getApplicationList();
for(int i = 0 ; i < abc.length ; i++)
{
if(abc[i].equals(foregroundTaskInfo.topActivity.getPackageName().toString()))
{
Intent lockIntent = new Intent(getApplicationContext(), GalleryImages.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(lockIntent);
}
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And this is my code where I select the applications and save them in SharedPreferences. I am starting the service onPause method of this code.
public class AllAppsActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
AppLockerPreference ap;
String prefApps[];
boolean[] appflag;
int[] arr;
int count = 0;
ImageView ivlock;
Button bloc;
ListView mylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ap = new AppLockerPreference(getApplicationContext());
packageManager = getPackageManager();
new LoadApplications().execute();
mylist = getListView();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
startService(new Intent(this, DetectorService.class));
//Toast.makeText(AllAppsActivity.this, sc.getString("app_loc", ""), Toast.LENGTH_SHORT).show();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ivlock = (ImageView) v.findViewById(R.id.app_lockimg);
if (ivlock.getDrawable() != null) {
ivlock.setImageDrawable(null);
appflag[position] = false;
} else {
ivlock.setImageResource(R.drawable.ic_action_secure);
appflag[position] = true;
}
for (int i = 0; i < appflag.length; ++i) {
if (appflag[i] == true) {
count++;
}
}
arr = new int[count];
int a = 0;
for (int i = 0; i < appflag.length; ++i) {
if (appflag[i] == true) {
arr[a] = i;
a++;
}
}
String[] prefapps = new String[count];
for (int i = 0; i < count; ++i) {
ApplicationInfo data = applist.get(arr[i]);
prefapps[i] = data.packageName.toString();
}
ap.saveCount(count);
ap.saveApplicationList(prefapps);
ap.saveServiceEnabled(true);
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(AllAppsActivity.this, R.layout.snippet_list_row, applist);
appflag = new boolean[listadaptor.getCount()];
for (int i = 0; i < listadaptor.getCount(); i++) {
appflag[i] = false;
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(AllAppsActivity.this, null, "Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
public ApplicationAdapter(Context context, int textViewResourceId, List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
}
ApplicationInfo data = appsList.get(position);
TextView appName = (TextView) view.findViewById(R.id.app_name);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
ImageView lockimg = (ImageView) view.findViewById(R.id.app_lockimg);
String[] prefapps;
prefapps = ap.getApplicationList();
//prefapps = new String[counter];
boolean flag = false;
String label = (String) data.packageName;
for(int i=0;i<prefapps.length;++i)
{
if(prefapps[i].equals(label))
{
flag = true;
//Toast.makeText(AllAppsActivity.this, ddd, Toast.LENGTH_SHORT).show();
}
}
if(flag==true)
{
lockimg.setImageResource(R.drawable.ic_action_secure);
appflag[position]=true;
appName.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
}
else
{
lockimg.setImageDrawable(null);
appflag[position] = false;
appName.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
}
}

I tried on my own and found a way to make the service. Here is the code.
public class DetectorService extends Service {
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
final boolean running = true;
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ActivityManager mActivityManager = (ActivityManager) getSystemService(getApplicationContext().ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
String[] prefs;
AppLockerPreference ap = new AppLockerPreference(getApplicationContext());
prefs = ap.getApplicationList();
for(int i = 0; i < prefs.length ; i++)
{
for(int j = 0; j< RunningTask.size() ; j++)
{
ActivityManager.RunningTaskInfo ar = RunningTask.get(j);
String activityOnTop=ar.topActivity.getPackageName();
if(prefs[i].equals(activityOnTop))
{
Intent lockIntent = new Intent(getApplicationContext(), GalleryImages.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(lockIntent);
}
}
}
}
}
}
).start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

Related

How to Pass gif data from Mainactivity to my Wallpaper Service Class

Here is my MainActivity Where I want to send the chosen GIF To the Wallpaper Service class using Uri :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, 0);
}
});
Button btn1;
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0){
Uri uri = data.getData();
Intent i = new Intent(MainActivity.this,one.class);
i.putExtra("ayush",uri.toString());
startActivity(i);
////////////////
}
}
}
And here is my Second Activity where I want to Receive the Gif data and put it on the movie decode stream. Please Suggest me some ways. Please suggest me some ways to do it.
public void onDestroy() {
super.onDestroy();
}
#Override
public Engine onCreateEngine() {
// TODO Auto-generated method stub
try {
//Movie movie=Movie.decodeStream(getResources().getMovie(R.drawable.endless_staircase));
Movie movie = getResources().getMovie(Intent.getIntent(Uri.parse(//I want to use the get intent extra here )));
return new GIFWallpaperEngine(movie);
} catch (Exception e) {
// TODO: handle exception
Log.d("GIF", "Could Not load Asset");
return null;
}
}
private class GIFWallpaperEngine extends Engine {
private final int frameDuration = 20;
private SurfaceHolder holder;
private Movie movie;
private boolean visible;
private Handler handler;
int mWhen;
long mStart;
float mScaleX, mScaleY;
public GIFWallpaperEngine(Movie movie) {
this.movie = movie;
handler = new Handler();
mWhen = -1;
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
// TODO Auto-generated method stub
super.onCreate(surfaceHolder);//tick();
this.holder = surfaceHolder;
}
private void draw() {
tick();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
canvas.save();
canvas.scale(mScaleX, mScaleY);
if (canvas != null) {
movie.draw(canvas, 0, 0);
}
canvas.restore();
// holder.unlockCanvasAndPost(canvas);
//movie.setTime(((int)(SystemClock.uptimeMillis()-SystemClock.uptimeMillis())%(movie.duration())));
//movie.setTime((int)((System.currentTimeMillis()%movie.duration())));
movie.setTime(mWhen);
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawGIF);
if (visible) handler.postDelayed(drawGIF, 1000L / 25L);
}
void tick() {
int dur = movie.duration();
if (mWhen == -1L) {
mWhen = 0;
mStart = SystemClock.uptimeMillis();
} else {
long mDiff = SystemClock.uptimeMillis() - mStart;
mWhen = (int) (mDiff % dur);
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
super.onSurfaceChanged(holder, format, width, height);
mScaleX = width / (1f * movie.width());
mScaleY = height / (1f * movie.height());
draw();
}
private Runnable drawGIF = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
draw();
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
handler.removeCallbacks(drawGIF);
}
public void onVisibilityChanged(boolean visible) {
// TODO Auto-generated method stub
//super.onVisibilityChanged(visible);
this.visible = visible;
if (visible) {
handler.post(drawGIF);
} else {
handler.removeCallbacks(drawGIF);
}
}
}
}
Please Suggest me Some Ways to do it.

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

How to make error message when on click in list view?

I have pdf reader with list view and cant open all pdf because diffrent password.
source code: https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/
I want pdf that can not open when on click pop up error messages.
can you help me?
Main Activity.java
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Pdf");
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
Log.e("Position", i + "Pdf");
}
});
}
public static ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(".pdf")) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
PdfActivity
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG = "PdfActivity";
int position = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init() {
pdfView = (PDFView) findViewById(R.id.pdfView);
//position = Environment.getExternalStorageDirectory()+"/sdcard/Pdf"
position = getIntent().getIntExtra("position", -1);
displayFromSdcard();
//String position = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Pdf/";
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.password("123456")
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
PdfAdapter
Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;
public PDFAdapter(Context context, ArrayList<File> al_pdf) {
super(context, R.layout.adapter_pdf, al_pdf);
this.context = context;
this.al_pdf = al_pdf;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_pdf.size() > 0) {
return al_pdf.size();
} else {
return 1;
}
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tv_filename.setText(al_pdf.get(position).getName());
return view;
}
public class ViewHolder {
TextView tv_filename;
}
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
if(isPaswordProcted()){
Toast.makeText(this, password procted, Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
}
}
});

Running Bluetooth as background service not working properly

*I am new in android any help please help me and thanks in advance.
I want that bluetooth is always connected in app while switching from one activity to another. so I am making background service . There are two classes first class shows the list of paired device and second class is used to run the bluetooth as background service . There is no error Everything is fine but when I switch the activity Bluetooth is disconnected and also it didn't show the status changed. Ask me If you need any additional information *
This is my first class Homescreen class
public class Homescreen extends Activity {
public static Homescreen home;
private Button mBtnSearch;
private Button mBtnConnect;
private ListView mLstDevices;
private BluetoothAdapter mBTAdapter;
private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
private static final int SETTINGS = 20;
private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
// (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord%28java.util.UUID%29)
private int mBufferSize = 50000; //Default
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
private static final String DEVICE_LIST = "com.blueserial.devicelist";
private static final String DEVICE_LIST_SELECTED = "com.blueserial.devicelistselected";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
private static final String TAG = "BlueTest5-Homescreen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
home=this;
ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one
Log.d(TAG, "Created");
mBtnSearch = (Button) findViewById(R.id.btnSearch);
mBtnConnect = (Button) findViewById(R.id.btnConnect);
mLstDevices = (ListView) findViewById(R.id.lstDevices);
/*
*Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change
*like screen rotate etc. If that's the case then populate all the views that are necessary here
*/
if (savedInstanceState != null) {
ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
if(list!=null){
initList(list);
MyAdapter adapter = (MyAdapter)mLstDevices.getAdapter();
int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
if(selectedIndex != -1){
adapter.setSelectedIndex(selectedIndex);
mBtnConnect.setEnabled(true);
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
mBtnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
} else if (!mBTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, BT_ENABLE_REQUEST);
} else {
new SearchDevices().execute();
}
}
});
mBtnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intt=new Intent(Homescreen.this,BluetoothService.class);
//bindService( intt, null, Context.BIND_AUTO_CREATE);
BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
intt.putExtra(DEVICE_EXTRA, device);
intt.putExtra(DEVICE_UUID, mDeviceUUID.toString());
intt.putExtra(BUFFER_SIZE, mBufferSize);
startService(intt);
// Toast.makeText(Homescreen.this, "Device Connected", Toast.LENGTH_LONG).show();
// BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
// Intent intent = new Intent(getApplicationContext(), MainBluetooth.class);
// intent.putExtra(DEVICE_EXTRA, device);
// intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
// intent.putExtra(BUFFER_SIZE, mBufferSize);
// startActivity(intent);
}
});
}
/**
* Called when the screen rotates. If this isn't handled, data already generated is no longer available
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
MyAdapter adapter = (MyAdapter) (mLstDevices.getAdapter());
ArrayList<BluetoothDevice> list = (ArrayList<BluetoothDevice>) adapter.getEntireList();
if (list != null) {
outState.putParcelableArrayList(DEVICE_LIST, list);
int selectedIndex = adapter.selectedIndex;
outState.putInt(DEVICE_LIST_SELECTED, selectedIndex);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case BT_ENABLE_REQUEST:
if (resultCode == RESULT_OK) {
msg("Bluetooth Enabled successfully");
new SearchDevices().execute();
} else {
msg("Bluetooth couldn't be enabled");
}
break;
case SETTINGS: //If the settings have been updated
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String uuid = prefs.getString("prefUuid", "Null");
mDeviceUUID = UUID.fromString(uuid);
Log.d(TAG, "UUID: " + uuid);
String bufSize = prefs.getString("prefTextBuffer", "Null");
mBufferSize = Integer.parseInt(bufSize);
String orientation = prefs.getString("prefOrientation", "Null");
Log.d(TAG, "Orientation: " + orientation);
if (orientation.equals("Landscape")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (orientation.equals("Portrait")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation.equals("Auto")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Quick way to call the Toast
* #param str
*/
private void msg(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
/**
* Initialize the List adapter
* #param objects
*/
private void initList(List<BluetoothDevice> objects) {
final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
mLstDevices.setAdapter(adapter);
mLstDevices.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedIndex(position);
mBtnConnect.setEnabled(true);
}
});
}
/**
* Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
* will show up with this. I didn't see any need to re-build the wheel over here
* #author ryder
*
*/
private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {
#Override
protected List<BluetoothDevice> doInBackground(Void... params) {
Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
listDevices.add(device);
}
return listDevices;
}
#Override
protected void onPostExecute(List<BluetoothDevice> listDevices) {
super.onPostExecute(listDevices);
if (listDevices.size() > 0) {
MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter();
adapter.replaceItems(listDevices);
} else {
msg("No paired devices found, please pair your serial BT device and try again");
}
}
}
/**
* Custom adapter to show the current devices in the list. This is a bit of an overkill for this
* project, but I figured it would be good learning
* Most of the code is lifted from somewhere but I can't find the link anymore
* #author ryder
*
*/
private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
private int selectedIndex;
private Context context;
private int selectedColor = Color.parseColor("#abcdef");
private List<BluetoothDevice> myList;
public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
super(ctx, resource, textViewResourceId, objects);
context = ctx;
myList = objects;
selectedIndex = -1;
}
public void setSelectedIndex(int position) {
selectedIndex = position;
notifyDataSetChanged();
}
public BluetoothDevice getSelectedItem() {
return myList.get(selectedIndex);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public BluetoothDevice getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView tv;
}
public void replaceItems(List<BluetoothDevice> list) {
myList = list;
notifyDataSetChanged();
}
public List<BluetoothDevice> getEntireList() {
return myList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.tv = (TextView) vi.findViewById(R.id.lstContent);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (selectedIndex != -1 && position == selectedIndex) {
holder.tv.setBackgroundColor(selectedColor);
} else {
holder.tv.setBackgroundColor(Color.WHITE);
}
BluetoothDevice device = myList.get(position);
holder.tv.setText(device.getName() + "\n " + device.getAddress());
return vi;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(Homescreen.this, PreferencesActivity.class);
startActivityForResult(intent, SETTINGS);
break;
}
return super.onOptionsItemSelected(item);
}
}
This is my second class BluetoothService Class
public class BluetoothService extends Service {
public static BluetoothService service;
private boolean mConnectSuccessful = true;
private static boolean isRunning = false;
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
//private UUID mDeviceUUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private boolean mIsBluetoothConnected = false;
//private BluetoothDevice mDevice=Homescreen.home.device;
private BluetoothDevice mDevice;
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
// Intent intt = getIntent();
// Bundle b = intt.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
// super.onStart(intent, startId);
}
#Override
public void onCreate() {
service=this;
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
// TODO Auto-generated method stub
// Intent intent = getIntent();
// Bundle b = intent.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.i("mDeviceUUID", ""+mDeviceUUID);
Log.d("mDevice",""+mDevice );
new ConnectBT().execute();
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
public boolean isRunning() {
return isRunning;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
super.onDestroy();
}
class ConnectBT extends AsyncTask<Void, Void, Void> {
//ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// http://stackoverflow.com/a/11130220/1287554
// progressDialog = ProgressDialog.show(BluetoothService.this, "Hold on", "Connecting");
Log.d("check check check", "check1");
}
#Override
protected Void doInBackground(Void... devices) {
Log.d("check check check", "check2");
try {
Log.e("check check check", "check3");
if (mBTSocket == null || !mIsBluetoothConnected) {
Log.e("UUID", ""+mDeviceUUID);
Log.e("mDevice", ""+mDevice);
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
Log.d("check check check", "check4");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
Log.d("check check check", "check5");
// Toast.makeText(BluetoothService.this, "background service start", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(BluetoothService.this, "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
Log.e("Device Status in service", "Disconnected");
} else {
Toast.makeText(BluetoothService.this, "Connected to device", Toast.LENGTH_SHORT).show();
Log.e("Device Status in service", "Device Connected");
mIsBluetoothConnected = true;
// Kick off input reader
}
//progressDialog.dismiss();
}
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device connected","BT Connected");
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device disconnected","BT Disconnected");
}
//else if...
}
};
}
Android's AsyncTask class will help you. Do the bluetooth discovery task in the doInBackground() method of AsyncTask.You can Toast a message a after the task in the onPostExecute() method. Here is sample code snippet to demonstrate the use of AsyncTask

AutoCompleteTextView Via XMLParsing onTextChange

I have this problem. I need to send a call to my SAX Parser (every time user tries enter name of the student) to get the names. What I am doing right now is sending a token-string to my HttpHandler which is returning 10 records every time because total no of students are about 40K so I can't parse them all at once. I am calling my AsyncTask for ParsingXML in onTextChanged event of AutoCompletetextview. but still I am not able to set the adapter to Autocomplete.
public ArrayList<AutoCompleteUserDataGetterSetter> parsexml(String token)
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL(xyz.com/xyz.ashx?token=+"token"); // URL of the XML
AutoCompleteUserDataXMLHandler myXMLHandler = new AutoCompleteUserDataXMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
return data=AutoCompleteUserDataXMLHandler.getArrayData();
}
Here is my AutoCompleteTextViewAdapter Code
ArrayList<AutoCompleteUserDataGetterSetter> data=new ArrayList<AutoCompleteUserDataGetterSetter>();
public UserNewMessageAutoCompleteAdapater(Context context,
int textViewResourceId,
ArrayList<AutoCompleteUserDataGetterSetter>data) {
super(context, textViewResourceId, data);
// TODO Auto-generated constructor stub
this.context = context;
this.data=data;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final AutoCompleteUserDataGetterSetter i = this.data.get(position);
if (i != null) {
Log.d("adapter", "in here");
AutoCompleteUserDataGetterSetter si = (AutoCompleteUserDataGetterSetter) i;
v = vi.inflate(R.layout.autocompletetext_layout, null);
final TextView title = (TextView) v
.findViewById(R.id.autocomplete_name);
TextView userid = (TextView) v
.findViewById(R.id.autocompleteuserid);
if (title != null)
title.setText(si.GetFullName());
userid.setText(si.GetUserId());
}
return v;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public AutoCompleteUserDataGetterSetter getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
and here is my AsyncTask Class
class SomeTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
UserMessagesComposeNewActivity.this.data=parsexml(users.getText().toString());
for(int i=0;i<data.size();i++)
{
nameadapter.add(data.get(i).GetFullName());
useridadapter.add(data.get(i).GetUserId());
}
if(data==null)
{
AutoCompleteUserDataGetterSetter umsgs=new AutoCompleteUserDataGetterSetter();
umsgs.SetFullName(" ");
umsgs.SetUserID("");
data.add(umsgs);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
users.setAdapter(nameadapter);
}
}
Finally after some head-desking finally sorted the issue Finally!
I gave up the custom adapter approach and used the ArrayAdapter approach. so here is the complete code for my Sending Messages to users via selecting their names.
public class UserMessagesComposeNewActivity extends Activity implements TextWatcher{
ArrayList<AutoCompleteUserDataGetterSetter> data=new
ArrayList<AutoCompleteUserDataGetterSetter>();
Long login;
Boolean shouldAutoComplete;
UserNewMessageAutoCompleteAdapater cdapater;
String TO,FROM;
Button btn;
AutoCompleteTextView users;
EditText edTextSubject,edTextMessage;
AutoCompleteWidget myAutoComplete;
List<String> nameadapter=new ArrayList<String>();
ArrayAdapter<String> dataAdapter ;
UserNewMessageAutoCompleteAdapater atAdapter;
String ResultEmail;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
setContentView(R.layout.user_messages_compose_new);
login=intent.getLongExtra("EmployeedId", 0);
btn=(Button)findViewById(R.id.userNewmessageSendButton);
edTextSubject=(EditText)findViewById(R.id.userNewmessageSubject);
edTextMessage=(EditText)findViewById(R.id.userNewmessageMessage);
users=(AutoCompleteTextView)findViewById(R.id.userNewmessageAutoCT);
users.addTextChangedListener(this);
users.setThreshold(4);
//Here we get the selected value from autocompletetextview dropdown
users.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for(int i=0;i<data.size();i++)
{
if(data.get(i).GetFullName().equals(users.getText().toString()))
{
TO=data.get(i).GetUserId();
}
else
{
TO="0";
}
}
}
});
//here we call the Send Email method.
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DomParserEmail().execute();
}
});
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>=4)
{
new SomeTask().execute();
}
}
class SomeTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
//Here we are parsing the xml
UserMessagesComposeNewActivity.this.data=parsexml(users.getText().toString());
if(data==null)
{
AutoCompleteUserDataGetterSetter umsgs=new AutoCompleteUserDataGetterSetter();
umsgs.SetFullName(" ");
umsgs.SetUserID("");
data.add(umsgs);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
UserMessagesComposeNewActivity.this.nameadapter.clear();
for(int i=0;i<data.size();i++)
{
UserMessagesComposeNewActivity.this.nameadapter.add(UserMessagesComposeNewActivity.this.data.get(i).GetFullName());
}
dataAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, nameadapter);
dataAdapter.notifyDataSetChanged();
users.setAdapter(dataAdapter);
users.showDropDown();
}
}
public ArrayList<AutoCompleteUserDataGetterSetter> parsexml(String token)
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("blah blah"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
AutoCompleteUserDataXMLHandler myXMLHandler = new AutoCompleteUserDataXMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
return data=AutoCompleteUserDataXMLHandler.getArrayData();
}
class DomParserEmail extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Sending your message");
this.dialog.setTitle("Please Wait");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// download and parse
UserMessagesComposeNewActivity.this.ResultEmail=EmailSuccessMessage(UserMessagesComposeNewActivity.this.edTextSubject.getText().toString(),UserMessagesComposeNewActivity.this.edTextMessage.getText().toString(),UserMessagesComposeNewActivity.this.TO,UserMessagesComposeNewActivity.this.login.toString());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
Toast toast=Toast.makeText(getApplicationContext(),UserMessagesComposeNewActivity.this.ResultEmail,Toast.LENGTH_LONG );
toast.show();
}
}
}
public String EmailSuccessMessage(String subject,String content,String To, String From) throws FactoryConfigurationError
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("abc.com/abc.asahx?blah blah");
/**
* Create the Handler to handle each of the XML tags.
**/
UserReplyMessageXMLParsing myXMLHandler = new UserReplyMessageXMLParsing();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
}
catch (Exception e)
{
System.out.println(e);
UserMessagesComposeNewActivity.this.ResultEmail="Email Not Sent";
}
UserReplyMessageXMLParsing usmx=new UserReplyMessageXMLParsing();
UserMessagesComposeNewActivity.this.ResultEmail=usmx.GetEmailStatus();
return UserMessagesComposeNewActivity.this.ResultEmail;
}
}

Categories

Resources