Make a Preference (inside a PreferenceFragment) responds to a click - java

I'm trying to make a preference react to a user-input but with no luck. I'm using PreferenceFragment and seems that not a single code I found so far can help me.
Here is my preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen " >
<PreferenceCategory
"
" >
<CheckBoxPreference
"
"
o aplicativo para uso"
aplicativo" />
</PreferenceCategory>
</PreferenceScreen>
And here is my screen code:
package com.gh0st.gerenciador;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TelaPreferencias extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "prefs_ativar";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment()).commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tela_preferencias, menu);
return true;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Toast.makeText(this, "Teste", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
}
I want that, when I touch on the preference, it shows a toast. The code seems to be fine (no errors), but it doesn't work. I think I didn't get the idea behind the listener. Can somebody help me out?
Thanks!
Before I forget, I'm using API level 19 (Android 4.4). I don't know if this changes something.

Missing the registration of the listener? This is how I do that:
// Register the listener
#Override
protected void onResume()
{
// Register OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
registerOnSharedPreferenceChangeListener(this);
// Fire the base method
super.onResume();
}
// Unregister the listener
#Override
protected void onPause()
{
// Unregister OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
unregisterOnSharedPreferenceChangeListener(this);
// Fire the base method
super.onPause();
}

I suggest you make use of the
Preference.OnPreferenceClickListener
You can find more about it here: http://developer.android.com/reference/android/preference/Preference.OnPreferenceClickListener.html
Example:
Preference p = findPreference("yourkey");
p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
// TODO stuff
return true;
}
});
Edit concerning deprecation:
PreferenceActivity.findPreference("key") --> deprecated
PreferenceFragment.findPreference("key") --> not deprecated

Related

In android studio cannot resolve method 'findViewById'

I am joining two activity through intent
package com.smartcodeone.newapp1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final String STRING_VAR = "com.smartcodeone.newapp1.HELLO_WORLD";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnMsg = (Button) findViewById(R.id.btnMsg);
btnMsg.setOnClickListener(new View.OnClickListener(){
//when user click's this function will be called
public void onClick(View v){
Intent intentvar = new Intent(getApplicationContext(),Main2Activity.class);
intentvar.putExtra(STRING_VAR,"Hello World"); //this is used to pass data to next intent
startActivity(intentvar);
}
});
}
private int findViewId(int btnMsg) {
return 0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public android.support.v4.app.FragmentManager getSupportFragmentManager() {
return null;
}
}
It might have to do with Android Studio. Try cleaning your project and then rebuilding. If that doesn't work go to File -> Invalidate Caches/Restart ...
I get those issues sometimes as well. Let me know if that works. I tried your code and it works fine.
The issue seems to be that you defined a method named: findViewById(int button) that always return 0.
Use the Activity method instead of your own:
this.findViewById(int resourceId)
Good luck!
It seems you are implementing your own findviewbyid(). I don't know if you intend to do so.
Try removing
private int findviewbyid(int btnMsg) {
}
The ActionBarActivity's findviewbyid should resolve your button from your layout file.

Android: Saving an ArrayList to SharedPreferences, but loading it is not working

After asking a similar question this morning, I did more research and found (I think) a way to save/load my ArrayList by saving it to SharedPreferences (After converting it to a Json String).
The problem is, I don't know where to put my saveListe() and my loadListe().
I don't get any error, but when restarting the application, the list is still the default one (It has 1 game in it).
Those 2 methods and my list are in a ListeJeux Class.
I tried using loadListe() in my mainActivity, and I used saveListe() in another activity (that add a game to the list for test purposes) just after adding a game.
If I launch the other activity, it adds a game to the list (this part is working), but if I restart the application, the list still contains 1 game only (default). What is the problem?
ListeJeux (contains save and load methods + the default list):
package com.example.jouons;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
#SuppressWarnings("deprecation")
public class ListeJeux extends ActionBarActivity {
// By default, the list contains one game, if the listView show more than
// one, then addJeu() works, if it still shows more than one game after a
// restart, then the save/load works (not working for now).
static Jeu jeu1 = new Jeu("Ballon fou", "moyens grands", "intérieur");
static ArrayList<Jeu> jeux = new ArrayList<>(Arrays.asList(jeu1));
// This is only to test.
static void addJeu() {
jeux.add(new Jeu("Ballon fou", "moyens grands", "intérieur"));
}
// Takes "jeux" (this is where the problem happens, I think), and makes it a
// Json String. Then store it in SharedPreference.
static public void saveListe(Context context) {
Gson gson = new Gson();
String listeJson = gson.toJson(jeux);
SharedPreferences prefs = context.getSharedPreferences("listePrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("listeEditor", listeJson);
editor.commit();
}
// Takes the contain of the SharedPreference (Json String) and reverts it to
// an ArrayList. Then returns it.
static public ArrayList<Jeu> loadListe(Context context) {
Gson gson = new Gson();
SharedPreferences prefs = context.getSharedPreferences("listePrefs", MODE_PRIVATE);
String extractedJson = prefs.getString("listeEditor", "");
Type type = new TypeToken<ArrayList<Jeu>>() {
}.getType();
ArrayList<Jeu> jeux = gson.fromJson(extractedJson, type);
return jeux;
}
}
The MainActivity (in which I use the loadList() method):
package com.example.jouons;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
#SuppressWarnings("deprecation")
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListeJeux.loadListe(this);
setupTrouvezButton();
setupRechercherButton();
setupListeButton();
}
private void setupListeButton() {
Button listeButton = (Button) findViewById(R.id.btnMainListe);
listeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ListeActivity.class));
}
});
}
private void setupTrouvezButton() {
Button trouvezButton = (Button) findViewById(R.id.btnMainTrouvez);
trouvezButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, TrouvezActivity.class));
}
});
}
private void setupRechercherButton() {
Button rechercherButton = (Button) findViewById(R.id.btnMainRechercher);
rechercherButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RechercherActivity.class));
}
});
}
#Override
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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And the other activity (that add a game to the list then save it):
package com.example.jouons;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
#SuppressWarnings("deprecation")
public class RechercherActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rechercher);
ListeJeux.addJeu();
ListeJeux.saveListe(this);
setupRetourButton();
}
private void setupRetourButton() {
Button retourButton = (Button) findViewById(R.id.btnRechercherRetour);
retourButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.rechercher, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you want to save a arraylist to the shared prefrence, you have to serialize the arraylist before you saving. I would prefer saving a serialized object to the sdcard instead of saving it to the shared prefrence, if it is not a confidantial information. if it is a cache file, i would recomend you save it to the app cache directory.
Serialize an object
public class SomeClassName implements Serializable{
private ArrayList<SomeObject> arrayList;
public void setObject(ArrayList<SomeObject> list){
arrayList = list;
}
public ArrayList<SomeObject> getObject(){
return arrayList;
}
}
ActionBarActivity although it is deprecated, it extends Activity, so you should be able to override onCreate, onResume and onPause to call your methods to load and save. For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rechercher);
setupRetourButton();
}
#Override
protected void onResume()
{
super.onResume();
ArrayList<Jeu> loaded = ListeJeux.loadListe(this);
for (Jeu j: loaded)
{
// This method to add doesn't exist and this whole loop should
// be refactored into the loadListe method.
ListeJeux.addJue(j)
}
// This size() method doesn't exist either and could also be subsumed into loadList
if (ListeJeux.size() == 0)
{
ListeJeux.addJeu();
ListeJeux.saveListe(this);
}
}
#Override
protected void onPause()
{
// Save the list as the app may stop any time after a pause.
ListeJeux.saveListe(this);
super.onPause();
}
Personally, I would refactor the code a little so the save and load methods on the list (ListeJeux), actually update the internal list. As you can see from the diagram at the top of this Android Documentation, you really only need to load in onResume as it should always be called before the Activity is displayed.

Declaration of MapView (ArcGIS for Android) Center and Zoom

I am begginer in java and ArcGIS for android. I want to make simple app with MapView.
I have problem with declaration of MapView center and Zoom. I need to do it programmatically (application startup) in java file, not in xml file. I will try explain it on on simple example.
Problem is in mMapView.setMapOptions(options); I need to do in onCreate(), if I make Button with mMapView.setMapOptions(options); everything is OK. I searched solution in samples and on the internet, but I think, that I do not know how to ask on it.
Sorry for my english and thank you for your comments.
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.esri.android.map.MapOptions;
import com.esri.android.map.MapView;
public class MainActivity extends Activity {
MapView mMapView = null;
Button b1;
MapOptions options = new MapOptions(MapOptions.MapType.TOPO, 49.591241, 17.255503, 16);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.map);
//mMapView.centerAndZoom(49.591241, 17.255503, 8);
btnClick();
mMapView.setMapOptions(options);
mMapView.setAllowRotationByPinch(true);
mMapView.setRotationAngle(25);
mMapView.enableWrapAround(true);
}
public void btnClick() {
b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//mMapView.centerAndZoom(49.591241, 17.255503, 10);
mMapView.setMapOptions(options);
}
});
}
#Override
protected void onPause() {
super.onPause();
// Call MapView.pause to suspend map rendering while the activity is paused, which can save battery usage.
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
// Call MapView.unpause to resume map rendering when the activity returns to the foreground.
mMapView.unpause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You could remove the MapView declaration from your XML and create it inside the activity. Then just add the MapView to your layout.
XML (details omitted)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/mapLayout"></LinearLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
MapView mapView = MapView(MainActivity.this, mapOpts);
// other logic/initializations
ViewGroup mapLayout = findViewById(R.id.mapLayout);
mapLayout.addView(mapView); // might have to specify index param if you need buttons
This is my solution by previous answer. Thanks zec!
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.esri.android.map.MapOptions;
import com.esri.android.map.MapView;
public class MainActivity extends Activity {
MapView mMapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapOptions options = new MapOptions(MapOptions.MapType.TOPO, 49.591241, 17.255503, 16);
mMapView = new MapView(MainActivity.this, options);
setContentView(mMapView);
}
#Override
protected void onPause() {
super.onPause();
// Call MapView.pause to suspend map rendering while the activity is paused, which can save battery usage.
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
// Call MapView.unpause to resume map rendering when the activity returns to the foreground.
mMapView.unpause();
}
}

InAppBilling crashes on startup

I'm trying to make an app that I can get a simple implementation of in app purchases. I've been falling this guide http://www.techotopia.com/index.php/Integrating_Google_Play_In-app_Billing_into_an_Android_Application_%E2%80%93_A_Tutorial
but it's fraught with probably outdated information and neglects to include all the names of the packages you need to download from the SDK manager.
The main errors I had from this program were seemingly reference errors like I had not imported a certain library or compatibility files were missing. I managed to resolve all of them in eclipse and there are no errors when I run the code but trying it on a device or in the VM, the app crashes when I try to run it there.
I excluded the key you need for the google play connection for obvious reasons.
package com.a.inappbilling;
import com.a.inappbilling.util.IabHelper;
import com.a.inappbilling.util.IabResult;
import com.a.inappbilling.util.Inventory;
import com.a.inappbilling.util.Purchase;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.content.Intent;
import android.util.Log;
public class InAppBillingActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_app_billing);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.in_app_billing, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_in_app_billing,
container, false);
return rootView;
}
}
private Button clickButton;
private Button buyButton;
#Override
protected void onStart() {
super.onStart();
buyButton = (Button)findViewById(R.id.buyButton);
clickButton = (Button)findViewById(R.id.clickButton);
clickButton.setEnabled(false);
String base64EncodedPublicKey =
"key here";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " +
result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void buttonClicked (View view)
{
clickButton.setEnabled(false);
buyButton.setEnabled(true);
}
private static final String TAG = "com.a.inappbilling";
IabHelper mHelper;
}
Add permission to your Manifest file
<uses-permission android:name="com.android.vending.BILLING" />
also add to your Manifest file under the Application node
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Also just verify you have added InAppBillingActivity.java to your Manifest file.

App Force Close

My app force closes on the onClick (goForIt). I'm just trying to set a content View but it forces closes eatch time I press my button. And also is it possible to make an app with only 1 activity ?
Could somebody tell me why please:
package com.XanderApps.techquizz;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goForIt(View view) {
setContentView(R.layout.question_one);
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
setContentView(R.layout.choice_done);
break;
case R.id.checkbox_cheese:
if (checked)
System.exit(0);
break;
}
}
#Override
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);
return true;
}
}
Without looking at your Logcat, my guess is that you are getting a 'NullPointerException' when you try to access your button.
Make sure you are 'instantiating' your button object using the findViewById syntax, before you are trying to use onClick().
As you haven't instantiated your goForIt inside onCreateView() of Activity. Thus it throws NPE(Null Pointer Exception).
Get your id of goForIt from your XML layout file.
Add
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
goForit=(Button)findViewById(R.id.goForItId);
}
And then add onClickListener on goForIt.

Categories