error: cannot find symbol variable MyOpenWeatherMapApiKey Android - android-studio

I am new to Android.I need help to solve the error below.
Got stuck here.
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create some dummy data for the ListView. Here's a sample weekly forecast
String[] data = {
"Mon 6/23 - Sunny - 31/17",
"Tue 6/24 - Foggy - 21/8",
"Wed 6/25 - Cloudy - 22/17",
"Thurs 6/26 - Rainy - 18/11",
"Fri 6/27 - Foggy - 21/10",
"Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
"Sun 6/29 - Sunny - 20/7"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
// Now that we have some dummy forecast data, create an ArrayAdapter.
// The ArrayAdapter will take data from a source (like our dummy forecast) and
// use it to populate the ListView it's attached to.
mForecastAdapter =
new ArrayAdapter<String>(
getActivity(), // The current context (this activity)
R.layout.list_item_forecast, // The name of the layout ID.
R.id.list_item_forecast_textview, // The ID of the textview to populate.
weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
// If there's no zip code, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String APPID_PARAM = "02867cfd75153da1eda43a17f213ffc5";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
}
}
}
}
[{
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.patels.sunshine";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
// Fields from build type: debug
public static final String OPEN_WEATHER_MAP_API_KEY = MyOpenWeatherMapApiKey;
}
I have written this code....I got stuck here..Unable to solve the error.
Help me out....Thank you

Under the app folder you can find build.gradle file, in this make this below changes.
Since you are using a String you have to use this syntax:
it.buildConfigField "String" , "OPEN_WEATHER_MAP_API_KEY" , "\"MyOpenWeatherMapApiKey\""
The last parameter has to be a String.

You should create an account here http://openweathermap.org/ and when you register with your email, you get an APIKey for your account. Use this api key and replace the MyOpenWeatherMapApiKey in the following line:
public static final String OPEN_WEATHER_MAP_API_KEY = MyOpenWeatherMapApiKey;
Another alternative would be to write the APIKey in grandle file as proposed already.

Related

thelinmichael/spotify-web-api-java: How to get value from Async/Sync methods

For instance, I want to obtain the uri of a Spotify track and put it in another method as a String value, however I'm lost on how I'd go about doing that. I tried experimenting with SharedPreferences to get the value but getString method wasn't working. I was just wondering if there's a simpler way to getting say track.getUri (or any) in another method from the Async/Sync method. Any assistance would be greatly appreciated.
The code so far:
private static final String accessToken = "...";
private static final String id = "01iyCAUm8EvOFqVWYJ3dVX";
public static SharedPreferences.Editor editor;
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setAccessToken(accessToken)
.build();
private static final GetTrackRequest getTrackRequest = spotifyApi.getTrack(id)
// .market(CountryCode.SE)
.build();
public static void getTrack_Sync() {
try {
final Track track = getTrackRequest.execute();
System.out.println("Name: " + track.getName());
} catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage());
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void getTrack_Async() {
try {
final CompletableFuture<Track> trackFuture = getTrackRequest.executeAsync();
// Thread free to do other tasks...
// Example Only. Never block in production code.
final Track track = trackFuture.join();
String uri = track.getUri();
editor = getSharedPreferences("uri", 0).edit();
editor.putString("uri", uri);
editor.commit();
editor.apply();
System.out.println("Name: " + track.getUri());
} catch (CompletionException e) {
System.out.println("Error: " + e.getCause().getMessage());
} catch (CancellationException e) {
System.out.println("Async operation cancelled.");
}
}
public void go() {
getTrack_Async();
// String value = editor.getString("uri", )
}
To get the track you need some kind of information to start with. e.g. I have the spotify trackId and can find the track (synchronously) like this:
public Track getTrack(String trackId) {
return spotifyApi.getTrack(trackId).build().execute();
}
Now the Track object (specifically com.wrapper.spotify.model_objects.specification.Track) provides a lot of information. e.g. the field uri.
So you could do just:
public void run(String trackId) {
Track track = spotifyApi.getTrack(trackId).build().execute();
String uri = track.uri;
// now call something else with the uri?
}
Does that help? Your question was not entirely clear for me.

J2ME - How to make a thread return a value and after that thread is finished, use the return value in other operations?

I got some questions regarding the use of threads, specially when you have to wait for a thread to be finished so you can perform other operations.
In my app, I use threads for operations such as http connections or when I read from or write to a RecordStore.
For example in the following class that I use to initialize my thread, I retrieve some customers from a webservice using the method called HttpQueryCustomers.
public class thrLoadCustomers implements Runnable {
private RMSCustomer mRMSCustomer;
private String mUrl;
public thrLoadCustomers(RMSCustomer rmsCust, String url) {
mRMSCustomer = rmsCust;
mUrl = url;
}
public void run() {
String jsonResultados = "";
try {
jsonResultados = HttpQueryCustomers();
} catch (IOException ex) {
//How to show a message from here??
} catch (SecurityException se) {
//How to show a message here??
} catch (NullPointerException npe) {
//How to show a message from here??
}
if (!jsonResultados.equals("")) {
try {
mRMSCustomer.save(jsonResultados);
} catch (RecordStoreException ex) {
//How to show a message from here???
}
}
}
public String HttpQueryCustomers() throws IOException,SecurityException,NullPointerException {
StringBuffer stringBuffer = new StringBuffer();
HttpConnection hc = null;
InputStream is = null;
System.out.println(mUrl);
try {
hc = (HttpConnection) Connector.open(mUrl);
if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
is = hc.openInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
}
} finally {
is.close();
hc.close();
}
String jsonData = stringBuffer.toString();
return jsonData.toString();
}
}
Notice in the above class that I pass a parameter called rmsCust of the type RMSCustomer
RMSCustomer is a class that I use to handle all the operations related to RMS:
public class RMSCustomer {
private String mRecordStoreName;
private Customer[] mCustomerList;
public RMSCustomer(String recordStoreName) {
mRecordStoreName = recordStoreName;
}
public Customer[] getCustomers() {
return mCustomerList;
}
public Customer get(int index) {
return mCustomerList[index];
}
public void save(String data) throws RecordStoreException,JSONException,NullPointerException {
RecordStore rs = null;
int idNuevoRegistro;
String stringJSON;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
JSONArray js = new JSONArray(data);
//Set the size of the array
mCustomerList = new Customer[js.length()];
for (int i = 0; i < js.length(); i++) {
JSONObject jsObj = js.getJSONObject(i);
stringJSON = jsObj.toString();
idNuevoRegistro = addRecord(stringJSON, rs);
//Add a new Customer to the array
mCustomerList[i] = initializeCustomer(stringJSON, idNuevoRegistro);
}
} finally {
if (rs != null) {
rs.closeRecordStore();
}
}
}
public int addRecord(String stringJSON, RecordStore rs) throws JSONException,RecordStoreException {
byte[] raw = stringJSON.getBytes();
int idNuevoRegistro = rs.addRecord(raw, 0, raw.length);
return idNuevoRegistro;
}
public Customer initializeCustomer(String stringJSON, int idRecord) throws JSONException {
Customer c = new Customer();
JSONObject jsonObj = new JSONObject(stringJSON);
// Set Customer properties
//...
return c;
}
}
This class is used to show a list of customer and ,as you can see, it extends the List class and receives an array of Customers as a parameter.
public class ListCustomers extends List {
private final Customer[] mData;
public static ListCustomers create(Customer[] data) {
int i = 0;
for (; i < data.length; i++) {
if (data[i] == null) {
break;
}
}
String[] names = new String[i];
for (int j = 0; j < i; j++) {
names[j] = data[j].name;
}
return new ListCustomers(names, data);
}
protected ListCustomers(String names[], Customer[] data) {
super("List of Customer", IMPLICIT, names, null);
mData = data;
}
public Customer getSelectedObject() {
return mData[this.getSelectedIndex()];
}
}
Finally this is how I call the thread from the MIDlet (using all the 3 previous classes) when I want to show a List of Customers:
private void showCustomerList(String url) {
showWaitForm();
if (scrCustomerList == null) {
rmsCustomers = new RMSCustomer("rmsCustomers");
thrLoadCustomers load = new thrLoadCustomers(rmsCustomers, url);
Thread t = new Thread(load);
t.start();
try {
t.join();
} catch (InterruptedException ex) {
}
scrCustomerList = ListCustomers.create(rmsCustomers.getCustomers());
scrCustomerList.addCommand(cmdSelect);
scrCustomerList.addCommand(cmdBack);
scrCustomerList.setCommandListener(this);
}
mDisplay.setCurrent(scrCustomerList);
}
Now here's the problems I have :
The showWaitForm() doesn't work (it sets a form with a Gauge as the
Current form)
I don't know how to show all the exceptions that might be thrown from
within the thrLoadCustomers class.
I don't know whether using t.join() is the best choice
The last question is about something the book I'm reading says :
Threads, in particular, can be a scarce commodity. The MSA
specification requires that an application must be allowed to create
ten threads. Just because you can doesn’t mean you should. In general,
try to use the fewest resources possible so that your application will
run as smoothly as possible
This is the first time a use threads, and in my app I might have up to 10 threads (classes). However, I will only execute once thread at the time, will I be going against what the previous quotation says??
I hope I'm not asking too many questions. Thank you very much for your help.
P.D Much of the code I posted here wouldn't have been possible with the help of Gregor Ophey
Question #1 is about a different problem not related to threading, and for which very little code is shown. I'd suggest you to post a new dedicated question with proper explanation of the issue.
Questions #2 and #3: You could define a wrapper class like this:
public class WSResult {
private boolean success; //true if the WS call went ok, false otherwise
private String errorMessage; //Error message to display if the WS call failed.
private Object result; //Result, only if the WS call succeeded.
private boolean completed = false;
//TODO getter and setters methods here
}
In your screen, you can create an instance of result and wait for it:
WSResult result = new WSResult();
//Start thread here
new Thread(new LoadCustomersTask(result)).start();
//This is old school thread sync.
synchronized(result){
while(!result.isCompleted()){
result.wait();
}
}
//Here the thread has returned, and we can diaplay the error message if any
if(result.isSuccess()){
} else {
//Display result.getErrorMessage()
}
Then your runnable would be like this:
class LoadCustomersTask implements Runnable {
private final WSResult result;
public LoadCustomersTask(WSResult res){
result = res;
}
public void run(){
//Do the WS call
//If it went well
result.setSuccess(true);
result.setResult(jsonResultados);
//Else
result.setSuccess(false);
result.setErrorMessage("Your error message");
//In any case, mark as completed
result.setcompleted(true);
//And notify awaiting threads
synchronized(result){
result.notifyAll();
}
}
}
You can also do it with thread.join, but wait/notify is better because you not making the screen depend on the particular thread where the runnable runs. You can wait/notify on the result instance, as shown, or on the runnable if it is intended for a single use.
Question #4: Yes threads must not be abused, specially in JavaME where programs usually run in single core CPUs with a frecuency in the order of MHz. Try not to have more than 1-3 threads running at the same time. If you really need to, consider using a single thread for running all background tasks (a blocking queue).

use thread inside buttonclick in android

I am receiving temperature values from a sensor through BLE and storing it in my db and passing the values as an array through intent to graph activity and diplaying a line graph. I am also posting the values to google app engine. i am doing this all within runOnUiThread() and hence my app crashes when there are too many values.Is it possible to pass values into the graph activity on a new thread? or any other better suggestions?
#Override
public void propertyChange(final PropertyChangeEvent event) {
final String property = event.getPropertyName();
runOnUiThread(new Runnable() {
public void run() {
try {
if (property.equals(PROPERTY_IR_TEMPERATURE)) {
double newIRValue = (Double) event.getNewValue();
// float newIRValue_1 = (Float) event.getNewValue();
TextView textView = (TextView) findViewById(R.id.ir_temperature);
String value = decimal.format(newIRValue);
String formattedText = value + DEGREE_SYM;
float value_chk = (float)(newIRValue);
String formattedText_1 = String.valueOf(value_chk);
String sensorid = test_1;
String sensortype = "temperature";
// write_data(sensorid,sensortype,value);
// Toast.makeText(getBaseContext(), "ARV sensid:"+sensorid+" senstype:"+sensortype, Toast.LENGTH_SHORT).show();
long timemilli = System.currentTimeMillis();
//Log.d("TIMMEE", String.valueOf(timemilli));
String time=String.valueOf(timemilli);
db = new DBHandler(getApplicationContext());
//db.deleteTempReadings();
// inserting data to temp table
Log.i("insert", "Inserting Records...");
);
Temperature(sensorid,formattedText_1));
//Toast.makeText(getBaseContext(), "SENSOR_ID:"+t.getSensorId()+"TEMPERATURE: "+t.getTemperature()+"TIME: "+t.getTimestamp(), Toast.LENGTH_LONG).show();
// reading data from db
Log.i("Reading", "Reading Records...");
List<Temperature> temp = db.getAllTempReadings();
int arraySize=temp.size();
double tempArray[]=new double[arraySize];
int timeArray[]=new int [arraySize];
//Log.d("ans", String.valueOf(temp.size()));
for (Temperature t : temp) {
String log="SENSOR ID: "+t.getSensorId()+"TEMPERATURE: "+t.getTemperature()+"TIME: "+t.getTimestamp();
Log.d("Record"+t, log);
}
// Reading values into the array!
for(int i=0;i<arraySize;i++){
tempArray[i]=Double.parseDouble(temp.get(i).getTemperature());
}
Button btn=(Button)findViewBy Id(R.id.btnGraph);
btn.setOnCLickListener(new View.onClickListener(){
public void onClick(View v){
Intent iIntent =new Intent(getApplicationContext(),GraphActivity.class);
tIntent.putExtra("tempArray",tempArray);
startActivity(tIntent);
}
});
// rest....posting to server code......
textView.setText(formattedText);
}
}
}
}
}
The temperature value you get from the sensor upto this you have to do stuff in one thread and after that you have to start three thread one for the inserting into the DB, the other one for the displaying the line graph and the last and the third one for the posting the data into the google app engine.
I think you are a bit confused here. The idea is to keep slow processing OUT of your UI thread. I suggest you do the writes to the DB and the App engine first in the 'current' (presumably less critical) thread and then when all is done simply update the graph display in the UI thread.
The only reason you need RunOnUiThread is to make changes to the views on the screen.

How to get list of folders present in a directory in SVN using java

I am using svnkit-1.3.5.jar in my application. On one of my screens on clicking a button I need to display a jQuery dialog box containing list of folders present at a particular path in SVN. Does svnkit provide any method that retrieves all folder names present at a specific location? How do I achieve this in java?
Here is the code i use for the same purpose (uses svnkit library). Modified version of #mstrap's code for better clarity.
public static String NAME = "svnusername";
public static String PASSWORD = "svnpass";
public final String TRUNK_VERSION_PATH = "svn://192.168.1.1/path";
public static List<String> apiVersions;
public List<String> getApiVersion() {
logger.info("Getting API Version list....");
apiVersions = new ArrayList<String>();
SVNURL repositoryURL = null;
try {
repositoryURL = SVNURL.parseURIEncoded(TRUNK_VERSION_PATH);
} catch (SVNException e) {
logger.error(e);
}
SVNRevision revision = SVNRevision.HEAD;
SvnOperationFactory operationFactory = new SvnOperationFactory();
operationFactory.setAuthenticationManager(new BasicAuthenticationManager(NAME, PASSWORD));
SvnList list = operationFactory.createList();
list.setDepth(SVNDepth.IMMEDIATES);
list.setRevision(revision);
list.addTarget(SvnTarget.fromURL(repositoryURL, revision));
list.setReceiver(new ISvnObjectReceiver<SVNDirEntry>() {
public void receive(SvnTarget target, SVNDirEntry object) throws SVNException {
String name = object.getRelativePath();
if(name!=null && !name.isEmpty()){
apiVersions.add(name);
}
}
});
try {
list.run();
} catch (SVNException ex) {
logger.error(ex);
}
return apiVersions;
}
Cheers!!
final URL url = ...
final SVNRevision revision = ...
final SvnOperationFactory operationFactory = ...
final SvnList list = operationFactory.createList();
list.setDepth(SVNDepth.IMMEDIATES);
list.setRevision(revision);
list.addTarget(SvnTarget.fromURL(url, revision);
list.setReceiver(new ISvnObjectReceiver<SVNDirEntry>() {
public void receive(SvnTarget target, SVNDirEntry object) throws SVNException {
final String name = object.getRelativePath();
System.out.println(name);
}
});
list.run();

Unable to Serialize into XML

I am trying to Serialize the content of some text into an XML file (performed when a user saves their selections), and then will later deserialize it (when the user chooses to display their saved selection).
I have been following the following tutorial on serialization.
I have also tried to do this via LINQ to XML but was either getting namespace errors, or the tool returned no errors, but did not work (with the same problem as described below).
The problem I am having is that my code is not returning any errors, but the function is not working (I have a label control that allows me to see that the 'catch' is being returned). I am building the tool in Expression Blend, using C#.
Here is my SaveSelection.cs Class
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.Xml;
namespace DYH
{
public class SaveSelections
{
[XmlAttribute("Title")]
public string Title
{ get; set; }
[XmlElement("Roof")]
public string RoofSelection
{ get; set; }
[XmlElement("Cladding")]
public string CladdingSelection
{ get; set; }
[XmlElement("MixedCladding")]
public string MixedCladdingSelection
{ get; set; }
[XmlElement("FAJ")]
public string FAJSelection
{ get; set; }
[XmlElement("GarageDoor")]
public string GarageDoorSelection
{ get; set; }
[XmlElement("FrontDoor")]
public string FrontDoorSelection
{ get; set; }
}
}
Here is my C# code
// Save Selection Button
private void Button_SaveSelection_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
// Save selections into the SavedSelections.xml doc
SaveSelections userselection = new SaveSelections();
userselection.Title = TextBox_SaveSelection.Text;
userselection.RoofSelection = Button_Roof_Select.Text;
userselection.CladdingSelection = Button_Cladding_Select.Text;
userselection.MixedCladdingSelection = Button_MixedCladding_Select.Text;
userselection.FAJSelection = Button_FAJ_Select.Text;
userselection.GarageDoorSelection = Button_GarageDoor_Select.Text;
userselection.FrontDoorSelection = Button_FrontDoor_Select.Text;
SerializeToXML(userselection);
// XDocument xmlSaveSelections = XDocument.Load("../SavedSelections.xml");
//
// XElement newSelection = new XElement("Selection", //xmlSaveSelections.Element("Selections").Add(
// //new XElement("Selection",
// new XElement("Title", TextBox_SaveSelection.Text),
// new XElement("RoofSelection", Button_Roof_Select.Text),
// new XElement("CladdingSelection", Button_Cladding_Select.Text),
// new XElement("MixedCladdingSelection", Button_MixedCladding_Select.Text),
// new XElement("FAJSelection", Button_FAJ_Select.Text),
// new XElement("GarageDoorSelection", Button_GarageDoor_Select.Text),
// new XElement("FrontDoorSelection", Button_FrontDoor_Select.Text));
//
//// xmlSaveSelections.Add(newSelection);
//// xmlSaveSelections.Save("../SavedSelections.xml");
SelectionLabel.Text = "Your selection has been saved as " + "'" + TextBox_SaveSelection.Text + "'. We suggest you write down the name of your selection.";
}
catch(Exception ex)
{
throw ex;
SelectionLabel.Text = "There was a problem saving your selection. Please try again shortly.";
}
}
// Saves SaveSelection.cs to XML file SavedSelections.xml
static public void SerializeToXML(SaveSelections selection)
{
XmlSerializer serializer = new XmlSerializer(typeof(SaveSelections));
TextWriter textWriter = new StreamWriter(#"/SavedSelections.xml");
serializer.Serialize(textWriter, selection);
textWriter.Close();
}
I have left evidence of one of my previous attempts commented out so you can see a previous format I tried.
My issue is that when I try to use the tool, the SelectionLabel.Text returns "There was a problem saving your selection. Please try again shortly." so I know that the code is returning the catch and not executing the 'try'.
Any help??
Edit 18/6/2012: The below code was the code that worked as per correct answer to question.
public void Button_SaveSelection_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
string roofSelection = TextBox_SaveSelection.Text + "_RoofSelection";
string claddingSelection = TextBox_SaveSelection.Text + "_CladdingSelection";
string mixedCladdingSelection = TextBox_SaveSelection.Text + "_MixedCladdingSelection";
string fajSelection = TextBox_SaveSelection.Text + "_FAJSelection";
string garageDoorSelection = TextBox_SaveSelection.Text + "_GarageDoorSelection";
string frontDoorSelection = TextBox_SaveSelection.Text + "_FrontDoorSelection";
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
// Gives us 6Mb of storage space in IsoStore
Int64 isoSpaceNeeded = 1048576 * 6;
Int64 currentIsoSpace = store.AvailableFreeSpace;
// If space needed is greater than (>) space available, increase space
if (isoSpaceNeeded > currentIsoSpace)
{
// If user accepts space increase
if (store.IncreaseQuotaTo(currentIsoSpace + isoSpaceNeeded))
{
IsolatedStorageFileStream file = store.CreateFile("SavedSelections.txt");
file.Close();
// Stream writer to populate information in
using (StreamWriter sw = new StreamWriter(store.OpenFile("SavedSelections.txt", FileMode.Open, FileAccess.Write)))
{
appSettings.Add(roofSelection, Button_Roof_Select.Text);
sw.WriteLine(roofSelection);
appSettings.Add(claddingSelection, Button_Cladding_Select.Text);
sw.WriteLine(claddingSelection);
appSettings.Add(mixedCladdingSelection, Button_MixedCladding_Select.Text);
sw.WriteLine(mixedCladdingSelection);
appSettings.Add(fajSelection, Button_FAJ_Select.Text);
sw.WriteLine(fajSelection);
appSettings.Add(garageDoorSelection, Button_GarageDoor_Select.Text);
sw.WriteLine(garageDoorSelection);
appSettings.Add(frontDoorSelection, Button_FrontDoor_Select.Text);
sw.WriteLine(frontDoorSelection);
}
SelectionLabel.Text = "Your selection has been saved as " + "'" + TextBox_SaveSelection.Text + "'. We suggest you write down the name of your selection.";
}
}
}
SelectionLabel.Text = "Your selection has been saved as " + "'" + TextBox_SaveSelection.Text + "'. We suggest you write down the name of your selection.";
}
catch //(Exception ex)
{
//throw ex;
SelectionLabel.Text = "There was a problem saving your selection. Please try again shortly.";
}
}
It looks like your issue is because you're trying to a file, but that file did not come from a FileSaveDialog initiated by a user action. You're running into a security feature of Silverlight where you're not allowed access to the local file system. Instead, try writing to IsolatedStorage. However, be aware that end users can completely (as well as selectively) disable application storage so you'll need to handle those exceptions as well.
Here's a quick article on how to use IsolatedStorage.

Resources