Using a ArrayList to order elements on Android App - Java for Android App Development

Hi I'm newbie on xdadevelopers and in android applications development, I'm trying to do an android app wich creates 3 objects called "Contacte". This 3 objects must be showed on the ActivityMain by preference order and for this I'm using an ArrayList to save them. When I create the ArrayList on the MainActivity I can show them correctly (in the order I want), but then for every element showed I show too one button to edit object propertied(Contacte). Using an intent I pass the object to another activity called EditaContacte from there I can change object properties, but when I save the changes and send the object back to the MainActivity the changes doesn't applied. I know there's not a good explanation...
Resume: I heave to do an app which show 3 objects with one buton each to edit object properties; the objects must be ordered by prioriti but I can't do it for change the properites on the second ativity and save the changes.
There's the "Contact" class:
Code:
public class Contacte implements Serializable {
/**
* Per poder passar l'objecte entre activities primer l'hem de serialitzar
*/
private String nom;
private String cognoms;
private String telefon;
private int horari; // 0 = horari sense definir; 1 = 24h; 2 = Mati; 3 = Tarda
private boolean principal;
/**
* Constructor sense parametres que permet crear un objecte contacte amb els
* valors predefinits
*/
public Contacte(){
nom = "Nom";
cognoms = "Cognom";
telefon = "Telefon";
horari = 0;
principal = false;
}
// Setters and Getters
The MainActivity
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array que contindrà 3 objectes de tipus contacte, el primer serà el contacte prioritari
ArrayList<Contacte> contactes = new ArrayList<Contacte>();
// Creem els objectes que representen els contactes
Contacte c1 = new Contacte();
Contacte c2 = new Contacte();
Contacte c3 = new Contacte();
// Assignem valors al primer contacte
c1.setNom("John");
c1.setCognoms("Doe");
c1.setTelefon("632145897");
c1.setHorari(2);
// Afegim els Contactes a l'ArrayList contactes
contactes.add(c1);
contactes.add(c2);
contactes.add(c3);
// Obtenim les referencies als elements on es mostren les dades del primer contacte
TextView nom1 = (TextView)findViewById(R.id.txtNom1);
TextView cognom1 = (TextView)findViewById(R.id.txtCognom1);
TextView telefon1 = (TextView)findViewById(R.id.txtTelefon1);
RadioButton horari24h1 = (RadioButton)findViewById(R.id.rdioButtonHorari24h1);
RadioButton mati1 = (RadioButton)findViewById(R.id.rdioButtonHorariMati1);
RadioButton tarda1 = (RadioButton)findViewById(R.id.rdioButtonHorariTarda1);
// Mostrem el nom, cognoms i telefon del primer contacte per pantalla
nom1.setText(contactes.get(0).getNom());
cognom1.setText(contactes.get(0).getCognoms());
telefon1.setText(contactes.get(0).getTelefon());
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.edita1:
// 1. create an intent pass class name or intnet action name
Intent i = new Intent();
i.setClass(MainActivity.this, EditaContacte.class);
// 2. create person object
Contacte c = new Contacte();
c = contactes.get(0);
// 3. put person in intent data
i.putExtra("contactec", contactes);
i.putExtra("index", 0);
// 4. start the activity
startActivity(i);
break;
// case R.id.edita2:
//DO something
// break;
// case R.id.edita3:
//DO something
// break;
}
}
};
And there's the EditaContacte
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edita_contacte);
// 1. get passed intent
Intent intent = getIntent();
Contacte c = new Contacte();
// 2. get person object from intent
c = (Contacte) intent.getSerializableExtra("contacte");
// 3. get reference to person textView
EditText editaNom = (EditText) findViewById(R.id.editaNom);
EditText editaCognom = (EditText) findViewById(R.id.editaCognom);
EditText editaTelefon = (EditText) findViewById(R.id.editaTelefon);
RadioButton editaTotDia = (RadioButton) findViewById(R.id.TotDia);
RadioButton editaMati = (RadioButton) findViewById(R.id.mati);
RadioButton editaTarda = (RadioButton) findViewById(R.id.tarda);
Button edita = (Button)findViewById(R.id.edita);
edita.setOnClickListener(onClickListener);
// 4. display name & age on textView
editaNom.setText(c.getNom());
editaCognom.setText(c.getCognoms());
editaTelefon.setText(c.getTelefon());
// Deixem marcat el RadioButton segons l'horari del contacte
switch(c.getHorari()){
case 0:
editaTotDia.setChecked(false);
editaMati.setChecked(false);
editaTarda.setChecked(false);
break;
case 1:
editaTotDia.setChecked(true);
editaMati.setChecked(false);
editaTarda.setChecked(false);
break;
case 2:
editaTotDia.setChecked(false);
editaMati.setChecked(true);
editaTarda.setChecked(false);
break;
case 3:
editaTotDia.setChecked(false);
editaMati.setChecked(false);
editaTarda.setChecked(true);
break;
}
}

cobogarciaj said:
Hi I'm newbie on xdadevelopers and in android applications development, I'm trying to do an android app wich creates 3 objects called "Contacte". This 3 objects must be showed on the ActivityMain by preference order and for this I'm using an ArrayList to save them. When I create the ArrayList on the MainActivity I can show them correctly (in the order I want), but then for every element showed I show too one button to edit object propertied(Contacte). Using an intent I pass the object to another activity called EditaContacte from there I can change object properties, but when I save the changes and send the object back to the MainActivity the changes doesn't applied. I know there's not a good explanation...
Resume: I heave to do an app which show 3 objects with one buton each to edit object properties; the objects must be ordered by prioriti but I can't do it for change the properites on the second ativity and save the changes.
There's the "Contact" class:
Code:
public class Contacte implements Serializable {
/**
* Per poder passar l'objecte entre activities primer l'hem de serialitzar
*/
private String nom;
private String cognoms;
private String telefon;
private int horari; // 0 = horari sense definir; 1 = 24h; 2 = Mati; 3 = Tarda
private boolean principal;
/**
* Constructor sense parametres que permet crear un objecte contacte amb els
* valors predefinits
*/
public Contacte(){
nom = "Nom";
cognoms = "Cognom";
telefon = "Telefon";
horari = 0;
principal = false;
}
// Setters and Getters
The MainActivity
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array que contindrà 3 objectes de tipus contacte, el primer serà el contacte prioritari
ArrayList<Contacte> contactes = new ArrayList<Contacte>();
// Creem els objectes que representen els contactes
Contacte c1 = new Contacte();
Contacte c2 = new Contacte();
Contacte c3 = new Contacte();
// Assignem valors al primer contacte
c1.setNom("John");
c1.setCognoms("Doe");
c1.setTelefon("632145897");
c1.setHorari(2);
// Afegim els Contactes a l'ArrayList contactes
contactes.add(c1);
contactes.add(c2);
contactes.add(c3);
// Obtenim les referencies als elements on es mostren les dades del primer contacte
TextView nom1 = (TextView)findViewById(R.id.txtNom1);
TextView cognom1 = (TextView)findViewById(R.id.txtCognom1);
TextView telefon1 = (TextView)findViewById(R.id.txtTelefon1);
RadioButton horari24h1 = (RadioButton)findViewById(R.id.rdioButtonHorari24h1);
RadioButton mati1 = (RadioButton)findViewById(R.id.rdioButtonHorariMati1);
RadioButton tarda1 = (RadioButton)findViewById(R.id.rdioButtonHorariTarda1);
// Mostrem el nom, cognoms i telefon del primer contacte per pantalla
nom1.setText(contactes.get(0).getNom());
cognom1.setText(contactes.get(0).getCognoms());
telefon1.setText(contactes.get(0).getTelefon());
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.edita1:
// 1. create an intent pass class name or intnet action name
Intent i = new Intent();
i.setClass(MainActivity.this, EditaContacte.class);
// 2. create person object
Contacte c = new Contacte();
c = contactes.get(0);
// 3. put person in intent data
[B]i.putExtra("contactec", contactes);[/B]
i.putExtra("index", 0);
// 4. start the activity
startActivity(i);
break;
// case R.id.edita2:
//DO something
// break;
// case R.id.edita3:
//DO something
// break;
}
}
};
And there's the EditaContacte
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edita_contacte);
// 1. get passed intent
Intent intent = getIntent();
Contacte c = new Contacte();
// 2. get person object from intent
c = (Contacte) intent.getSerializableExtra("contacte");
// 3. get reference to person textView
EditText editaNom = (EditText) findViewById(R.id.editaNom);
EditText editaCognom = (EditText) findViewById(R.id.editaCognom);
EditText editaTelefon = (EditText) findViewById(R.id.editaTelefon);
RadioButton editaTotDia = (RadioButton) findViewById(R.id.TotDia);
RadioButton editaMati = (RadioButton) findViewById(R.id.mati);
RadioButton editaTarda = (RadioButton) findViewById(R.id.tarda);
Button edita = (Button)findViewById(R.id.edita);
edita.setOnClickListener(onClickListener);
// 4. display name & age on textView
editaNom.setText(c.getNom());
editaCognom.setText(c.getCognoms());
editaTelefon.setText(c.getTelefon());
// Deixem marcat el RadioButton segons l'horari del contacte
switch(c.getHorari()){
case 0:
editaTotDia.setChecked(false);
editaMati.setChecked(false);
editaTarda.setChecked(false);
break;
case 1:
editaTotDia.setChecked(true);
editaMati.setChecked(false);
editaTarda.setChecked(false);
break;
case 2:
editaTotDia.setChecked(false);
editaMati.setChecked(true);
editaTarda.setChecked(false);
break;
case 3:
editaTotDia.setChecked(false);
editaMati.setChecked(false);
editaTarda.setChecked(true);
break;
}
}
Click to expand...
Click to collapse
Ok so the first thing that I see in your code is that while you declare an OnClickListener, you never call setOnClickListener() for it on any of your buttons, though it might be in some other methods (onResum()?) that you didn't show. Then there is a very nasty spelling mistake in your OnClickListener's method where you call i.putExtra("contactec", contactes); instead of i.putExtra("contacte", contactes);. A good pratcice to avoid these kind of mistakes is to declare a public static final String KEY_CONTACTE = "contacte"; which you'll want to use in both activities (with MainActivity.KEY_CONTACTE in the second one) . Other than that, you might also want to consider using the startActivityForResult(), setResult() and onActivityResult() methods to pass data back from the second edit activity.

Related

FC when using interface to launch new fragment form listView

I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
@override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
@override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
@override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
@override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.

SharedPreferences Context Issue

I have created a questionnaire in the beginning of the app in order to base a user model off the answers chosen. The values of the chosen options are stored as Shared Preferences as shown below. With the data retrieved I am then trying to tag a Google map with certain tags based on the answers chosen. The issue I am encountering is that of reading the stored Shared Preference values across the different activities, from the Question2 Activity, to that of the Map Activity (code below). Any pointers on how to solve the *context* conflict would be greatly appreciated.
Question2 Activity:
Code:
public class Question2 extends Activity{
RadioButton q2a1,q2a2,q2a3;
Button btn2;
public static final String MY_PREF = "MyPreferences";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.activity_question2, null);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
q2a1 = (RadioButton) findViewById(R.id.q2a1);
q2a2 = (RadioButton) findViewById(R.id.q2a2);
q2a3 = (RadioButton) findViewById(R.id.q2a3);
btn2 = (Button) findViewById(R.id.q2_button);
btn2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
SharedPreferences prefernces = getSharedPreferences(MY_PREF, 0);
SharedPreferences.Editor editor = prefernces.edit();
if (q2a1.isChecked()){
editor.putInt("answer_value2", 1);
editor.commit();
}
if (q2a2.isChecked()){
editor.putInt("answer_value2", 2);
editor.commit();
}
if (q2a3.isChecked()){
editor.putInt("answer_value2", 3);
editor.commit();
}else {
editor.putInt("answer_value2", 0);
editor.commit();
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), Question3.class);
startActivity(intent);
}
});
}
}
Map Activity:
Code:
public class MapActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapLayout)).getMap();
map.setMyLocationEnabled(true);
SharedPreferences preferences = getSharedPreferences(Question2.MY_PREF,MODE_PRIVATE);
int q1answer = preferences.getInt("answer_value", 0);
int q2answer = preferences.getInt("answer_value2", 0);
int q3answer = preferences.getInt("answer_value3", 0);
if(q1answer == 1){
//method
}
if(q1answer == 2){
//method
}
if(q1answer == 3){
//method
}
if(q2answer == 1){
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(HEALTHSHOP).title("Health Shop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grasy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MINT).title("Mint").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 2){
Toast.makeText(getApplicationContext(), "Your result is " + q2answer, Toast.LENGTH_SHORT).show();
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(JUBILEE).title("Jubilee").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grassy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 3){
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(PASTIZZERIA).title("Pastizerria").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(BURGERKING).title("Burger King").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
if(q3answer == 1){
//implementation
}if(q3answer == 2){
//implementation
}if(q3answer == 3){
//implementation
}if(q3answer == 4){
//implementation
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
Use this
create this class in your package
Code:
public class SharedPrefence{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferences";
// Answers (make variable public to access from outside)
public static final String KEY_ANSWER_TWO = "answer_value2";
//similarly other answers tag can be added(this is the key of preference)
// Constructor
public SharedPrefence(Context context) {
_context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create Answer.
* */
public void createAnswer(int ans) {
// Storing name in pref
editor.putInt(KEY_ANSWER_TWO, ans);
// commit changes
editor.commit();
}
public int getAnswer(String tag,int default) {
return pref.getString(tag, default);
}
}
now create an activity and initialise this class in the starting with the activity context.
next call the create answer method of this class and you are done.
also no need to create sharedprefence in each activity.
and it's even better if you create only one activity and use ViewPager for all questions.you can google for it.
And if this was useful click on thanks below.
:victory::victory::victory::victory:

[Q] How to stop the ball at touch release

hi, its killing me i can't fix it i made this thing because i was learning Canvas and drawing on android !
i included moving animations (smooth) but i removed it
Code:
package com.example.graphics;
import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
import java.util.Formatter;
import android.graphics.Typeface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class BouncingBallView extends View {
private int xMin = 0; // This view's bounds
private int xMax;
private int yMin = 0;
private int yMax;
private float ballRadius = 80; // Ball's radius
private float ballX = ballRadius + 20; // Ball's center (x,y)
private float ballY = ballRadius + 40;
private float ballSpeedX = 11; // Ball's speed (x,y)
private float ballSpeedY = 7;
//private RectF ballBounds; // Needed for Canvas.drawOval
private Paint paint; // The paint (e.g. style, color) used for drawing
// Status message to show Ball's (x,y) position and speed.
private StringBuilder statusMsg = new StringBuilder();
private Formatter formatter = new Formatter(statusMsg); // Formatting the statusMsg
private float previousX;
private float previousY;
private float currentX;
private float currentY;
private float scale;
private int ifdrawcount = 0;
// Constructor
public BouncingBallView(Context context) {
super(context);
//ballBounds = new RectF();
paint = new Paint();
paint.setTypeface(Typeface.MONOSPACE);
paint.setTextSize(25);
setFocusableInTouchMode(true);
//setFocusable(true);
requestFocus();
}
/*public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase rightward speed
ballSpeedX++;
break;
case KeyEvent.KEYCODE_DPAD_LEFT: // Increase leftward speed
ballSpeedX--;
break;
case KeyEvent.KEYCODE_DPAD_UP: // Increase upward speed
ballSpeedY--;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: // Increase downward speed
ballSpeedY++;
break;
case KeyEvent.KEYCODE_DPAD_CENTER: // Stop
ballSpeedX = 0;
ballSpeedY = 0;
break;
case KeyEvent.KEYCODE_A: // Zoom in
// Max radius is about 90% of half of the smaller dimension
float maxRadius = (xMax > yMax) ? yMax / 2 * 0.9f : xMax / 2 * 0.9f;
if (ballRadius < maxRadius) {
ballRadius *= 1.05; // Increase radius by 5%
}
break;
case KeyEvent.KEYCODE_Z: // Zoom out
if (ballRadius > 20) { // Minimum radius
ballRadius *= 0.95; // Decrease radius by 5%
}
break;
}
return true; // Event handled
}*/
// Called back to draw the view. Also called by invalidate().
@Override
protected void onDraw(Canvas canvas) {
// Draw the ball
//ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
//paint.setColor(Color.GRAY);
//canvas.drawOval(ballBounds, paint);
//canvas.drawCircle(70, yMax -70, 60, paint);
//canvas.drawCircle(xMax -70, yMax -60, 60, paint);
paint.setColor(Color.GREEN);
canvas.drawCircle(ballX, ballY, ballRadius, paint);
// Draw the status message
paint.setColor(Color.WHITE);
paint.setStrokeWidth(2);
canvas.drawText(statusMsg.toString(), 10, 30, paint);
if(ifdrawcount > 0){
canvas.drawLine(previousX, previousY, currentX, currentY, paint);
paint.setStrokeWidth(10);
paint.setColor(Color.BLACK);
canvas.drawPoint(previousX,previousY,paint);
ifdrawcount--;
}
// Update the position of the ball, including collision detection and reaction.
update();
// Delay
try {
Thread.sleep(16);
} catch (InterruptedException e) { }
invalidate(); // Force a re-draw
}
// Touch-input handler
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
ifdrawcount = 10;
//float deltaX, deltaY;
scale = 20.0f / ((xMax > yMax) ? yMax : xMax);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
previousX = currentX;
previousY = currentY;
case MotionEvent.ACTION_MOVE:
ballSpeedY = (currentY - previousY) * scale;
ballSpeedX = (currentX - previousX) * scale;
case MotionEvent.ACTION_UP:
ballSpeedX = 0;
ballSpeedY = 0;
}
return true; // Event handled
}
// Detect collision and update the position of the ball.
private void update() {
// Get new (x,y) position
ballX += ballSpeedX;
ballY += ballSpeedY;
/*if(ifdrawcount == 0)
ballSpeedX = 0; ballSpeedY = 0;*/
// Detect collision and react
if (ballX + ballRadius > xMax) {
ballSpeedX = -ballSpeedX;
ballX = xMax-ballRadius;
} else if (ballX - ballRadius < xMin) {
ballSpeedX = -ballSpeedX;
ballX = xMin+ballRadius;
}
if (ballY + ballRadius > yMax) {
ballSpeedY = -ballSpeedY;
ballY = yMax - ballRadius;
} else if (ballY - ballRadius < yMin) {
ballSpeedY = -ballSpeedY;
ballY = yMin + ballRadius;
}
// Build status message
statusMsg.delete(0, statusMsg.length()); // Empty buffer
formatter.format("%3.0f %3.0f || %3.0f %3.0f", ballSpeedX, ballSpeedY,ballX,ballY);
}
// Called back when the view is first created or its size changes.
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
xMax = w-1;
yMax = h-1;
}
}
the problem is my ball doesn't move at all, but i see the line, once i remove the line:
Code:
case MotionEvent.ACTION_UP:
ballSpeedX = 0;
ballSpeedY = 0;
it works, but you know, after release it continues with same speed :! its like the ACTION_UP is always the case, !!! any idea why it doesn't work, how to stop the ball once the user releases the screen?
also sorry if this is not the right place. i searched the forums, i got confused i didn't find anyplace to ask this question so i tough this is the best place!

Fontpath is not passed through intent

In my app there is an activity say Activity A which has an image view with some text views. code is listed below
Code:
public class EidCardFinal extends Activity {
private ImageView imageView;
private TextView receiver, sender, messagebody;
private Intent intent;
private Bundle bundle;
private static final int FONT_SELECT = 1;
// public String filepath = "MyFileStorage";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eid_card_final);
intent = getIntent();
String message1 = intent.getStringExtra("RECEIVER");
String message2 = intent.getStringExtra("SENDER");
String message3 = intent.getStringExtra("MESSAGEBODY");
String check_click = intent.getStringExtra("bttnclick");
imageView = (ImageView) findViewById(R.id.imageView1);
receiver = (TextView) findViewById(R.id.textView1);
sender = (TextView) findViewById(R.id.textView2);
messagebody = (TextView) findViewById(R.id.textView3);
receiver.setText(message1);
sender.setText(message2);
messagebody.setText(message3);
// Selected image id
if ("BUTTONCLICK".equals(check_click)) {
String path = intent.getStringExtra("image");
Uri myUri = Uri.parse(path);
imageView.setImageURI(myUri);
} else {
int position = intent.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
// ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(imageAdapter.thumbIds[position]);
case R.id.change_fonts:
Intent fontintent = new Intent();
bundle = getIntent().getExtras();
fontintent.putExtras(bundle);
fontintent.setClass(getApplicationContext(), FontSelection.class);
this.startActivityForResult(fontintent, FONT_SELECT);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FONT_SELECT) {
Bundle pathadd= data.getExtras();
String fontadd = pathadd.getString("FONTPATH");
//intent = getIntent();
/*String message1 = data.getStringExtra("RECEIVER");
String message2 = data.getStringExtra("SENDER");
String message3 = data.getStringExtra("MESSAGEBODY");
//String check_click = intent.getStringExtra("bttnclick");
imageView = (ImageView) findViewById(R.id.imageView1);
receiver = (TextView) findViewById(R.id.textView1);
sender = (TextView) findViewById(R.id.textView2);
messagebody = (TextView) findViewById(R.id.textView3);
receiver.setText(message1);
sender.setText(message2);
messagebody.setText(message3);*/
//bundle = getIntent().getExtras();
Typeface tyfa = Typeface.createFromAsset(getAssets(), fontadd);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
From menu, user is taken to another activity say Activity B from where a custom font can be selected for Activity A. Code is listed below
Code:
public class FontSelection extends Activity {
String[] fontpath = { "fonts/android_7.ttf", "fonts/doridrobot.ttf",
"fonts/droidsansmono.ttf", "fonts/droidserif-bold.ttf",
"fonts/green-avocado.ttf", "fonts/lokicola.ttf",
"fonts/outwrite.ttf", "fonts/painting-the-light.ttf",
"fonts/roboto-black.ttf", "fonts/roboto-boldcondensed.ttf",
"fonts/roboto-medium.ttf", "fonts/roboto-regular.ttf" };
String[] fontname = { "android_7", "doridrobot", "droidsansmono",
"droidserif-bold", "green-avocado", "lokicola", "outwrite",
"painting-the-light", "roboto-black", "roboto-boldcondensed",
"roboto-medium", "roboto-regular" };
private Intent fontpathintent = new Intent();
private Bundle bundle1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_font_selection);
RadioButton radio1 = (RadioButton) findViewById(R.id.radioButton1);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontpath[0]);
radio1.setTypeface(tf1);
radio1.setText(fontname[0]);
RadioButton radio2 = (RadioButton) findViewById(R.id.radioButton2);
Typeface tf2 = Typeface.createFromAsset(getAssets(), fontpath[1]);
radio2.setTypeface(tf2);
radio2.setText(fontname[1]);
RadioButton radio3 = (RadioButton) findViewById(R.id.radioButton3);
Typeface tf3 = Typeface.createFromAsset(getAssets(), fontpath[2]);
radio3.setTypeface(tf3);
radio3.setText(fontname[2]);
RadioButton radio4 = (RadioButton) findViewById(R.id.radioButton4);
Typeface tf4 = Typeface.createFromAsset(getAssets(), fontpath[3]);
radio4.setTypeface(tf4);
radio4.setText(fontname[3]);
RadioButton radio5 = (RadioButton) findViewById(R.id.radioButton5);
Typeface tf5 = Typeface.createFromAsset(getAssets(), fontpath[4]);
radio5.setTypeface(tf5);
radio5.setText(fontname[4]);
RadioButton radio6 = (RadioButton) findViewById(R.id.radioButton6);
Typeface tf6 = Typeface.createFromAsset(getAssets(), fontpath[5]);
radio6.setTypeface(tf6);
radio6.setText(fontname[5]);
RadioButton radio7 = (RadioButton) findViewById(R.id.radioButton7);
Typeface tf7 = Typeface.createFromAsset(getAssets(), fontpath[6]);
radio7.setTypeface(tf7);
radio7.setText(fontname[6]);
RadioButton radio8 = (RadioButton) findViewById(R.id.radioButton8);
Typeface tf8 = Typeface.createFromAsset(getAssets(), fontpath[7]);
radio8.setTypeface(tf8);
radio8.setText(fontname[7]);
RadioButton radio9 = (RadioButton) findViewById(R.id.radioButton9);
Typeface tf9 = Typeface.createFromAsset(getAssets(), fontpath[8]);
radio9.setTypeface(tf9);
radio9.setText(fontname[8]);
RadioButton radio10 = (RadioButton) findViewById(R.id.radioButton10);
Typeface tf10 = Typeface.createFromAsset(getAssets(), fontpath[9]);
radio10.setTypeface(tf10);
radio10.setText(fontname[9]);
RadioButton radio11 = (RadioButton) findViewById(R.id.radioButton11);
Typeface tf11 = Typeface.createFromAsset(getAssets(), fontpath[10]);
radio11.setTypeface(tf11);
radio11.setText(fontname[10]);
RadioButton radio12 = (RadioButton) findViewById(R.id.radioButton12);
Typeface tf12 = Typeface.createFromAsset(getAssets(), fontpath[11]);
radio12.setTypeface(tf12);
radio12.setText(fontname[11]);
}
public void onRadioButtonClick(View view) {
bundle1 = getIntent().getExtras();
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.radioButton1:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[0]);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
fontpathintent.putExtras(bundle1);
startActivity(fontpathintent);
break;
case R.id.radioButton2:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[1]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton3:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[2]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton4:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[3]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton5:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[4]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton6:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[5]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton7:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[6]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton8:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[7]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton9:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[8]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton10:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[9]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
break;
case R.id.radioButton11:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[10]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton12:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[11]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
}
}
my problem is, upon selection of font, there is no change in activity A, i mean font in activity A remains unchanged.
ariez4u said:
In my app there is an activity say Activity A which has an image view with some text views. code is listed below
Code:
public class EidCardFinal extends Activity {
private ImageView imageView;
private TextView receiver, sender, messagebody;
private Intent intent;
private Bundle bundle;
private static final int FONT_SELECT = 1;
// public String filepath = "MyFileStorage";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eid_card_final);
intent = getIntent();
String message1 = intent.getStringExtra("RECEIVER");
String message2 = intent.getStringExtra("SENDER");
String message3 = intent.getStringExtra("MESSAGEBODY");
String check_click = intent.getStringExtra("bttnclick");
imageView = (ImageView) findViewById(R.id.imageView1);
receiver = (TextView) findViewById(R.id.textView1);
sender = (TextView) findViewById(R.id.textView2);
messagebody = (TextView) findViewById(R.id.textView3);
receiver.setText(message1);
sender.setText(message2);
messagebody.setText(message3);
// Selected image id
if ("BUTTONCLICK".equals(check_click)) {
String path = intent.getStringExtra("image");
Uri myUri = Uri.parse(path);
imageView.setImageURI(myUri);
} else {
int position = intent.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
// ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(imageAdapter.thumbIds[position]);
case R.id.change_fonts:
Intent fontintent = new Intent();
bundle = getIntent().getExtras();
fontintent.putExtras(bundle);
fontintent.setClass(getApplicationContext(), FontSelection.class);
this.startActivityForResult(fontintent, FONT_SELECT);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FONT_SELECT) {
Bundle pathadd= data.getExtras();
String fontadd = pathadd.getString("FONTPATH");
//intent = getIntent();
/*String message1 = data.getStringExtra("RECEIVER");
String message2 = data.getStringExtra("SENDER");
String message3 = data.getStringExtra("MESSAGEBODY");
//String check_click = intent.getStringExtra("bttnclick");
imageView = (ImageView) findViewById(R.id.imageView1);
receiver = (TextView) findViewById(R.id.textView1);
sender = (TextView) findViewById(R.id.textView2);
messagebody = (TextView) findViewById(R.id.textView3);
receiver.setText(message1);
sender.setText(message2);
messagebody.setText(message3);*/
//bundle = getIntent().getExtras();
Typeface tyfa = Typeface.createFromAsset(getAssets(), fontadd);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
From menu, user is taken to another activity say Activity B from where a custom font can be selected for Activity A. Code is listed below
Code:
public class FontSelection extends Activity {
String[] fontpath = { "fonts/android_7.ttf", "fonts/doridrobot.ttf",
"fonts/droidsansmono.ttf", "fonts/droidserif-bold.ttf",
"fonts/green-avocado.ttf", "fonts/lokicola.ttf",
"fonts/outwrite.ttf", "fonts/painting-the-light.ttf",
"fonts/roboto-black.ttf", "fonts/roboto-boldcondensed.ttf",
"fonts/roboto-medium.ttf", "fonts/roboto-regular.ttf" };
String[] fontname = { "android_7", "doridrobot", "droidsansmono",
"droidserif-bold", "green-avocado", "lokicola", "outwrite",
"painting-the-light", "roboto-black", "roboto-boldcondensed",
"roboto-medium", "roboto-regular" };
private Intent fontpathintent = new Intent();
private Bundle bundle1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_font_selection);
RadioButton radio1 = (RadioButton) findViewById(R.id.radioButton1);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontpath[0]);
radio1.setTypeface(tf1);
radio1.setText(fontname[0]);
RadioButton radio2 = (RadioButton) findViewById(R.id.radioButton2);
Typeface tf2 = Typeface.createFromAsset(getAssets(), fontpath[1]);
radio2.setTypeface(tf2);
radio2.setText(fontname[1]);
RadioButton radio3 = (RadioButton) findViewById(R.id.radioButton3);
Typeface tf3 = Typeface.createFromAsset(getAssets(), fontpath[2]);
radio3.setTypeface(tf3);
radio3.setText(fontname[2]);
RadioButton radio4 = (RadioButton) findViewById(R.id.radioButton4);
Typeface tf4 = Typeface.createFromAsset(getAssets(), fontpath[3]);
radio4.setTypeface(tf4);
radio4.setText(fontname[3]);
RadioButton radio5 = (RadioButton) findViewById(R.id.radioButton5);
Typeface tf5 = Typeface.createFromAsset(getAssets(), fontpath[4]);
radio5.setTypeface(tf5);
radio5.setText(fontname[4]);
RadioButton radio6 = (RadioButton) findViewById(R.id.radioButton6);
Typeface tf6 = Typeface.createFromAsset(getAssets(), fontpath[5]);
radio6.setTypeface(tf6);
radio6.setText(fontname[5]);
RadioButton radio7 = (RadioButton) findViewById(R.id.radioButton7);
Typeface tf7 = Typeface.createFromAsset(getAssets(), fontpath[6]);
radio7.setTypeface(tf7);
radio7.setText(fontname[6]);
RadioButton radio8 = (RadioButton) findViewById(R.id.radioButton8);
Typeface tf8 = Typeface.createFromAsset(getAssets(), fontpath[7]);
radio8.setTypeface(tf8);
radio8.setText(fontname[7]);
RadioButton radio9 = (RadioButton) findViewById(R.id.radioButton9);
Typeface tf9 = Typeface.createFromAsset(getAssets(), fontpath[8]);
radio9.setTypeface(tf9);
radio9.setText(fontname[8]);
RadioButton radio10 = (RadioButton) findViewById(R.id.radioButton10);
Typeface tf10 = Typeface.createFromAsset(getAssets(), fontpath[9]);
radio10.setTypeface(tf10);
radio10.setText(fontname[9]);
RadioButton radio11 = (RadioButton) findViewById(R.id.radioButton11);
Typeface tf11 = Typeface.createFromAsset(getAssets(), fontpath[10]);
radio11.setTypeface(tf11);
radio11.setText(fontname[10]);
RadioButton radio12 = (RadioButton) findViewById(R.id.radioButton12);
Typeface tf12 = Typeface.createFromAsset(getAssets(), fontpath[11]);
radio12.setTypeface(tf12);
radio12.setText(fontname[11]);
}
public void onRadioButtonClick(View view) {
bundle1 = getIntent().getExtras();
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.radioButton1:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[0]);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
fontpathintent.putExtras(bundle1);
startActivity(fontpathintent);
break;
case R.id.radioButton2:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[1]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton3:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[2]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton4:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[3]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton5:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[4]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton6:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[5]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton7:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[6]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton8:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[7]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton9:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[8]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton10:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[9]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
break;
case R.id.radioButton11:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[10]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
case R.id.radioButton12:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[11]);
fontpathintent.putExtras(bundle1);
fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
startActivity(fontpathintent);
break;
}
}
my problem is, upon selection of font, there is no change in activity A, i mean font in activity A remains unchanged.
Click to expand...
Click to collapse
Your problem is that you restart your first acitivity in your font selection activity. Instead you'd want to call setResult() in there and then finish that activity. Only that way onActivityResult() is called in your first activity!
SimplicityApks said:
Your problem is that you restart your first acitivity in your font selection activity. Instead you'd want to call setResult() in there and then finish that activity. Only that way onActivityResult() is called in your first activity!
Click to expand...
Click to collapse
Well, thanks for the reply. I have made changes as per your instructions but unfortunately result is same. Changes in the code
Code:
case R.id.radioButton1:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[0]);
// fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
// fontpathintent.putExtras(bundle1);
// startActivity(fontpathintent);
setResult(1, fontpathintent);
finish();
break;
case R.id.radioButton2:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[1]);
// fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
// fontpathintent.putExtras(bundle1);
// startActivity(fontpathintent);
setResult(1, fontpathintent);
finish();
break;
Code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// Bundle pathadd= data.getExtras();
String customfont = data.getStringExtra("FONTPATH");
// String fontadd = pathadd.getString("FONTPATH");
// intent = getIntent();
/*
* String message1 = data.getStringExtra("RECEIVER"); String
* message2 = data.getStringExtra("SENDER"); String message3 =
* data.getStringExtra("MESSAGEBODY"); //String check_click =
* intent.getStringExtra("bttnclick"); imageView = (ImageView)
* findViewById(R.id.imageView1); receiver = (TextView)
* findViewById(R.id.textView1); sender = (TextView)
* findViewById(R.id.textView2); messagebody = (TextView)
* findViewById(R.id.textView3); receiver.setText(message1);
* sender.setText(message2); messagebody.setText(message3);
*/
// bundle = getIntent().getExtras();
Typeface tyfa = Typeface.createFromAsset(getAssets(),
customfont);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
}
}
}
ariez4u said:
Well, thanks for the reply. I have made changes as per your instructions but unfortunately result is same. Changes in the code
Code:
case R.id.radioButton1:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[0]);
// fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
// fontpathintent.putExtras(bundle1);
// startActivity(fontpathintent);
setResult(1, fontpathintent);
finish();
break;
case R.id.radioButton2:
if (checked)
fontpathintent.putExtra("FONTPATH", fontpath[1]);
// fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
// fontpathintent.putExtras(bundle1);
// startActivity(fontpathintent);
setResult(1, fontpathintent);
finish();
break;
Code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// Bundle pathadd= data.getExtras();
String customfont = data.getStringExtra("FONTPATH");
// String fontadd = pathadd.getString("FONTPATH");
// intent = getIntent();
/*
* String message1 = data.getStringExtra("RECEIVER"); String
* message2 = data.getStringExtra("SENDER"); String message3 =
* data.getStringExtra("MESSAGEBODY"); //String check_click =
* intent.getStringExtra("bttnclick"); imageView = (ImageView)
* findViewById(R.id.imageView1); receiver = (TextView)
* findViewById(R.id.textView1); sender = (TextView)
* findViewById(R.id.textView2); messagebody = (TextView)
* findViewById(R.id.textView3); receiver.setText(message1);
* sender.setText(message2); messagebody.setText(message3);
*/
// bundle = getIntent().getExtras();
Typeface tyfa = Typeface.createFromAsset(getAssets(),
customfont);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
}
}
}
Click to expand...
Click to collapse
Mmmh strange... I assume your onActivityResult() gets called? I'm not familiar with the typefaces but maybe you need to invalidate() the view to see the change. Well you might as well check if tyfa is a valid typeface in that method, because to me the code looks functional.
SimplicityApks said:
Your problem is that you restart your first acitivity in your font selection activity. Instead you'd want to call setResult() in there and then finish that activity. Only that way onActivityResult() is called in your first activity!
Click to expand...
Click to collapse
i have acted upon your instructions but unable to find the solution, i think (as you have suggested too) that onActivityResult() is not called, beccause i have tried below but no result as well.
Code:
tyfa = Typeface.createFromAsset(getAssets(),
[B][COLOR="Red"]"fonts/outwrite.ttf"[/COLOR][/B]);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
SimplicityApks said:
Mmmh strange... I assume your onActivityResult() gets called? I'm not familiar with the typefaces but maybe you need to invalidate() the view to see the change. Well you might as well check if tyfa is a valid typeface in that method, because to me the code looks functional.
Click to expand...
Click to collapse
i have acted upon your instructions but unable to find the solution, i think (as you have suggested too) that onActivityResult() is not called, beccause i have tried below but no result as well.
Code:
tyfa = Typeface.createFromAsset(getAssets(),
[B][COLOR="Red"]"fonts/outwrite.ttf"[/COLOR][/B]);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
ariez4u said:
i have acted upon your instructions but unable to find the solution, i think (as you have suggested too) that onActivityResult() is not called, beccause i have tried below but no result as well.
Code:
tyfa = Typeface.createFromAsset(getAssets(),
[B][COLOR="Red"]"fonts/outwrite.ttf"[/COLOR][/B]);
receiver.setTypeface(tyfa);
sender.setTypeface(tyfa);
messagebody.setTypeface(tyfa);
Click to expand...
Click to collapse
I think I found what the problem is here, you call setResult() with your requestCode, but instead it should be called with a resultCode as first parameter, so it should be setResult(RESULT_OK, fontpathintent);! Let me know if that works, see here for a sample.
SimplicityApks said:
I think I found what the problem is here, you call setResult() with your requestCode, but instead it should be called with a resultCode as first parameter, so it should be setResult(RESULT_OK, fontpathintent);! Let me know if that works, see here for a sample.
Click to expand...
Click to collapse
really obliged. thank you very much. my problem is solved

Android Studio Fragments using Java

I'm working in a project that have 3 Fragments (List, Add and Update fragments)
The List Fragment have a RecyclerView and FloatingActionButton to add a new record.
the Add Fragments have the fields (EditText) to Add New Record
and the Update Fragment have the fields (EditText) to change Data and update.
When a new record is added, the data for this record can be viewed in the recycler. And clicking on any item in the recycler gives you the opportunity to delete or show the data of this item in the UpdateFragment.
my problem is that simple project is near to be finished but I have a big problem:
I'm not know how to send the data of clicked item on the RecyclerView to the UpdateData Fragment to show this data on the EditText in UpdateFragment and updat if I desire.
I'm created a Click.Listener on the RecyclerView Adapter when I click a row_layout in RecyclerView:
@override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Model model = arrayList.get(position);
final String id = model.getId();
final String titulo = model.getTitulo();
final String prioridad = model.getPrioridad();
final String descripcion = model.getDescripcion();
final String addTimeStamp = model.getAddTimeStamp();
final String updateTimeStamp = model.getUpdateTimeStamp();
// set views
holder.titulo.setText(titulo);
holder.descripcion.setText(descripcion);
// colorea el ImageView
switch(prioridad){
case "ALTA": holder.itemView.findViewById(R.id.priority_indicator).setBackgroundColor(Color.parseColor("#FF4646")); break; // rojo
case "MEDIA": holder.itemView.findViewById(R.id.priority_indicator).setBackgroundColor(Color.parseColor("#FFC114")); break; // amarillo
case "BAJA": holder.itemView.findViewById(R.id.priority_indicator).setBackgroundColor(Color.parseColor("#00C980")); break; // verde
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
//Toast.makeText(context, "CLICK EN UN ITEM", Toast.LENGTH_SHORT).show()
editDialog(
""+position,
""+id,
""+titulo,
""+prioridad,
""+descripcion,
""+addTimeStamp,
""+updateTimeStamp
);
}
});
//This take me to Update Fragment but I'm not have a way to send the holder data (id, titulo, prioridad, description) to UpdateFragment
holder.row_layout.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_listFragment_to_editRecordFragment);
}
});
}
Can anyone please know how to solve this problem?
Thank in advanced to all for read.

Categories

Resources