ArrayList<Integer> 's remove method confusing? - Java for Android App Development

Suppose I added a digit '1' to the arraylist<Integer> which is at position 0.So when I call remove method like this.
array.remove(1);
It gives an exception.although the method remove(object) exists.so I how can I remove the object(integer) by not using the position
Sent from my GT-S5570 using XDA Premium 4 mobile app

arpitkh96 said:
Suppose I added a digit '1' to the arraylist<Integer> which is at position 0.So when I call remove method like this.
array.remove(1);
It gives an exception.although the method remove(object) exists.so I how can I remove the object(integer) by not using the position
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
array.remove(new Integer(1));

SimplicityApks said:
array.remove(new Integer(1));
Click to expand...
Click to collapse
That didn't worked.I am using it like this
Code:
//CopyIds is the arraylist
private BroadcastReceiver Copy_Receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Bundle b=arg1.getExtras();
if(b!=null){
int id=b.getInt("id");
Integer id1=new Integer(id);
if(CopyIds.contains(id)){
boolean completed=b.getBoolean("COPY_COMPLETED",false);
View process=rootView.findViewWithTag("copy"+id);
if(completed){ rootView.removeViewInLayout(process);CopyIds.remove(id1);}
else{
String name=b.getString("name");
int p1=b.getInt("p1");
int p2=b.getInt("p2");
long total=b.getLong("total");
long done=b.getLong("done");
((TextView)process.findViewById(R.id.progressText)).setText("Copying \n"+name+"\n"+utils.readableFileSize(done)+"/"+utils.readableFileSize(total)+"\n"+p1+"%");
ProgressBar p=(ProgressBar)process.findViewById(R.id.progressBar1);
p.setProgress(p1);
p.setSecondaryProgress(p2);}
}else{
View root=getActivity().getLayoutInflater().inflate(R.layout.processrow, null);
root.setPaddingRelative(10,10,10,10);
String name=b.getString("name");
int p1=b.getInt("p1");
int p2=b.getInt("p2");
root.setTag("copy"+id);
((TextView)root.findViewById(R.id.progressText)).setText("Copying \n"+name);
ProgressBar p=(ProgressBar)root.findViewById(R.id.progressBar1);
p.setProgress(p1);
p.setSecondaryProgress(p2);
CopyIds.add(id);
rootView.addView(root);
}
}
}};
Log says error receiving broadcast.arryindexoutofbounds exception ,size 1 index 1
Sent from my GT-S5570 using XDA Premium 4 mobile app

arpitkh96 said:
That didn't worked.I am using it like this
Code:
//CopyIds is the arraylist
private BroadcastReceiver Copy_Receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Bundle b=arg1.getExtras();
if(b!=null){
int id=b.getInt("id");
Integer id1=new Integer(id);
if(CopyIds.contains(id)){
boolean completed=b.getBoolean("COPY_COMPLETED",false);
View process=rootView.findViewWithTag("copy"+id);
if(completed){ rootView.removeViewInLayout(process);CopyIds.remove(id1);}
else{
String name=b.getString("name");
int p1=b.getInt("p1");
int p2=b.getInt("p2");
long total=b.getLong("total");
long done=b.getLong("done");
((TextView)process.findViewById(R.id.progressText)).setText("Copying \n"+name+"\n"+utils.readableFileSize(done)+"/"+utils.readableFileSize(total)+"\n"+p1+"%");
ProgressBar p=(ProgressBar)process.findViewById(R.id.progressBar1);
p.setProgress(p1);
p.setSecondaryProgress(p2);}
}else{
View root=getActivity().getLayoutInflater().inflate(R.layout.processrow, null);
root.setPaddingRelative(10,10,10,10);
String name=b.getString("name");
int p1=b.getInt("p1");
int p2=b.getInt("p2");
root.setTag("copy"+id);
((TextView)root.findViewById(R.id.progressText)).setText("Copying \n"+name);
ProgressBar p=(ProgressBar)root.findViewById(R.id.progressBar1);
p.setProgress(p1);
p.setSecondaryProgress(p2);
CopyIds.add(id);
rootView.addView(root);
}
}
}};
Log says error receiving broadcast.arryindexoutofbounds exception ,size 1 index 1
Click to expand...
Click to collapse
Strange since I don't get any compile time errors (sorry don't have time to test it right now) and that should be the way to do it...
Anyway, if it still doesn't work for you, just manually search for the right index using get().equals in a for loop and remove the element at the right index then... (that's what the remove(Object) method does anyway).

SimplicityApks said:
array.remove(new Integer(1));
Click to expand...
Click to collapse
That works. But why ArrayList is not generified. I would like to use it like:
Code:
arrayList.<Integer>remove(new Integer(1));
It would throw Compiler time Error in case if you pass object of wrong type, which would safe time people like OP.

SimplicityApks said:
Strange since I don't get any compile time errors (sorry don't have time to test it right now) and that should be the way to do it...
Anyway, if it still doesn't work for you, just manually search for the right index using get().equals in a for loop and remove the element at the right index then... (that's what the remove(Object) method does anyway).
Click to expand...
Click to collapse
I solved it
Sent from my GT-S5570 using XDA Premium 4 mobile app

Related

Preference changes only happen when restarting the app

Hey there! I was coding an app I added a preferences menu, and it works, but changes happen only when I restart the application,anyone knows how to make changes happen whithout exitting the app??? Thanks in advance
My code ( from main activity):
preferencias = preferenceManager.getDefaultSharedPreferences(TimeToSpeechActivity.this);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//nothing here, do I have to put anything?
}
};
preferencias.registerOnSharedPreferenceChangeListener(listener);
getPrefs();
changefont(fuente, letra);
if (boole == true) {fontcolors();}
private void getPrefs(){
fuente = Typeface.createFromAsset(getAssets() , preferencias.getString("elegirfuente", "fonts/Default.ttf"));
letra = Integer.parseInt(preferencias.getString("fontstyle", "0"));
bol = preferencias.getBoolean("randomcolors", true);
}
Click to expand...
Click to collapse
I have nothing put in preference activity, do i have to put anything?
Also, do I have to edit this?: (SharedPreferences prefs, String key) I ask this because i havent created prefs and key varibles
Thanks in advance!!!
It should update for you if you put getPrefs() inside the sharedpreferences listener
Sent from my Xoom using xda premium
thanks, but if I do that I get a nullpointer exception, I think its caused because the params I use to set "changefont(fuente, letra);" and "if (boole == true) {fontcolors();}" have null value....another idea ,please? I am breaking my head with this...
My updated code:
preferencias = preferenceManager.getDefaultSharedPreferences(Time ToSpeechActivity.this);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener () {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
getPrefs();
}
};
preferencias.registerOnSharedPreferenceChangeListener(listener);
changefont(fuente, letra);
if (boole == true) {fontcolors();}
private void getPrefs(){
fuente = Typeface.createFromAsset(getAssets() , preferencias.getString("elegirfuente", "fonts/Default.ttf"));
letra = Integer.parseInt(preferencias.getString("fontstyle ", "0"));
bol = preferencias.getBoolean("randomcolors", true);
}
Click to expand...
Click to collapse
i tried to put changefont and fontcolors functions inside the sharedpreference listener... but if i do, that options are not set... so I think there is a problem with the listener...why???
I will add the code of my preference class:
public class PantallaOpciones extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.opciones);
}
}
Click to expand...
Click to collapse
One way ive always done preference updates was to use a dedicated method for updating (like you have with openPrefs()) then calling it after operations:
runOperation(){
updatePrefsMethod();
getPrefsMethod();
}
If i was near my pc i could give you a more solid example, but alas, im stuck at work lol
Also, use the stacktraces to check which line gives it null (itll say something like "at com.yourapp.identifier(offending Class - line number)
maybe if you a null check on the boolean for color that sets it false, you may not get the nullPointerException
Sent from my Xoom using xda premium
z3nful said:
One way ive always done preference updates was to use a dedicated method for updating (like you have with openPrefs()) then calling it after operations:
runOperation(){
updatePrefsMethod();
getPrefsMethod();
}
If i was near my pc i could give you a more solid example, but alas, im stuck at work lol
Also, maybe if you a null check on the boolean for color that sets it false, you may not get the nullPointerException
Sent from my Xoom using xda premium
Click to expand...
Click to collapse
OK, could you give me an example as soon as you can,please?

[Q]need help to make an xposed module

I am trying to make an xposed module(private use) to implement clear all button(ImageView) in recents.
Here is my code
Code:
package com.mycompany.myapp3;
import android.graphics.*;
import android.view.*;
import android.widget.*;
import de.robv.android.xposed.*;
import de.*;
import de.robv.android.xposed.callbacks.*;
import de.robv.android.xposed.callbacks.XC_LoadPackage.*;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
public class MainActivity implements IXposedHookLoadPackage
{ImageView m;
String rc="com.android.systemui.recent.RecentsPanelView";
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable
{
findAndHookMethod(rc, lpparam.classLoader, "updateClock", new XC_MethodHook() {
@Override
protected void afterHookedMethod(final MethodHookParam param) throws Throwable
{
m.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
ViewGroup mRecentsContainer = (ViewGroup) XposedHelpers.getObjectField(
param.thisObject, "mRecentsContainer");
// passing null parameter in this case is our action flag to remove all views
mRecentsContainer.removeViewInLayout(null);
}
});
}
});
}}
Now the problem is that i have already that ImageView in recent_panel.xml with no action assigned.i know its id and want to implement onclick action to that ImageView only by using its id.so what code should i add so that code recognises that ImageView and assigns it the above onclick action
Sent from my GT-S5570 using XDA Premium 4 mobile app
It's only an idea and maybe it doesn't solve your problem: Have you tried to hook onCreate and use the this-Object to call findViewById?
And you are making a mistake: You have to look, whether the loaded package is your specific package you want to hook. You try to hook every app.
Regards
EmptinessFiller said:
It's only an idea and maybe it doesn't solve your problem: Have you tried to hook onCreate and use the this-Object to call findViewById?
And you are making a mistake: You have to look, whether the loaded package is your specific package you want to hook. You try to hook every app.
Regards
Click to expand...
Click to collapse
1. this-object.?Can you give an example?
2.yes you are right i will fix it
Sent from my GT-S5570 using XDA Premium 4 mobile app
Sth. like m = (ImageView) ((Activity) param.thisObject).findViewById(id);
(Not tested)
EmptinessFiller said:
Sth. like m = (ImageView) ((Activity) param.thisObject).findViewById(id);
(Not tested)
Click to expand...
Click to collapse
I have got the solution already.thanks for your help
Sent from my GT-S5570 using XDA Premium 4 mobile app

[Q]Problem in loading icons of apks(files) using asynctask

Here are the adapter and asynctask class
Code:
class Myadapter extends ArrayAdapter<Layoutelements> {
Context context;
public Myadapter(Context context, int resourceId,List<Layoutelements> items) {
super(context, resourceId, items);
this .context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder holder = null ;
Layoutelements rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.rowlayout, null );
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.secondLine);
holder.txtTitle = (TextView) convertView.findViewById(R.id.firstline);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.txtDesc.setText(rowItem.getDesc().toString());
holder.txtTitle.setText(rowItem.getTitle());
String ext=getFileExtension(rowItem.getDesc());
if(ext.equals(".apk"))
{holder.imageView.setImageDrawable(rowItem.getImageId());
holder.imageView.setTag(rowItem.getDesc());//
////tag of imageView == path
////to image
new ImageDownloaderTask(holder.imageView).execute(rowItem.getDesc());
}
else if(ext.equals(".png") || ext.equals(".jpg") || ext.equals(".jpeg"))
{holder.imageView.setImageDrawable(rowItem.getImageId());
holder.imageView.setTag(rowItem.getDesc());//
////tag of imageView == path
////to image
new LoadImage(holder.imageView).execute(rowItem.getDesc());
}
else{
holder.imageView.setImageDrawable(rowItem.getImageId());}
return convertView;
}
}
Code:
class ImageDownloaderTask extends AsyncTask<String, Void, Drawable> {
private final WeakReference<ImageView> imageViewReference;
private String path;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
// Actual download method, run in the task thread
protected Drawable doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
path =params[0];
try{PackageManager pm=getPackageManager();
PackageInfo pi=pm.getPackageArchiveInfo(path,0);
//// the secret arethese two lines....
pi.applicationInfo.sourceDir=path;
pi.applicationInfo.publicSourceDir=path;
////
return pi.applicationInfo.loadIcon(pm);
}catch(Exception e){return getResources().getDrawable(R.drawable.apk);}
}
@Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Drawable bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageDrawable(bitmap);
} else {
imageView.setImageDrawable(imageView.getContext().getResources()
.getDrawable(R.drawable.apk));
}
}
}
}
}
I am making a file manager.
Now the problem is like this.
If i scroll down icons load correctly. But when i scroll up, the icons load again.they are not cached once they are loaded.i want that icons are cached till directory is changed.
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
I am making a file manager.
Now the problem is like this.
If i scroll down icons load correctly. But when i scroll up, the icons load again.they are not cached once they are loaded.i want that icons are cached till directory is changed.
Click to expand...
Click to collapse
Try using an LruCache or your images. Also, you might want to take a look at this guide explaining it further.
SimplicityApks said:
Try using an LruCache or your images. Also, you might want to take a look at this guide explaining it further.
Click to expand...
Click to collapse
Thanks i will check them
Sent from my GT-S5570 using XDA Premium 4 mobile app
It worked but is buggy.the images many times get blurred after scrolling up as shown in screenshots.See the thumbnails in both images
Sent from my GT-S5570 using XDA Premium 4 mobile app
After scroll
Is this due to low cache memory.should i try on another device.should i show you the new modified code.
Sent from my GT-S5570 using XDA Premium 4 mobile app

[Guide] Listeners in Java development

You are new to java development and want to get buttons working?
Maybe you are a Pro but want a reminder?
whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional
Some people are distracted between guides over internet and want the easiest way to get their project working, me too
Steps :
1-Define the button :
Code:
Button btn1;
Checkbox chkbox1;
RadioButton radio1;
2- Intialize it :
Code:
btn1 = (Button) findViewById(R.id.btn1);
chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
radio1= (RadioButton) findViewById(R.id.radio1);
3-Add the listener :
Button:
Code:
btn1.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
//Write awesome code here
}
});
CheckBox :
Code:
chkbox1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (start.isChecked()) {
//if the checkbox checked
} else {
//if not checked
}
}
});
}
radio button:
Code:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio1:
if (checked){
}
else{
}
break;
}
}
or use it in a radio Group :
Code:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio1:
if (checked)
//Write code
break;
case R.id.radio2:
if (checked)
//Write code
break;
}
}
Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
____________________________________________________________________
____________________________________________________________________
Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )
after defining and initializing your objects add this :
Code:
OnClickListener click_listener = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == your_id) {
//do stuff for this object
} else if (id == your_id2) {
//do other stuff for diffrent object
} else if (id == your_id3) {
//and so on
}
}
};
To do list :
-add on touch listeners
-add on drag listeners
Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button
also there is some other ways to add a listener but this is the fastest and less disturbing :good:
If this guide is useful, press thanks
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Click to expand...
Click to collapse
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
Click to expand...
Click to collapse
I meant that the op shuld edit this guide and use those instead of OnCickListeners
GalaxyInABox said:
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
ya new with java8 it will be a nice usage scenario of lambadas
Sent from my GT-S5302 using Tapatalk 2
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
ok, i will add this
You can also add onClick property in XML and then handle it in a code.
Awesome tutorial! Thank you very much!
Please, you could share more related knowledge. It's really useful!
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
For this kind of stuff, using some well known libraries from well known Android dev is a must.
https://github.com/JakeWharton/butterknife
Very powerfull, super easy to use, error prone and without any performance impact.
rafalniski said:
You can also add onClick property in XML and then handle it in a code.
Click to expand...
Click to collapse
SKAm69 said:
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
Click to expand...
Click to collapse
will add them both, although I don't like this way
Mohamedrashad. Thanks a lot.
Sent from my P880 using Tapatalk
If you have multiple clickable objects then it's best to use just 1 onClickListener for all of them and use a switch on their ID's. This reduces resource usage as you only have 1 listener, not 5, 10 or however many you would have otherwise. It's not essential for this but it is a best practice if you want to streamline your code.
Mobile right now so I can't chuck up an example until tomorrow evening or so.
You dude had a great thread. Its helping me. Bravoo !!
Sent from my GT-I8190 using XDA Premium 4 mobile app
As @Jonny already pointed out: Use your class as a listener instead of creating a new (anonymous) inner class! Say you have a ListView, instead of doing this:
Code:
class MyFragment extends Fragment {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
});
}
}
you can do this:
Code:
class MyFragment extends ListFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
}
This may look stupid, but when you have many listeners, you can un-clutter it. In my opinion this is the best way. You can also add "this" class as listener for as many ui elements as you want(because all of them extend view, you can use one OnClickListener), then you only need to have a switch statement to distinguish between the views. And voila, you prevented cluttering the code with boilerplate stuff.
Example using code in an app I'm making - app for my school.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.website_btn :
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
break;
case R.id.facebook_btn :
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
break;
case R.id.twitter_btn :
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
break;
}
}
};
Jonny said:
Example using code in an app I'm making.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == R.id.website_btn) {
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
} else if (id == R.id.facebook_btn) {
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
} else if (id == R.id.twitter_btn) {
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
}
}
};
Click to expand...
Click to collapse
i'm adding this to OP if you don't mind jonny
mohamedrashad said:
i'm adding this to OP if you don't mind jonny
Click to expand...
Click to collapse
That's fine - if I didn't want people to use/adapt/learn from the code then I wouldn't put it up, use it as you want :good:
Sent from my HTC One using Tapatalk
Keep it up
Great tutorials, keep em coming!
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Rebound.co said:
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Click to expand...
Click to collapse
in the onClick method just have this code:
Code:
startActivity(new Intent(this, YourActivity.class));

[Q]Service doesn't stop even after calling stopService

Here is the service
Code:
public class SearchService extends IntentService {
public SearchService() {
super("SearchService");
// TODO Auto-generated constructor stub
}
// Binder given to clients
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
[user=439709]@override[/user]
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String FILENAME=intent.getStringExtra("name");
String FILEPATH=intent.getStringExtra("path");
ArrayList a=getSearchResult(new File(FILEPATH),FILENAME);
Toast.makeText(this, "Search Completed", Toast.LENGTH_LONG).show();
publishResults(a);
this.stopSelf();
}
private void publishResults(ArrayList<File> outputPath) {
Intent intent = new Intent("notify");
ArrayList<String> a=new ArrayList<String>();
for(int i=0;i<outputPath.size();i++){a.add(outputPath.get(i).getPath());}
intent.putStringArrayListExtra("path", a);
sendBroadcast(intent);
} private void publishResults(String a) {
Intent intent = new Intent("current");
intent.putExtra("name", a);
sendBroadcast(intent);
}}
I am using it like this
Code:
final Intent intent = new Intent(getActivity(), SearchService.class);
intent.putExtra("path",fpath);
intent.putExtra("name",a);
p=new ProgressDialog(getActivity());
p.setCancelable(false);
p.setTitle("Searching Files");
p.setMessage("Please Wait");
p.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
p.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
getActivity().stopService(new Intent(getActivity(),SearchService.class));
// TODO: Implement this method
}
});
p.show();
getActivity().startService(intent);
but even after pressing cancel button,broadcast is received in activity
Sent from my GT-S5570 using XDA Premium 4 mobile app
A service to display a toast and brodcast the data it recieved looks like a design flaw
anyways you are extending the intent service i guess it does not implement stopService() rather it stops automatically when it has nothing to do[not sure with it please check documentation for IntentService never actually used one of those ]
I guess you need to extend the Service class from package android.app
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
A service to display a toast and brodcast the data it recieved looks like a design flaw
anyways you are extending the intent service i guess it does not implement stopService() rather it stops automatically when it has nothing to do[not sure with it please check documentation for IntentService never actually used one of those ]
I guess you need to extend the Service class from package android.app
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
Actually I am using toast just for debugging.I am learning services. so I might be wrong at places.I made this service to search for files while an indeterminate progress dialog shows in activity till the broadcast of result is received.
I used intentservice because it was supposed to do one work at a time.please suggest me exact ways to use service in my case.I also want to make sure that if activity is paused(minimized) then, when task is completed activity is also started
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
Actually I am using toast just for debugging.I am learning services. so I might be wrong at places. I made this service to search for files while an indeterminate progress dialog shows in activity till the broadcast of result is received.
I used intentservice because it was supposed to do one work at a time.please suggest me exact ways to use service in my case.I also want to make sure that if activity is paused(minimized) then, when task is completed activity is also started
Click to expand...
Click to collapse
You can still use an IntentService to do that. To stop it just pass an Intent to it with a boolean extra indicating that you don't want to do anything. You'll need only one more if clause in the onHandleIntent of the service.
SimplicityApks said:
You can still use an IntentService to do that. To stop it just pass an Intent to it with a boolean extra indicating that you don't want to do anything. You'll need only one more if clause in the onHandleIntent of the service.
Click to expand...
Click to collapse
That didnt worked I used it like this.
Code:
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String FILENAME=intent.getStringExtra("name");
String FILEPATH=intent.getStringExtra("path");
boolean b=intent.getBooleanExtra("run",false);
while(b){
ArrayList<File> a=getSearchResult(new File(FILEPATH),FILENAME);
publishResults(a);
this.stopSelf();}
}
Code:
final Intent intent = new Intent(getActivity(), SearchService.class);
intent.putExtra("path",fpath);
intent.putExtra("name",a);
intent.putExtra("run",true);
p=new ProgressDialog(getActivity());
p.setCancelable(false);
p.setTitle("Searching Files");
p.setMessage("Please Wait");
p.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
p.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
Intent j=new Intent(getActivity(),SearchService.class);
j.putExtra("run",false);
getActivity().stopService(j);
// TODO: Implement this method
}
});
p.show();
getActivity().startService(intent);
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
That didnt worked I used it like this.
Code:
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String FILENAME=intent.getStringExtra("name");
String FILEPATH=intent.getStringExtra("path");
boolean b=intent.getBooleanExtra("run",false);
while(b){
ArrayList<File> a=getSearchResult(new File(FILEPATH),FILENAME);
publishResults(a);
this.stopSelf();}
}
Code:
final Intent intent = new Intent(getActivity(), SearchService.class);
intent.putExtra("path",fpath);
intent.putExtra("name",a);
intent.putExtra("run",true);
p=new ProgressDialog(getActivity());
p.setCancelable(false);
p.setTitle("Searching Files");
p.setMessage("Please Wait");
p.getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
p.setButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
Intent j=new Intent(getActivity(),SearchService.class);
j.putExtra("run",false);
getActivity().stopService(j);
// TODO: Implement this method
}
});
p.show();
getActivity().startService(intent);
Click to expand...
Click to collapse
First, if you look in the Dokumentation for IntentService, it says that you should not call stopSelf because it is already implemented to do that when there are no intents left. So It really should be easier to use a Service if you want to stop it like that.
If you want to keep using the intent service, I'd instead use a boolean instance variable which is checked in the publishResults method so just let the service do its work, but before it is published in the UI thread check if the dialog was canceled or not. Otherwise because you have two threads you can't be sure when the other thread receives the boolean change.
To me it seems like you could also use an AsyncTask to handle the threading and that class is easily cancelable .
SimplicityApks said:
First, if you look in the Dokumentation for IntentService, it says that you should not call stopSelf because it is already implemented to do that when there are no intents left. So It really should be easier to use a Service if you want to stop it like that.
If you want to keep using the intent service, I'd instead use a boolean instance variable which is checked in the publishResults method so just let the service do its work, but before it is published in the UI thread check if the dialog was canceled or not. Otherwise because you have two threads you can't be sure when the other thread receives the boolean change.
To me it seems like you could also use an AsyncTask to handle the threading and that class is easily cancelable .
Click to expand...
Click to collapse
I cannot use Asynctask ,as operation could be long.checking the boolean before publish is good idea.I will try this
Sent from my GT-S5570 using XDA Premium 4 mobile app

Categories

Resources