I am new at Android coding and this forum and with Google Maps. When I am trying to exprot the project to test it I am getting this error
> "app_name" is not translated in af, am, ar, be, bg, ca, cs, da, de, el, en-rGB, en-rIN, es, es-rUS, et, et-rEE, fa, fi, fr, fr-rCA, hi, hr, hu, hy-rAM, in, it, iw, ja, ka-rGE, km-rKH,
ko, lo-rLA, lt, lv, mn-rMN, ms, ms-rMY, nb, nl, pl, pt, pt-rBR, pt-rPT, ro, ru, sk, sl, sr, sv, sw, th, tl, tr, uk, vi, zh-rCN, zh-rHK, zh-rTW, zu
at values/strings.xml and exept "app_name" for "hello_world" and "menu_settings" too.
The "strings" code is:
> <?xml version="1.0" encoding="utf-8"?> <resources>
>
> <string name="app_name">ThessMuseams</string>
> <string name="hello_world">Hello world!</string>
> <string name="menu_settings">Settings</string>
>
> </resources>
and my Java code is:
package com.vogella.android.locationapi.maps;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class ShowMapActivity extends Activity implements OnMarkerClickListener{
static final LatLng THESSALONIKI = new LatLng(40.63935, 22.94461);
static final LatLng AMT = new LatLng(40.63501, 22.95441);
static final LatLng MOBC = new LatLng(40.62348, 22.95458);
static final LatLng JMT = new LatLng(40.63935, 22.94461);
static final LatLng NOESIS = new LatLng(40.55522, 23.01824);
static final LatLng TCMC = new LatLng(40.63935, 22.94461);
static final LatLng SMOMA = new LatLng(40.65872, 22.93045);
static final LatLng LEMMT = new LatLng(40.63935, 22.94461);
static final LatLng LP = new LatLng(40.62727, 22.94833);
static final LatLng MMA = new LatLng(40.63083, 22.94348);
static final LatLng MMOCA = new LatLng(40.62481, 22.96231);
static final LatLng OMT = new LatLng(40.62631, 22.96262);
static final LatLng BIM = new LatLng(40.63124, 22.93658);
static final LatLng WMOT = new LatLng(40.62441, 22.95992);
static final LatLng RMOT = new LatLng(40.62668, 22.95325);
static final LatLng MORT = new LatLng(40.64547, 22.92515);
static final LatLng TIT = new LatLng(40.62862, 22.96279);
static final LatLng WM = new LatLng(40.64468, 22.90976);
static final LatLng TMP = new LatLng(40.63337, 22.93638);
Marker thessaloniki, atatourk, byzntino, jewish, noesis, cinema, modernArt, laografiko, leykosPyrgos, makedonikouAgona, macModernArt, olympic,
byzantinInstraments, warMuseam, radioMuseam, railsMuseam, telloglio, water, photography;
private GoogleMap map;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setOnMarkerClickListener(this);
thessaloniki = map.addMarker(new MarkerOptions().position(THESSALONIKI).title("Θεσσαλονίκη"));
atatourk = map.addMarker(new MarkerOptions().position(AMT).title("Μουσείο Ατατούρκ Θεσσαλονίκης"));
byzntino = map.addMarker(new MarkerOptions().position(MOBC).title("Μουσείο Βυζαντινού Πολιτισμού Θεσσαλονίκης"));
jewish = map.addMarker(new MarkerOptions().position(JMT).title("Κέντρο Ιστορικής Διαδρομής Εβραϊσμού Θεσσαλονίκης"));
noesis = map.addMarker(new MarkerOptions().position(NOESIS).title("Κέντρο Διάδοσης Επιστημών & Μουσείο Τεχνολογίας «Νόησις»"));
cinema = map.addMarker(new MarkerOptions().position(TCMC).title("Μουσείο Κινηματογράφου Θεσσαλονίκης"));
modernArt = map.addMarker(new MarkerOptions().position(SMOMA).title("Κρατικό Μουσείο Σύγχρονης Τέχνης"));
laografiko = map.addMarker(new MarkerOptions().position(LEMMT).title("Λαογραφικό και Εθνολογικό Μουσείο Μακεδονίας-Θράκης"));
leykosPyrgos = map.addMarker(new MarkerOptions().position(LP).title("Λευκός Πύργος"));
makedonikouAgona = map.addMarker(new MarkerOptions().position(MMA).title("Μουσείο Μακεδονικού Αγώνα"));
macModernArt = map.addMarker(new MarkerOptions().position(MMOCA).title("Μακεδονικό Μουσείο Σύγχρονης Τέχνης"));
olympic = map.addMarker(new MarkerOptions().position(OMT).title("Ολυμπιακό Μουσείο Θεσσαλονίκης"));
byzantinInstraments = map.addMarker(new MarkerOptions().position(BIM).title("Μουσείο Αρχαίων, Βυζαντινών και Μεταβυζαντινών Οργάνων"));
warMuseam = map.addMarker(new MarkerOptions().position(WMOT).title("Πολεμικό Μουσείο Θεσσαλονίκης"));
radioMuseam = map.addMarker(new MarkerOptions().position(RMOT).title("Μουσείο Ραδιοφωνίας Θεσσαλονίκης"));
railsMuseam = map.addMarker(new MarkerOptions().position(MORT).title("Σιδηροδρομικό Μουσείο Θεσσαλονίκης"));
telloglio = map.addMarker(new MarkerOptions().position(TIT).title("Τελλόγλειο Ίδρυμα Τεχνών"));
water = map.addMarker(new MarkerOptions().position(WM).title("Μουσείο Ύδρευσης Θεσσαλονίκης"));
photography = map.addMarker(new MarkerOptions().position(TMP).title("Μουσείο Φωτογραφίας Θεσσαλονίκης"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(THESSALONIKI, 15));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
@override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.show_map, menu);
return true;
}
public boolean onMarkerClick(Marker marker) {
if (marker.equals(thessaloniki))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(atatourk))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(byzntino))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(jewish))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(noesis))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(cinema))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(modernArt))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(laografiko))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(leykosPyrgos))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(makedonikouAgona))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(macModernArt))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(olympic))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(byzantinInstraments))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(warMuseam))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(radioMuseam))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(railsMuseam))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(telloglio))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(water))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
else if (marker.equals(photography))
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL"));
startActivity(browserIntent);
}
return true;
}
}
If you need more information please tell me.
Can't anyone help me?
alexcha92 said:
I am new at Android coding and this forum and with Google Maps. When I am trying to exprot the project to test it I am getting this error
> "app_name" is not translated in af, am, ar, be, bg, ca, cs, da, de, el, en-rGB, en-rIN, es, es-rUS, et, et-rEE, fa, fi, fr, fr-rCA, hi, hr, hu, hy-rAM, in, it, iw, ja, ka-rGE, km-rKH,
ko, lo-rLA, lt, lv, mn-rMN, ms, ms-rMY, nb, nl, pl, pt, pt-rBR, pt-rPT, ro, ru, sk, sl, sr, sv, sw, th, tl, tr, uk, vi, zh-rCN, zh-rHK, zh-rTW, zu
at values/strings.xml and exept "app_name" for "hello_world" and "menu_settings" too.
If you need more information please tell me.
Can't anyone help me?
Click to expand...
Click to collapse
The error is thrown by a check called lint which checks every dependency and guesses you want your app to be translated into all language the libraries you use are translated, in case of maps basically everyone. There is some setting for lint in the Eclipse preferences. You could completely turn lint off or configure it so it ignores the translation warnings.
Internationilization
It seems the exception has to do with translating strings into other languages. First of all never put literals into your code, all strings are placed in a strings file located in a directory/folder. the directory folder will have an extension that identifies the language for example values-en holds english strings, values-es holds espanish. when you create xml the ide ask for the configuration folder
In "Window" > "Preferences" > "Android" > "Lint Error Checking":
Find the MissingTranslation line, and set it to Warning
Little extra tip: [CODE ] and [/CODE ] tags, without the spaces, do this:
Code:
if(!formatted) {
format();
}
Sent from my GT-I9300 using Tapatalk 4
Add translatable="false" to avoid app name errors.
Code:
<string name="app_name" translatable="false">YOUR_APP_NAME</string>
Thanks guys you helped me very much!! I hope the app will work because is for a course I have. And thanks for your general tips too
Related
Okay, so i asked this question a while back and didnt get much help, but I am extremely lost. My partner who before actually programmed the app put in the necessary stuff, however i dont think it works in froyo+. I am extremely new to programming in general, and i cannot for the life of me figure this out. I have even tried other codes, but they dont work. Can someone please give me a detailed description on how to make a clock widget open the alarm clock app.
BTW this is the code that we are using at the moment:
package honeycomb.clocks;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
public class BlueClock extends AppWidgetProvider
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
{
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.blueclock);
Intent ClocksIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(new ComponentName("com.android.alarmclock", "com.android.alarmclock.AlarmClock"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ClocksIntent, 0);
views.setOnClickPendingIntent(R.id.Widget, pendingIntent);
AppWidgetManager.getInstance(context).updateAppWidget(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), views);
}
}
}
Click to expand...
Click to collapse
Hi,
I don't know if there's a better aproach, but this is the actual code I'm using to launch the alarm:
Code:
public static final Intent alarmIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
// Verify clock implementation
String clockImpls[][] = {
{"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
{"Standar Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
{"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
{"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
{"Samsung Galaxy S", "com.sec.android.app.clockpackage","com.sec.android.app.clockpackage.ClockPackage"}
};
boolean foundClockImpl = false;
for(int i=0; i<clockImpls.length; i++) {
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try {
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
alarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf) {
}
}
if (foundClockImpl)
return alarmClockIntent;
else
return null;
}
Hope it helps!
pmduque said:
Hi,
I don't know if there's a better aproach, but this is the actual code I'm using to launch the alarm:
Code:
public static final Intent alarmIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
// Verify clock implementation
String clockImpls[][] = {
{"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
{"Standar Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
{"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
{"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
{"Samsung Galaxy S", "com.sec.android.app.clockpackage","com.sec.android.app.clockpackage.ClockPackage"}
};
boolean foundClockImpl = false;
for(int i=0; i<clockImpls.length; i++) {
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try {
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
alarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf) {
}
}
if (foundClockImpl)
return alarmClockIntent;
else
return null;
}
Hope it helps!
Click to expand...
Click to collapse
Many thanks for this!!
sndytime said:
Many thanks for this!!
Click to expand...
Click to collapse
Unfortunately it didnt help me , Im not a programmer, and I dont know what Im supposed to do with this code and my partner is pissing me off
in order to launch an external activity from an appwidget you need to set a very specific flag on the intent you broadcast. mine was for launching gmail.
Code:
Intent mailClient = new Intent(Intent.ACTION_VIEW);
mailClient.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
[B]mailClient.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);[/B]
PendingIntent onClickPending = PendingIntent.getBroadcast(context, 0, mailClient, 0);
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.gitc_widget_html);
rv.setOnClickPendingIntent(R.id.full_widget, onClickPending);
//then update Your Appwidgets
//AppWidgetManager manager = AppWidgetManager.getInstance(context);
//manager.updateAppWidget(mAppWidgetId, rv);
and please realize that this was kinda a stub of what to do. i left alot out that was specific to my appwidget but that was needed for this to work. but the premise of creating an intent for what you want to launch then creating a pendingIntent and then attaching it to a view of your appwidget and then updating the remote view of you appwidget by using an AppwidgetManager holds true for any situation.
if you need me to elaborate then we can chat then.
-----
o and you aren't updating your appwidgets properly...
you need to get an array of all appwidgets you have and then call updateAppWidget on each like this (again, with my class names and such)
Code:
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, GITextCloud.class));
for (int id : ids) {
manager.updateAppWidget(id, rv);
//rv is the RemoteViews you created earlier up in the program...
//RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.gitc_widget_html);
}
pmduque said:
Hi,
I don't know if there's a better aproach, but this is the actual code I'm using to launch the alarm:
Code:
public static final Intent alarmIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
// Verify clock implementation
String clockImpls[][] = {
{"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
{"Standar Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
{"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
{"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
{"Samsung Galaxy S", "com.sec.android.app.clockpackage","com.sec.android.app.clockpackage.ClockPackage"}
};
boolean foundClockImpl = false;
for(int i=0; i<clockImpls.length; i++) {
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try {
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
alarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf) {
}
}
if (foundClockImpl)
return alarmClockIntent;
else
return null;
}
Hope it helps!
Click to expand...
Click to collapse
this isnt actually launching the clock application. you are just returning an intent that can be used to launch the clock application (still need to make a pendingIntent and attach it to a view). there is a difference and a new programmer could be very confused by this post.
other than that it looks like a nice way to find the class and package names for what clock is installed. =)
schwartzman93 said:
Unfortunately it didnt help me , Im not a programmer, and I dont know what Im supposed to do with this code and my partner is pissing me off
Click to expand...
Click to collapse
Code:
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.widget.RemoteViews;
public class Widget2 extends AppWidgetProvider
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
PendingIntent pendingIntent;
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
{
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget2);
pendingIntent = PendingIntent.getActivity(context, 0,getAlarmPackage(context), 0);
views.setOnClickPendingIntent(R.id.Widget2, pendingIntent);
AppWidgetManager
.getInstance(context)
.updateAppWidget(
intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS),
views);
}
}
public Intent getAlarmPackage(Context context)
{
PackageManager packageManager = context.getPackageManager();
Intent AlarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
String clockImpls[][] = {
{ "Standard Alarm", "com.android.alarmclock",
"com.android.alarmclock.AlarmClock" },
{ "HTC Alarm ClockDT", "com.htc.android.worldclock",
"com.htc.android.worldclock.WorldClockTabControl" },
{ "Standard Alarm ClockDT", "com.android.deskclock",
"com.android.deskclock.AlarmClock" },
{ "Froyo Nexus Alarm ClockDT",
"com.google.android.deskclock",
"com.android.deskclock.DeskClock" },
{ "Moto Blur Alarm ClockDT",
"com.motorola.blur.alarmclock",
"com.motorola.blur.alarmclock.AlarmClock" },
{ "Samsung Galaxy S", "com.sec.android.app.clockpackage",
"com.sec.android.app.clockpackage.ClockPackage" } };
boolean foundClockImpl = false;
for (int i = 0; i < clockImpls.length; i++)
{
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try
{
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn,PackageManager.GET_META_DATA);
AlarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf)
{
}
}
if (foundClockImpl)
{
return AlarmClockIntent;
}
else
{
return null;
}
}
}
Here is the Complete Source of my Appwidget Provider it generates a Clickevent on Appwidget to start the specific alarm app on the different phones.
Here is the Link to the simple Clock widget i have extended
Hope this helps!!
SUCCESS!!!!! Thank you guys so much, you have no idea how grateful I am for your help.
i created a java web service. it returns ArrayList type(text,image URL).
and my client side code i receive the by following code:
public class CustomeAdapter extends ArrayAdapter<RowItem> {
private List<RowItem> objects;
Context context;
private Bitmap bitmap;
Drawable d;
ViewHolder holder = null;
public CustomeAdapter(Context context, int listViewResourceId, List<RowItem> first) {
super(context, listViewResourceId, first);
this.context = context;
}
private class ViewHolder {
ImageView image;
TextView name,service,local;
}
@suppressLint("NewApi")
public View getView(int position, View convertView, ViewGroup parent){
//ViewHolder holder = null;
RowItem rowItem = getItem(position);
//final Bitmap bitmap = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.image=(ImageView) convertView.findViewById(R.id.imageView1);
holder.name = (TextView) convertView.findViewById(R.id.item_textView1);
holder.service = (TextView) convertView.findViewById(R.id.item_textView2);
holder.local = (TextView) convertView.findViewById(R.id.item_textView3);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.name.setText("Name:"+rowItem.getCustomerName());
holder.service.setText("Service:"+rowItem.getServiceName());
holder.local.setText("Locality:"+rowItem.getLocalityName());
String src="http://192.168.1.16:8080/"+rowItem.getImage();
try {
URL url = new URL(src);
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder.image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return convertView;
}
i am getting followimg error:
android.os.NetworkOnMainThreadException
can any one help me
I think there is a library that does this well, but can't remember it right now...
Check the library repo, and some of the apps that list libraries. Also, maybe Google will turn up something helpful.
Lazy list perhaps?
https://github.com/thest1/LazyList
I have a fragment, which contains a button that when pressed loads a new fragment. The new fragment runs an async task to populate a listview with data.
I am running into trouble, trying to load a new fragment from the onClick. The problem is I can not get the getFragmentManager();
My async task looks like this:
Code:
public class GetStyleStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
android.support.v4.app.Fragment Fragment_one;
public GetStyleStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Analyzing Statistics");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourStyleStatistics);
//make array list for beer
final List<StyleInfo> tasteList = new ArrayList<StyleInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String style = jsonArray.getJSONObject(i).getString("style");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
int count = i + 1;
style = count + ". " + style;
//create object
StyleInfo tempTaste = new StyleInfo(style, rate, beerID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
StyleInfoAdapter adapter1 = new StyleInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
StyleInfo o=(StyleInfo)arg0.getItemAtPosition(arg2);
String bID = o.id;
//todo: add onclick for fragment to load
FragmentManager man= (Activity)c.getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
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();
}
}
can not resolve method FragmentManager() is the error I am receiving
Hi,
To be able to call getFragmentManager() or getSupportFragmentManager() you'll need to use FragmentActivity, so what I would do is:
1. Make sure the activity that calls the asycTask is a FragmentActivity.
2. Pass this actvity to the asycTask.
Something like: (asyncTask method)
setActivity(Activity activity)
{
fm = activity.getFragmentManager();
}
mrsegev said:
Hi,
To be able to call getFragmentManager() or getSupportFragmentManager() you'll need to use FragmentActivity, so what I would do is:
1. Make sure the activity that calls the asycTask is a FragmentActivity.
2. Pass this actvity to the asycTask.
Something like: (asyncTask method)
setActivity(Activity activity)
{
fm = activity.getFragmentManager();
}
Click to expand...
Click to collapse
thats the problem, I launch the asyncTask from a fragment....
Oh! So you'll access your activity like this:
getActivity().getFragmentManager();
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.
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: