Auth Exception in Pinterest API - pinterest

I am getting { "status": "failure", "code": 3, "host": "coreapp-devplatform-devapi-173", "generated_at": "Tue, 29 Sep 2015 05:42:42 +0000", "message": "Authorization failed.", "data": null } exception while invoking https://api.pinterest.com/v1/oauth/token?code=&client_id=&grant_type=authorization_code. Can anyone help me to resolve this?
Code:
if (request.getParameter("code") != null) {
code = request.getParameter("code");
}
String authorizeUrl = "https://api.pinterest.com/v1/oauth/token";
String postStr = "code=" + code + "&client_id=" + clientId + "&grant_type=authorization_code";
String responseStr = postTokenRequest(authorizeUrl, postStr);
//Method
public String postTokenRequest(String serverURL, String content) {
String inputLine = "";
HttpsURLConnection connection = null;
URL url = new URL(serverURL);
String method = "POST";
InputStream connectionIn = null;
BufferedReader buffer = null;
try {
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.getOutputStream().write(content.getBytes());
int returnCode = connection.getResponseCode();
if (returnCode == 200) {
connectionIn = connection.getInputStream();
} else {
connectionIn = connection.getErrorStream();
}
buffer = new BufferedReader(new InputStreamReader(connectionIn));
StringBuilder sb = new StringBuilder();
while ((inputLine = buffer.readLine()) != null) {
sb.append(inputLine);
}
buffer.close();
return sb.toString();
}catch(Exception e){}
}

Related

Poper way to make a HTTPClient PostAsync and GetAsync?

I want to make a proper HTTPClient request. I have a code but I am always getting so may exceptions like:
Java.IO.IOException: Socket closed
System.OperationCanceledException: The operation was canceled.
Java.Net.SocketException: Connection reset
Java.Net.SocketException: Software caused connection abort
Java.Net.UnknownHostException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
Java.Net.UnknownHostException: Unable to resolve host "tbs.scratchit.ph": No address associated with hostname
Java.IO.IOException: isConnected failed: ETIMEDOUT (Connection timed out)
Java.Net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
I am always getting these kinds of exceptions, errors.
I am starting to wonder how can I create a Post Async and GetAsync properly to avoid these errors in the future?
Here is how I create a HTTP Client:
1. I have a class call Constants, in there I will declare a new HTTP Client so that I only have 1 HTTPClient across my project
public class Constants
{
public static HttpClient client = new HttpClient();
}
2. I have a function(s) that gets data from my server through a PHP API by sending the parameters through JSON.
public async void FirstTimeSyncUser(string host, string database, string contact, string ipaddress)
{
try
{
syncStatus.Text = "Checking internet connection";
string apifile = "first-time-sync-user-api.php";
if (CrossConnectivity.Current.IsConnected)
{
syncStatus.Text = "Initializing first-time user sync";
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getData = conn.QueryAsync<UserTable>("SELECT * FROM tblUser WHERE ContactID = ? AND Deleted != '1'", contact);
var resultCount = getData.Result.Count;
var current_datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
int count = 1;
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
if (resultCount == 0)
{
syncStatus.Text = "Getting user data from the server";
var link = "http://" + ipaddress + "/" + Constants.apifolder + "/api/" + apifile;
string contentType = "application/json";
JObject json = new JObject
{
{ "Host", host },
{ "Database", database },
{ "ContactID", contact }
};
Constants.client.DefaultRequestHeaders.ConnectionClose = true;
var response = await Constants.client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
{
try
{
var dataresult = JsonConvert.DeserializeObject<List<UserData>>(content, settings);
var datacount = dataresult.Count;
for (int i = 0; i < datacount; i++)
{
syncStatus.Text = "Syncing user " + count + " out of " + datacount;
var item = dataresult[i];
var userid = item.UserID;
var usrpassword = item.UsrPassword;
var usertypeid = item.UserTypeID;
var userstatus = item.UserStatus;
var lastsync = DateTime.Parse(current_datetime);
var lastupdated = item.LastUpdated;
var deleted = item.Deleted;
var insertdata = new UserTable
{
UserID = userid,
UsrPassword = usrpassword,
ContactID = contact,
UserTypeID = usertypeid,
UserStatus = userstatus,
LastSync = lastsync,
LastUpdated = lastupdated,
Deleted = deleted
};
await conn.InsertOrReplaceAsync(insertdata);
count++;
}
synccount += "Total synced user: " + count + "\n";
var logType = "App Log";
var log = "Initialized first-time sync (<b>User</b>) <br/>" + "App Version: <b>" + Constants.appversion + "</b><br/> Device ID: <b>" + Constants.deviceID + "</b>";
int logdeleted = 0;
Save_Logs(contact, logType, log, database, logdeleted);
Preferences.Set("userchangeslastcheck", current_datetime, "private_prefs");
FirstTimeSyncSystemSerial(host, database, contact, ipaddress);
}
catch
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Failed to send the data.\n\n Error:\n\n" + content + "\n\n Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
else
{
Preferences.Set("userchangeslastcheck", current_datetime, "private_prefs");
FirstTimeSyncSystemSerial(host, database, contact, ipaddress);
}
}
else
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Server is unreachable.\n\n Error:\n\n"+ response.StatusCode +" Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
else
{
SyncUserClientUpdate(host, database, contact, ipaddress);
}
}
else
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Please connect to the internet to sync your data. Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
var retry = await DisplayAlert("Application Error", "Syncing failed. Failed to send the data.\n\n Error:\n\n" + ex.Message.ToString() + "\n\n Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
3. After getting the data I needed it will execute another function with another POSTASYNC Call. In my code above when I got the user data from my server it will execute the next function which is FirstTimeSyncSystemSerial(host, database, contact, ipaddress);
What am I doing wrong? and How can I improve this so that I can avoid these exceptions?
Debug your code to find out where the exception is thrown.
Put a try catch blocked around that block of code. Then catch all the expected exceptions and try loopback again for a number of time.
You can Make a Generic Custom Service call That Can be Called Anywhere When You Need
public class RestClient : IRestClient
{
private const string TokenHeaderKey = "Any Token Header";
private HttpClient _httpclient = new HttpClient();
public async Task<T> GetAsync<T>(string url, string token) where T : new()
{
var responseContent = await ExecuteRequest(
async () =>
{
try
{
AddTokenToDefaultRequestsHeader(token);
return await _httpclient.GetAsync(url);
}
finally
{
ClearAuthenticationHeader();
}
});
return await Deserialize<T>(responseContent);
}
private void AddTokenToDefaultRequestsHeader(string token)
{
_httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TokenHeaderKey, token);
}
private void ClearAuthenticationHeader()
{
_httpclient.DefaultRequestHeaders.Authorization = null;
}
private static async Task<HttpContent> ExecuteRequest(Func<Task<HttpResponseMessage>> requestFunc)
{
HttpResponseMessage response = null;
try
{
response = await requestFunc();
if (!response.IsSuccessStatusCode)
{
var message = $"Executed HTTP request returned status code {response.StatusCode} and reason phrase {response.ReasonPhrase}";
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new Exception(message);
}
throw new Exception(message);
}
return response.Content;
}
catch (Exception exception)
{
if (exception is HttpRequestException || exception is WebException || exception is TaskCanceledException)
{
throw new Exception(
"Could not connect to service.");
}
throw;
}
}
private static async Task<T> Deserialize<T>(HttpContent responseContent) where T : new()
{
try
{
var responseContentString = await responseContent.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseContentString);
}
catch (Exception exception)
{
if (exception is TaskCanceledException || exception is JsonException)
{
throw new Exception("Could not deserialize response content.", exception);
}
throw;
}
}
And Add an App settings class
public class AppSettings : IAppSettings
{
public string Server => "server url";
public string ServerEndPoint => "End point";
public string Token => "Token If you Have any";
}
Then Call Like this
public class Servicecall
{
private readonly IRestClient _restClient;
private readonly IAppSettings _appSettings;
public PatientService(IRestClient restClient, IAppSettings appSettings)
{
_restClient = restClient;
_appSettings = appSettings;
}
public async Task<IList<PatientViewModel>> GetPatients()
{
var url = _appSettings.Server + _appSettings.EndPoint ;
var token = _appSettings.Token;
return GetPatientList(await _restClient.GetAsync<List<ListModelClass>>(url, token));
}
public IList<Model> GetPatientList(IList<ListModelClass> List)
{
return List.Select(p => new Model(p)).ToList();
}
}
This way You can Call deferent services without typing a lot of boilercodes
This way You can Call Services with real ease

Sinch java error

i am using sinch from java, i recently reput credit to the account, and now when i try to send message i get succes message, but the sms isn't send. Following the link https://messagingapi.sinch.com/v1/sms/162393899 i get this
{"errorCode":40107,"message":"Invalid authorization key:
vivi******#gmail.com","reference":"BA:vivi******#gmail.com_GtIfKPDMJEKL4VJWR0kkJQ"}
the code
try {
String phoneNumber = "+40732******";
String appKey = "*****";
String appSecret = "****";
String message = "Test";
URL url = new URL("https://messagingapi.sinch.com/v1/sms/" + phoneNumber);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String userCredentials = "application\\" + appKey + ":" + appSecret;
byte[] encoded = Base64.encodeBase64(userCredentials.getBytes());
String basicAuth = "Basic " + new String(encoded);
connection.setRequestProperty("Authorization", basicAuth);
String postData = "{\"Message\":\"" + message + "\"}";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}

Why am I getting a "NotSupportedException" with this code?

I am trying to call a Web API method from a handheld device (Compact Framework) with this code:
// "fullFilePath" is a value such as "\Program Files\Bla\abc.xml"
// "uri" is something like "http://localhost:28642/api/ControllerName/PostArgsAndXMLFile?serialNum=8675309&siteNum=42"
SendXMLFile(fullFilePath, uri, 500);
. . .
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
uri = uri.Replace('\\', '/');
if (!uri.StartsWith("/"))
{
uri = "/" + uri;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded"; // not "text/xml" correct?
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
Somewhere in SendXMLFile(), it is failing with "NotSupportedException" though... As it's running on a handheld device, I can't put a breakpoint in it and step through it; I could sprinkle a bunch of debug statements throughout (MessageBox.Show()), but I'd rather not do that.
The server code never even reaches the breakpoint I put on the "XDocument doc =" line below:
[Route("api/ControllerName/PostArgsAndXMLFile")]
public void PostArgsAndFile([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
XDocument doc = XDocument.Parse(stringifiedXML);
Is it that the Compact framework can't call a (RESTful) Web API method for some reason? Obviously, the client (handheld/Compact Framework) compiles and runs, it just refuses to actually follow through with the runtime realities of it all.
Does my code require a small alteration for it to fit, or do I need to take a completely different tack?
Web API is not going to be able to handle your body content. You declared it as application/x-form-urlencoded, but it is actually XML formatted and your method signature is expecting it to be a XMLDataContract serialized string.
Instead of using the parameter stringifiedXML, instead, just read the body inside your method..
[Route("api/ControllerName/PostArgsAndXMLFile")]
public async void PostArgsAndFile(string serialNum, string siteNum)
{
XDocument doc = XDocument.Parse(await Request.Content.ReadAsStringAsync());
}
Or event better, use a stream directly.
[Route("api/ControllerName/PostArgsAndXMLFile")]
public async void PostArgsAndFile(string serialNum, string siteNum)
{
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
}
This way, you can put the ContentType on the client back to application/xml as it should be.
Using Darrel's code on the server side (I'm using the second one, the Stream), this works on the Client side:
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ContentType = "application/xml";
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
Which can be called like so:
private void buttonNose_Click(object sender, EventArgs e)
{
String fullFilePath = #"C:\McMurtry\LonesomeDove.XML";
String uri = #"http://localhost:21608/api/inventory/sendxml/ff/gg/42";
SendXMLFile(fullFilePath, uri, 500);
}

Google GeoLocation API returns different results for the same wifi access point

We are using Google's geolocation API to get the latlong for the wifi access points. We are seeing inconsistent results. Google's API returns different latlong on different boxes. When I test on my development box, I get the latlong which points to a location in US. When I test the same on the amazon ec2 box, I get the latlong which points to a location in Japan. Has anybody else experienced the same with Google's GeoLocation API?
Below is the code and the response strings from both hosts. JDK and JSON jar version is same on both the hosts.
public void testWifiIdMappingApi() {
String apiUrl = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxxxxxxxxxxxxxxxxxxxxxx";
InputStream inputStream = null;
HttpsURLConnection con = null;
DataOutputStream wr = null;
try {
URL url = new URL(apiUrl);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
JSONObject obj = new JSONObject();
JSONArray wifiAry = new JSONArray();
JSONObject wifiObj = new JSONObject();
wifiObj.put("macAddress", "6c:f3:7f:4b:37:74");
wifiObj.put("signalStrength", 60);
wifiAry.add(wifiObj);
wifiObj = new JSONObject();
wifiObj.put("macAddress", "6c:f3:7f:4b:37:75");
wifiObj.put("signalStrength", 60);
wifiAry.add(wifiObj);
obj.put("wifiAccessPoints", wifiAry);
System.out.println(obj.toString());
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(obj.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
inputStream = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
final char[] buffer = new char[4096];
StringBuilder response = new StringBuilder();
Reader r = new InputStreamReader(inputStream, "UTF-8");
int read;
do {
read = r.read(buffer, 0, buffer.length);
if (read > 0) {
response.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(new java.util.Date() + " - "
+ response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (wr != null)
wr.close();
if (con != null)
con.disconnect();
} catch (Exception e) {
}
}
}
Input JSON String
{"wifiAccessPoints":[{"signalStrength":60,"macAddress":"6c:f3:7f:4b:37:74"},
{"signalStrength":60,"macAddress":"6c:f3:7f:4b:37:75"}]}
Response on the amazon ec2 host
{
"location": {
"lat": 40.603124,
"lng": 140.463922
},
"accuracy": 122000.0
}
Response on my development box (windows 7)
{
"location": {
"lat": 37.593392,
"lng": -122.04383
},
"accuracy": 22000.0
}
You might want to pass the considerIp field as False in your POST body. This would be what Google determines to be your location when the wifi routers aren't doing their job.

Customize toast in asyntask in android

I just wanna ask if it is possible to use my customize toast in onPostExecute of my Asyntask in android. If yes then how? I tried to put it on the onPostExecute but I got a lot red lines. Here is my code for my customize toast:
Typeface tfR= Typeface.createFromAsset(getAssets(), "Gothic_Regular.TTF");
LayoutInflater inflater = getLayoutInflater();
View layouttoast = inflater.inflate(R.layout.toast_bg, (ViewGroup)findViewById(R.id.toastAttribute));
TextView msg = ((TextView) layouttoast.findViewById(R.id.txt_toast));
msg.setTypeface(tfR);
msg.setText(toast_msg);
msg.setTextSize(TypedValue.COMPLEX_UNIT_PX,16);
Toast mytoast = new Toast(getBaseContext());
mytoast.setView(layouttoast);
mytoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
mytoast.setDuration(Toast.LENGTH_SHORT);
mytoast.show();
Then I want to put it here:
public class DoPost extends AsyncTask<String, Void, Boolean>
{
Exception exception = null;
Context mContext = null;
. . . . .
public DoPost(Context context, String username, String password,
String reportcode, String remarks, String date, String province,
String infotype, String competitor, ArrayList<String> brands,
ArrayList<String> segments)
{
mContext = context;
. . . .
databaseHandler = new DatabaseHandler(context);
if (databaseHandler != null)
{
databaseHandler.close();
databaseHandler.createDB();
}
}
protected void onPreExecute()
{
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Uploading attachment details....");
progressDialog.show();
progressDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... arg0)
{
try {
JSONObject jObject = new JSONObject();
Log.d("DoPost Constants.FILE_URI", Constants.FILE_URI.toString());
Log.d("DoPost create SELECTEDFILE URI", SelectedFiles.listFileUri.toString());
Log.d("DoPost create SELECTEDFILE FILENAME", SelectedFiles.listFileName.toString());
// String filename = "Chapt-19.pdf";
String filename = "";
try {
JSONArray jArraySubrands = new JSONArray();
JSONArray jArrayConsumerSegments = new JSONArray();
JSONArray jArrayReportUpload = new JSONArray();
for (int i = 0; i < Constants.SHARED_PREFERENCES_SUBBRANDS.size(); i++)
{
JSONObject brand = new JSONObject();
brand.put("Id", _brands.get(i));
jArraySubrands.put(brand);
}
for (int j = 0; j < Constants.SHARED_PREFERENCES_SEGMENTS.size(); j++)
{
JSONObject consumerSegments = new JSONObject();
consumerSegments.put("Id", _segments.get(j));
jArrayConsumerSegments.put(consumerSegments);
}
for (int i = 0; i < Constants.ARRAYLIST_FILENAME.size(); i++)
{
JSONObject jObjectReportUpload = new JSONObject();
filename = Constants.ARRAYLIST_FILENAME.get(i);
jObjectReportUpload.put("ReportUploadId", 0);
jObjectReportUpload.put("Filename", filename);
jObjectReportUpload.put("TempFilename", filename);
jObjectReportUpload.put("Description", "Image Testing");
jObjectReportUpload.put("ReportUploadTypeId", 1);
jObjectReportUpload.put("ReportId", 0);
jArrayReportUpload.put(jObjectReportUpload);
Log.d("filename: ", filename);
}
jObject.put("ReportId", 0);
jObject.put("ReportCode", _code);
jObject.put("Title", "Mobile Developer");
jObject.put("Remarks", _remarks);
jObject.put("DateObserved", _date);
jObject.put("ProvinceId", _province);
jObject.put("InformationTypeId", _infotype);
jObject.put("ReportTypeId", 1);
jObject.put("IsCompetitor", _competitor);
jObject.put("SubBrands", jArraySubrands);
jObject.put("ConsumerSegments", jArrayConsumerSegments);
jObject.put("ReportUploads", jArrayReportUpload);
} catch (Exception e)
{
e.printStackTrace();
}
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpPost httpPost = new HttpPost("http://phsjghhghghulchghg4.hgh.com:1214/api/reports");
HttpClient httpclient = new DefaultHttpClient(httpParameters);
httpPost.addHeader("Authorization","Basic "+ Base64.encodeToString((_username + ":" + _password).getBytes(),Base64.NO_WRAP));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes(HTTP.UTF_8)));
String response = httpclient.execute(httpPost).toString();
Log.i("response: ", response);
Log.i("JSON", jObject.toString());
} catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e("Header","ClientProtocolException in callWebService(). "+ e.getMessage());
error = String.valueOf(e);
return false;
}
catch (IOException e)
{
e.printStackTrace();
Log.e("Header","IOException in callWebService(). " + e.getMessage());
error = String.valueOf(e);
return false;
}
return true;
}
protected void onPostExecute(Boolean valid)
{
progressDialog.dismiss();
Log.d("RESULT", String.valueOf(valid));
if(valid){
//Customzize toast here.
new DoPost(mContext,_username, _password, _code, _remarks, _date, _province, _infotype,_competitor,_brands, _segments).execute();
}else{
//Customzize toast here.
}
}
I think I've found out what's going on. Your scope is wrong. currently your code is running in AsyncTask, not Activity! That's why you cannot use getAssets, getLayoutInflater, findViewById, getBaseContext. Create your AsyncTask in your xxxActivity. And use Your xxxActivity.this.findViewById, and so on.

Resources