I have been using a hand built ListActivity as my AppWidget config Activity but to be honest it looks ****ty and doesnt fit in with the rest of the app. So i wanted to transition over to a PreferenceActivity. i made a stub of a PreferenceActivity that launches the layout just fine when it is the main activity. but when i try to change from my ListActivity to my PreferenceAcitivity i get no launching of PreferenceActivity when i launch my widget. all i get is my widget.
i did a refactoring of my xml files to change the instances of my ListActivity (GITextConfig) to my PreferenceActivity (GITextPreferences).
how can i use a PreferenceActivity as my config?
do i need to have a dummy Activity be the config with a button to launch the PreferenceActivity? cause that works just fine. its lame and shouldnt be that way... nvm that does not work... i just cant get a prefs activity to run from an appwidget
anyone? this is quite annoying... i know it can be done as other widgets like gmail unread count does this. at least it appears to have a preferenceactivity as the configuration
got it to work. i dont know what i was doing before but i think i had a little too much of a stub for it to work. after i implemented the appwidget id verification and created my PreferenceManger and overode the onBackPressed() method it seems to work.... happy and confused.
Code:
public class GITextPreferences extends PreferenceActivity {
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager localPrefs = getPreferenceManager();
localPrefs.setSharedPreferencesName("GITC_Prefs");
addPreferencesFromResource(R.xml.gitc_preferences);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
}
@Override
public void onBackPressed() {
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
}
I had a class which i wanted to split into two for better readability and whenever i want to start a method from the second class the code gives NullPointerException.
So i ended up making another dummyclass and realized the problem is that either i dont know to to call from another class in android or am facing another issue.
In java id just make an object and call it but here NullPointerException and app crashes
Code:
public class active extends Activity {
public Button but;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void click()
{
but = (Button)findViewById(R.id.wifiSwitch);
but.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Rebooting...", Toast.LENGTH_LONG).show();
}
});
}
}
In the first class i do the following
Code:
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
rootReqSetting();
mActive = new active();
mActive.click();
return true;
}
the mActive = new active(); and mActive.click(); causes the nullexception.
Some help please ?
Well, first I request that you post logcats in the future.
Second: You call that:
Code:
but = (Button)findViewById(R.id.wifiSwitch);
but.setOnClickListener(new View.OnClickListener() {
What is the system doing? There is a new object whose onCreate method has never been called (just the constructor). For that reason the field but is null (equals "no value"). That's why it crashes.
Third: You do not do it that way:
mActive = new active();
Starting other Activities is done using Intents. Read this: http://www.vogella.com/articles/AndroidIntent/article.html
Where in the code did you inflate the wifi button ????
That is the cause of NullPointerException
Secondly,
You cant instantiate activities like this you must use
startActivity(Intent);
Sent from my GT-S5302 using Tapatalk 2
Thank you for you answer.
The Third part i understood that i should make an intent for the second class.
About the second part you said i didnt understand correctly , can you explain a little more ?
@sak-venom1997 what do you mean by inflate the button, didnt the whole menu get inflated when i called it in the first ?
Code:
getMenuInflater().inflate(R.menu.main, menu);
or there is something i should add?
And a new window will show when i start the intent without calling anything in it. i just want the button to do what it is supposed to do.
Tell me how the hell did you manage to put a Button in a MenuItem that code would just infate the menu Button would be infalted only if the parent layout is inflated
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
Tell me how the hell did you manage to put a Button in a MenuItem that code would just infate the menu Button would be infalted only if the parent layout is inflated
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
can you tell me then what am supposed to do, Am new to android and trying to learn.
You must call
setContentView(R.layout.layout_name);
Where is that button ure reffering
Sent from my GT-S5302 using Tapatalk 2
I am currently trying to implement an app that has a service running until the user explicitly ends it via the app. I would like the service to remain on otherwise. My current problem is that whenever the app is removed from the recent apps, it terminates the service as well. I have tried using START_STICKY in my onStartCommand but it doesn't change anything.
Code:
public class TriggerService extends Service{
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
and here is my code for when I call the service:
Code:
public void startServ(boolean state){
editor = sp.edit();
if (state == true) {
startService(new Intent(currentActivity, TriggerService.class));
editor.putBoolean("service_status", true);
toast = Toast.makeText(currentActivity, "Service Running", Toast.LENGTH_SHORT);
toast.show();
} else {
stopService(new Intent(currentActivity, TriggerService.class));
editor.putBoolean("service_status", false);
toast = Toast.makeText(currentActivity, "Service Not Running", Toast.LENGTH_SHORT);
toast.show();
}
editor.commit();
}
EDIT: I tried adding
Code:
android:isolatedProcess="true"
to the manifest but it didn't help. I tried a few things that were recommended over here but so far no dice
Check this article, it also suggests a potential solution
http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-is-on-the-way/
And this open issue
https://code.google.com/p/android/issues/detail?id=63793
painlessDeath said:
Check this article, it also suggests a potential solution
http://www.androidpolice.com/2014/0...ated-background-services-a-fix-is-on-the-way/
And this open issue
https://code.google.com/p/android/issues/detail?id=63793
Click to expand...
Click to collapse
You are a god send. Tested the app on JB and the service stayed when I closed the app. Thank god.
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));
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