WP8 issue with html agility pack - windows-phone-8

This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}

Related

org.json.JSONException: No value for opening_hours ,how to handle this type of error

logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)

How to get url of uploaded file to google drive in android using Drive API?

I need to get the link of the video that I upload it to google drive so that I can open the video in the web browser, I can upload a video file to google drive and can get also the file ID using the following code:
private void UploadFile(final DriveId driveId)
{
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult)
{
if (!driveContentsResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create new file contents");
return;
}
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
Toast.makeText(context, "Uploading to drive....", Toast.LENGTH_LONG).show();
final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoFiles/testVideo.mkv");
try
{
FileInputStream fileInputStream = new FileInputStream(theFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1)
{
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mkv").setStarred(false).build();
DriveFolder folder = driveId.asDriveFolder();
folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(#NonNull DriveFolder.DriveFileResult driveFileResult)
{
if (!driveFileResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the file");
return;
}
Log.v(TAG, "Created a file: " + driveFileResult.getDriveFile().getDriveId());
}
});
}
});
}
I tried to get the video url using the following code:
DriveFile file = Drive.DriveApi.getFile(googleApiClient,driveId);
DriveResource.MetadataResult mdRslt = file.getMetadata(googleApiClient).await();
if (mdRslt != null && mdRslt.getStatus().isSuccess()) {
String link = mdRslt.getMetadata().getWebContentLink();
Log.d("LINK", link);
}
But then I got "Cannot resolve symbol 'googleApiClient'
Any suggestion please?
Ok, I found the solution, first I have to get the completed file ID by using the change events listener, then we can add "drive.google.com/open?id=" to the file ID, so the complate url will be drive.google.com/open?id=FileID.
here is my answer:
public class Uploader extends Activity implements ConnectionCallbacks,OnConnectionFailedListener{
private static final String TAG = "Google Drive Activity";
private static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
public DriveFile file;
private String FOLDER_NAME = "GD_VideoFile";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume()
{
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onStop()
{
super.onStop();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result)
{
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint)
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
if (mGoogleApiClient != null)
{
check_folder_exists();
} else
{
Log.e(TAG, "Could not connect to google drive manager");
}
}
#Override
public void onConnectionSuspended(int cause)
{
Log.i(TAG, "GoogleApiClient connection suspended");
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data)
{
switch (requestCode)
{
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK)
{
DriveId mFileId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + "");
String url = "https://drive.google.com/open?id="+ mFileId.getResourceId();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void check_folder_exists()
{
Query query = new Query.Builder().addFilter(Filters.and(Filters.eq(SearchableField.TITLE, FOLDER_NAME), Filters.eq(SearchableField.TRASHED, false))).build();
Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(#NonNull DriveApi.MetadataBufferResult result)
{
if (!result.getStatus().isSuccess())
{
Log.e(TAG, "Cannot create folder in the root.");
} else
{
boolean isFound = false;
for (Metadata m : result.getMetadataBuffer())
{
if (m.getTitle().equals(FOLDER_NAME)) {
Log.e(TAG, "Folder exists");
isFound = true;
DriveId driveId = m.getDriveId();
UploadFile(driveId);
break;
}
}
if (!isFound)
{
Log.i(TAG, "Folder not found; creating it.");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(FOLDER_NAME).build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
#Override
public void onResult(#NonNull DriveFolder.DriveFolderResult result)
{
if (!result.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the folder");
} else {
Log.i(TAG, "Created a folder");
DriveId driveId = result.getDriveFolder().getDriveId();
UploadFile(driveId);
}
}
});
}
}
}
});
}
private void UploadFile(final DriveId driveId)
{
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>()
{
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult)
{
if (!driveContentsResult.getStatus().isSuccess())
{
Log.e(TAG, "U AR A MORON! Error while trying to create new file contents");
return;
}
OutputStream outputStream = driveContentsResult.getDriveContents().getOutputStream();
Toast.makeText(Uploader.this, "Uploading to drive....", Toast.LENGTH_LONG).show();
final File theFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyMobile_Videos/a.mov");
try
{
FileInputStream fileInputStream = new FileInputStream(theFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1)
{
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(theFile.getName()).setMimeType("video/mov").setStarred(false).build();
DriveFolder folder = driveId.asDriveFolder();
folder.createFile(mGoogleApiClient, changeSet, driveContentsResult.getDriveContents()).setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>()
{
#Override
public void onResult(#NonNull DriveFolder.DriveFileResult driveFileResult)
{
if (!driveFileResult.getStatus().isSuccess())
{
Log.e(TAG, "Error while trying to create the file");
return;
}
Toast.makeText(Uploader.this, "Created a file: " + driveFileResult.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
String Folder_Id = driveId.getResourceId();
System.out.println("The folder id: " +Folder_Id);
//This is to get the file id from the listener
DriveId File_Uncompleted_Id = driveFileResult.getDriveFile().getDriveId();
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, File_Uncompleted_Id);
file.addChangeListener(mGoogleApiClient, changeListener);
}
//A listener to handle file change events.
final private ChangeListener changeListener = new ChangeListener()
{
#Override
public void onChange(ChangeEvent event)
{
String File_Completed_Id = event.getDriveId().getResourceId();
System.out.println("The uploaded file id: " +File_Completed_Id);
System.out.println("File URL: https://drive.google.com/open?id=" +File_Completed_Id);
}
};
}
);
}
}
);
}
}

Clear image cache created by <Image>

If I have an element like this in a Windows Store or Windows Phone application:
<Image Source="{Binding UrlToWebServer}" />
the image is cached locally. This is great. But how do I remove all cached images on disc from code?
You just have to set the imagesource to NULL
Something like this:
BitmapImage bitmapImage = myimage.Source as BitmapImage;
bitmapImage.UriSource = null;
myimage.Source = null;
This works for me. Here you can find mor infos handling images (section Image Caching for example).
Hi it´s a little bit late to answer this question but you can use this class to delete the cache of a specific files or all if you want
this is the class helper
class CacheCleanup : IDisposable
{
private DispatcherTimer cleanCacheTimer;
public CacheCleanup(TimeSpan? cleanInterval = null)
{
if (!cleanInterval.HasValue)
cleanInterval = TimeSpan.FromMinutes(0.2);
cleanCacheTimer = new DispatcherTimer();
cleanCacheTimer.Interval = cleanInterval.Value;
cleanCacheTimer.Tick += CleanCacheTimer_Tick;
cleanCacheTimer.Start();
}
private void CleanCacheTimer_Tick(object sender, object e)
{
try
{
StorageFolder localDirectory = ApplicationData.Current.LocalFolder;
string[] tmpCacheDirectories = Directory.GetDirectories(localDirectory.Path + "\\..\\ac\\inetcache");
foreach (string dir in tmpCacheDirectories)
{
string[] tmpCacheFilesPng = Directory.GetFiles(dir, "*.png");
foreach (string file in tmpCacheFilesPng)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted png: " + file);
}
catch (Exception) { }
}
string[] tmpCacheFilesJpg = Directory.GetFiles(dir, "*.jpg");
foreach (string file in tmpCacheFilesJpg)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted jpg: " + file);
}
catch (Exception) { }
}
}
}
catch (Exception ex) { Debug.WriteLine("ERROR CLEANING CACHE: " + ex.Message); }
}
public void Dispose()
{
if (cleanCacheTimer != null)
{
cleanCacheTimer.Stop();
cleanCacheTimer = null;
}
}
}
and this is the way how you can call this class in some part of your c# code
CacheCleanup cacheCleanup = new CacheCleanup();

Waiting and Return a result with DownloadStringAsync WP8

I do a webrequest with DownloadStringAsync() but I need to return the result only when the DownloadStringCompleted event has been called. After the downloadasync-method, I need to wait for the result and then I could return it in a string property. So I implemented a while(Result == "") but I don't know what to do there. I already tried Thread.sleep(500) but it seems the download never gets completed. And the code remains in the while forever.
string Result = "";
public String Query(DataRequestParam dataRequestParam)
{
try
{
WebClient web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += OnDownloadStringCompleted;
web.DownloadStringAsync(dataRequestParam.TargetUri);
while (Result == "")
{
//What am i supposed to do here ?
}
return Result;
}
catch(WebException we)
{
MessageBox.Show(we.Message);
return null;
}
}
private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
//Error treating
}
else
{
Result = e.Result;
}
}
UI CODE
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode != NavigationMode.Back)
{
ServerFunctions.SetUserProfil(User.UserLogin,User.UserPassword);
this.listBoxGetDocsLibs.Clear();
List<BdeskDocLib> list = new List<BdeskDocLib>();
try
{
//HERE THE START OF THE DOWNLOAD
ServerFunctions.GetDocLibs(true);
}
catch (Exception ex)
{
//error
}
foreach (BdeskDocLib docLib in list)
{
this.listBoxGetDocsLibs.Add(docLib);
}
}
}
the ServerFunction static class
public static List<BdeskDocLib> GetDocLibs(bool onlyDocLibPerso)
{
string xmlContent = GetXml(URL_GETDOCLIBS);
List<BdeskDocLib> result = BdeskDocLib.GetListFromXml(xmlContent, onlyDocLibPerso);
return result;
}
private static String GetXml(string partialUrl)
{
string url = GenerateUrl(partialUrl);
DataRequestParam dataRequestParam = new DataRequestParam();
dataRequestParam.TargetUri = new Uri(url);
dataRequestParam.UserAgent = "BSynchro";
dataRequestParam.AuthentificationLogin = userLogin;
dataRequestParam.AuthentificationPassword = userPwd;
//HERE I START THE QUERY method
// NEED QUERY RETURNS A STRING or Task<String>
DataRequest requesteur = new DataRequest();
xmlResult=requesteur.Query(dataRequestParam);
if (CheckErrorConnexion(xmlResult) == false)
{
throw new Exception("Erreur du login ou mot de passe");
}
return xmlResult;
}
There is nothing good in blocking main UI (unless you really need to). But if you want to wait for your result you can make some use of async-await and TaskCompletitionSource - you can find more about on this blog and how to use TCS in this answer:
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
public async Task<string> Query(DataRequestParam dataRequestParam)
{
string Result = "";
try
{
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)
{
MessageBox.Show(we.Message);
return null;
}
return Result;
}
(I've not tried this code, there maight be some mistakes, but it should work)
Basing on this code you can also extend your WebClient with awaitable version of download string.

Http Post with Blackberry 6.0 issue

I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}