How to pass variable String from this situation? - android

I have this three different projects. Project1(isLibrary), Project2 and Project3 set the Project1 as Library. Now, my problem is that Im sending a request to the server but I cant get to pass the String from my Project2 to Project1. Project 3 will also use Project1 and will send a different request. Any Ideas?
In my Project1, I have an TestAsyncTask Class.
public class TestAsyncTask extends AsyncTask<String, Void, String> {
TextView textView1[], textView2[];
TextView textView;
private LinearLayout linearLayout;
//It's just a sample, not a valid soap header
String string1 = "http://soapactionheaderline"; //Provides the value for the SOAPAction header line.
//It's just a sample, not valid server
String string2 = "https://server.com"; //This is the target URL/Server that we will be connecting to.
Context context;
int resultInt;
//Constructor
public TestAsyncTask(Context cContext){
context = cContext; //Pass Context to constructor
}
//Getter for LinearLayout.
public LinearLayout getLinearLayout(){
return linearLayout;
}
//Setter for LinearLayout.
public void setLinearLayout(LinearLayout lLinearLayout){
this.linearLayout = lLinearLayout;
}
//Getter for String.
public String getString(){
return string2;
}
//Setter for String.
public void setString(String sString){
this.string2 = sString;
}
#Override
protected String doInBackground(String... aServerConnectionString) {
String resultString = null;
try {
// Uses URL and HttpURLConnection for server connection.
URL uRL = new URL(string2);
HttpURLConnection httpURLConnection = (HttpURLConnection) uRL.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setChunkedStreamingMode(0);
//.addRequestProperty - Adds the given property to the request SOAPAction header
httpURLConnection.addRequestProperty("SOAPAction", string1);
httpURLConnection.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpURLConnection.addRequestProperty("Content-Length", "" + "THIS IS WHERE I NEED TO PASS THE STRING VARIABLE FROM MY Project2".length());
httpURLConnection.setRequestMethod(HttpPost.METHOD_NAME);
// Using OutputStream and Writer to send a request to the server.
OutputStream outputStream = httpURLConnection.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.write("THIS IS WHERE I NEED TO PASS THE STRING VARIABLE FROM MY Project2");
writer.flush();
writer.close();
// Using InputStream to get the response of the request from the server.
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);
int aint = httpURLConnection.getResponseCode();
while ((aint = bufferedReader.read()) != -1) {
byteArrayBuffer.append(aint); //Read bytes to the Buffer until there is nothing more to read.
}
resultString = new String(byteArrayBuffer.toByteArray());
// Use SAXParser(Simple API for XML) to handle the parsing of XML(Response).
SAXParserFactory sAXParserFactory = SAXParserFactory.newInstance();
SAXParser sAXParser = sAXParserFactory.newSAXParser();
XMLReader xMLReader = sAXParser.getXMLReader();
// Create handler to handle XML Tags
TestXMLHandler xMLHandler = new TestXMLHandler();
xMLReader.setContentHandler(xMLHandler);
InputSource inputSource = new InputSource(new StringReader(resultString));
xMLReader.parse(inputSource);
} catch (Exception exception) {
resultString = exception.getMessage(); in the created String and display it to UI.
}
return resultString;
}
//This step is the return-value from doInBackground.
protected void onPostExecute(String aReturnValueString) {
// Create an object/instance of GBData Class and get results from GBXMLHandler.
TestGetterSetter data = TestXMLHandler.testdata;
int sizeInt = data.getOperatorName().size();
textView1 = new TextView[sizeInt];
textView2 = new TextView[sizeInt];
//The for statement provides a compact way to iterate over a range of values.
for (resultInt = 0; resultInt < sizeInt; resultInt++) {
textView1[resultInt] = new TextView(context.getApplicationContext());
textView1[resultInt].setText("OperatorName = " + data.getOperatorName().get(resultInt));
linearLayout.addView(textView1[resultInt]);
textView2[resultInt] = new TextView(context.getApplicationContext());
textView2[resultInt].setText("type = " + data.getType().get(resultInt));
linearLayout.addView(textView2[resultInt]);
}
}
}
In my Project2, I have TestActivity1 class which extends the activity, it's the UI
public class TestActivity1 extends Activity{
TestAsyncTask asyncTask = new TestAsyncTask(this);
//This is just a sample soap
String requestString = "<soapenv---------------------------------------------------------------->";
#Override
public void onCreate(Bundle aBundle) {
super.onCreate(aBundle);
asyncTask.execute(asyncTask.getString());
LinearLayout linearLayout = asyncTask.getLinearLayout();
linearLayout = new LinearLayout(this);
linearLayout.setOrientation(1);
asyncTask.setLinearLayout(linearLayout);
// Set the ContentView to layout for display
setContentView(linearLayout);
}
}

I dont really know what you are trying to achieve in your code. Anyhow, come to the problem, I think you are already passing a string value to your AsyncTask. All you need to do is to make use of it in its doInBackground method. For example:
protected String doInBackground(String... aServerConnectionString) {
String yourValue = aServerConnectionString[0];
...
...
...
writer.write(yourValue); //pass your value to writer
...
...
...
}
P.S. I believe your code will not run as it doesn't seem logical at certain places

Firstly, I think its very important that you read up on AsyncTask because your implementation does not correctly utilize how it is designed to work. You've caused yourself more issues if I'm honest :)
To solve your problem based on your current implementation its important you see how the execute() function works in combination with doInBackground().
Execute takes a string array for its arguments, so in Project2 you could do something like this:
String url = "";
String request = "";
asyncTask.execute(url, request);
Then in your ASyncTask, the doInBackground method receives the arguments you used for the execute method. As your passing the values you require between classes, your doInBackground method could look something like this:
#Override
protected String doInBackground(String... aServerConnectionString) {
String url, request;
if (aServerConnectionString[0] != null) {
url = aServerConnectionString[0];
}
if (aServerConnectionString[1] != null) {
request = aServerConnectionString[1];
}
This way your ASyncTask can remove all its string related stuff as it will rely on Project2/3 to pass through the strings.

keep the strings in strings.xml in your library projects as well as target projects..always top priority for resources is given to targeted project..so you can reference that same id and send the staring to server without any issues

Related

Best way to request data from server

I need to fetch some data from my server in order to make my app work. In order to do that, I will be using POST. As far as I know, I have to request that data in a thread which can not be the main thread. I am finding it a little bit difficult to put the data I am receiving in a variable defined in the UI thread. So, my question is, which is the best way to do it?
Is it correct to set the value of a variable defined, for example, in my main activity, with a setter called inside an AsyncTask? Or is there a better option than this?
Thread nt = new Thread(){
#Override
public void run(){
try{
//get data with POST and then something like main.setValue(data);
}catch(Exception e){
e.printStackTrace();
}
}
};
nt.start();
I have read that I may use Interfaces in order to archive that, but it is a concept that I do not understand very well yet. I would like to directly use a method which returns the data, but as far as I know, it is not possible.
EDIT: new code according to NoChinDeluxe answer:
public class LoginHandler {
public static class Login extends AsyncTask<String, String, Integer> {
LoginCallback listener;
#Override
protected Integer doInBackground(String... params) {
URL url;
postDataParams.put("name", params[0]);
HashMap<String, String> postDataParams = new HashMap<String, String>();
postDataParams.put("password", params[1]);
try {
url = new URL("http://mashiron.xyz/_03z/gmpia/proc.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(HttpHandler.getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
System.out.println("Respuesta: "+conn.getResponseCode());
return conn.getResponseCode();
} catch (Exception e) {
e.printStackTrace();
return 404;
}
}
protected void onPostExecute(int result){
System.out.println("Respuesta 2: "+result);
listener.onResultReceived(result);
}
}
public interface LoginCallback {
void onResultReceived(int result);
}
}
EDIT: added exception for NoChinDeluxe:
03-24 17:38:09.072 13312-13312/com.pitazzo.geomoments E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pitazzo.geomoments, PID: 13312
java.lang.NullPointerException: Attempt to invoke interface method 'void com.pitazzo.geomoments.Handlers.LoginHandler$LoginCallback.onResultReceived(int)' on a null object reference
at com.pitazzo.geomoments.Handlers.LoginHandler$Login.onPostExecute(LoginHandler.java:65)
at com.pitazzo.geomoments.Handlers.LoginHandler$Login.onPostExecute(LoginHandler.java:17)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5300)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
EDIT: more code for NoChainDeluxe
public class LoginActivity extends AppCompatActivity implements LoginHandler.LoginCallback{
EditText name;
EditText password;
Button login;
int code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
/*
if(logueado){
}
*/
name = (EditText) findViewById(R.id.loginuser);
password = (EditText) findViewById(R.id.loginpassword);
login = (Button) findViewById(R.id.loginlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String params[] = {name.getText().toString(), password.getText().toString()};
System.out.println("Params: "+params.toString());
new LoginHandler.Login().execute(params);
System.out.println("Respuesta 4: "+code);
if(code == 200){
Toast toast1 =
Toast.makeText(getApplicationContext(),
"Iniciado sesión", Toast.LENGTH_SHORT);
toast1.show();
}else{
Toast toast1 =
Toast.makeText(getApplicationContext(),
"Nombre de usuario y/o contraseña incorrectos: "+code, Toast.LENGTH_SHORT);
toast1.show();
}
}
});
}
public void onResultReceived(int resultado) {
code = resultado;
System.out.println("Respuesta 3: "+code);
}
}
The best way to achieve this is to use an HttpURLConnection to make your web calls inside an AsyncTask and then pass the result back to your calling Activity through a callback. Here's some code to help you get started:
The first thing you should understand is how to properly use a callback with an AsyncTask. Here is an example AsyncTask that defines a callback interface:
import android.os.AsyncTask;
public class TestTask extends AsyncTask<String, Void, String> {
TestTaskCallback listener;
public TestTask(TestTaskCallback listener) {
this.listener = listener;
}
protected String doInBackground(String... args) {
String input = args[0];
String output = "simulated return value";
return output;
}
protected void onPostExecute(String result) {
listener.onResultReceived(result);
}
public interface TestTaskCallback {
void onResultReceived(String result);
}
}
The way this works is, you define a public interface that you then implement in your Activity. This acts as a "listener" that is waiting for any data that is sent through to it. We define the interface TestTaskCallback because we are going to be sending our data from our AsyncTask to our calling Activity.
Then in the Activity, we need to implement this interface, and pass in a reference to our implementation to the task when we create it. That way, when the task fires, it knows where to send the result, which is back to our Activity. An example implementation might look like this:
public class TestActivity extends AppCompatActivity implements TestTask.TestTaskCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
new TestTask(this).execute("Some input");
}
public void onResultReceived(String result) {
Log.d("TEST TASK RESULT", result);
}
}
So our Activity implements the interface that we defined inside our AsyncTask, and notice that our AsyncTask takes the reference to this implementation (passed in through the constructor) and sends data to it in the onPostExecute() method. This will allow your result to be sent to the main UI thread so that you can update your Activity appropriately.
The only thing left is to actually make the web calls. I would recommend using an HttpURLConnection for this. You would put this code inside the doInBackground() method of your AsyncTask.
I'll show you an example web service call I have set up. This shows how to make a web service call to retrieve a JSON response. It looks something like this:
//The JSON we will get back as a response from the server
JSONObject jsonResponse = null;
//Http connections and data streams
URL url;
HttpURLConnection httpURLConnection = null;
OutputStreamWriter outputStreamWriter = null;
try {
//open connection to the server
url = new URL("your_url_to_web_service");
httpURLConnection = (HttpURLConnection) url.openConnection();
//set request properties
httpURLConnection.setDoOutput(true); //defaults request method to POST
httpURLConnection.setDoInput(true); //allow input to this HttpURLConnection
httpURLConnection.setRequestProperty("Content-Type", "application/json"); //header params
httpURLConnection.setRequestProperty("Accept", "application/json"); //header params
httpURLConnection.setFixedLengthStreamingMode(jsonToSend.toString().getBytes().length); //header param "content-length"
//open output stream and POST our JSON data to server
outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
outputStreamWriter.write(jsonToSend.toString());
outputStreamWriter.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination
//prepare input buffer and get the http response from server
StringBuilder stringBuilder = new StringBuilder();
int responseCode = httpURLConnection.getResponseCode();
//Check to make sure we got a valid status response from the server,
//then get the server JSON response if we did.
if(responseCode == HttpURLConnection.HTTP_OK) {
//read in each line of the response to the input buffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close(); //close out the input stream
try {
//Copy the JSON response to a local JSONObject
jsonResponse = new JSONObject(stringBuilder.toString());
} catch (JSONException je) {
je.printStackTrace();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if(httpURLConnection != null) {
httpURLConnection.disconnect(); //close out our http connection
}
if(outputStreamWriter != null) {
try {
outputStreamWriter.close(); //close our output stream
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
//Return the JSON response from the server.
return jsonResponse;
This is pretty much all you need to know to do exactly what it is you are trying to do. I realize this is a ton of info to throw at you all at once, but if you take your time and work through it piece by piece, you'll find it's not too difficult after all and is actually a VERY powerful tool that you'll use all the time programming Android apps!
Hope this helps. Feel free to ask questions for any parts you don't fully understand yet!
Better use an AsyncTask to propagate the data to your UI thread, just use onPostExecute() to set the result on your activity's class.
The error you are getting is because of accessing UI elements from background thread.
AsyncTask is a Thread pool based api that runs your task in a seperate thread
,but your UI part runs in a thread usually called UI thread,
to update any changes to ui put the logic onPostExecute()
NOTE: Use okhttp to get consistent http api, it also supports http2.Their github wiki is very helpful, check here for examples.

Android - HttpGet with parameters

I'm doing a REST API in Android with my GET method using Slim framework. I didn't have any problem about retrieving all the values of a table, for example, cars.
The problem comes when I try to access to the name of a Car by it's id. I have the method on Slim framework created and it works perfectly:
GET METHOD
$app->get("/cars/:idCar",function($idCar) use($app)
{
try{
$connection = getConnection();
$dbh = $connection->prepare("SELECT name FROM cars WHERE idCar = ?");
$dbh->bindParam(1,$idCar);
$dbh->execute();
$car = $dbh->fetchObject();
$connection = null;
header("HTTP/1.1 200");
header("Content-Type:application/json; charset=utf-8");
echo json_encode($car,JSON_UNESCAPED_UNICODE );
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
});
And if I put the url on my browser:
http://IP of my computer/project/cars/1
it returns to me:
{"name":"Car1"}
So in the GET method there isn't any problem.
The problem it's when I try to execute HttpGet, because I get stuck of what I have to do. What I have right now:
HttpGet method inside the AsyncTask
class FindCar extends AsyncTask<Integer, Integer, Void> {
protected void onPreExecute(){
}
protected Void doInBackground(Integer... idCar) {
String url = "http://IP of my computer/project/cars/" + idCar[0].intValue();
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
method.setHeader("content-type", "application/json");
try {
HttpResponse resp = httpClient.execute(method);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
for (int i = 0; i < respJSON.length(); i++) {
JSONObject obj = respJSON.getJSONObject(i);
String name = obj.getString("name");
}
} catch (Exception ex) {
}
return null;
}
protected void onProgressUpdate(){
}
protected void onPostExecute(){
}
}
And it gives to me some questions:
Should I create a JSONArray just for one attribute?
What is the best practice to get the name in my AsyncTask?
After getting the name by the id of my Car that I pass to my AsyncTask, how can I return it out of the AsyncTask?
Should I create a NameValuePair to set the value of my id?
Thanks in advance!
You do not need the JSONArray (since there is no square brackets in the responce)! Please try instead of
JSONArray respJSON = new JSONArray(respStr);
for (int i = 0; i < respJSON.length(); i++) {
JSONObject obj = respJSON.getJSONObject(i);
String name = obj.getString("name");
}
the following:
JSONObject respJSON = new JSONObject(respStr);
String name = respJSON.getString("name");
As for returning the result - return it from doInBackground to onPostExecute method then store it somewhere (you can show it on the screen since onPostExecute runs on UI thread). To return value from doInBackground change last type param of AsyncTask<Integer, Integer, Void> from Void to other type.
Best practice is do not use AsyncTask and do not parse JSON manually (when it is possible) :) Retrofit would be a good choice
i use something like this:
public function getCarsById($id) {
$stmt = $this->conn->prepare("SELECT name FROM cars WHERE idCar = ?");
$stmt->bind_param("s", $id);
if ($stmt->execute()) {
$car= $stmt->get_result()->fetch_assoc();
$stmt->close();
return $car;
} else {
return NULL;
}
}
Regarding the java class, i use Retrofi that is incredible fast and can be used Synchronous and Asynchronous.

AsyncTask sanity check

I've been going over various Asynctask tutorials and examples, but I'm still a little confused. If I want to issue 3 web requests and return their response
like:
//example
String[] response = new String[3];
response[0] = webrequest("http://www.google.com"); //simple HTTP GET request
response[1] = webrequest("http://www.bing.com"); //simple HTTP GET request
response[2] = webrequest("http://www.aj.com"); //simple HTTP GET request
//sample results from request
response[0] = "blah";
response[1] = "arg";
response[2] = "meh";
To do this with an AsyncTask, would I need to implement 3 different ATs? Should I be using something else?
String[] response = new String[3];
webCreate sample = new webCreate();
try{
response[0] = sample.execute("http://www.google.com").get().toString();
response[1] = sample.execute("http://www.google.com").get().toString();
response[2] = sample.execute("http://www.google.com").get().toString();
}
catch (Exception sampleMsg)
{}
public class webCreate extends AsyncTask<String, String, String> {
}
protected String doInBackground(String... params) {
// String url=params[0];
String webRequestResponse = null; //the
// web request
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
return reponse;
}
I know I could access the response data by using .get(), but then my "Async" would become "sync" lol. I feel like I should be using something other than AsyncTask, but I have no idea what that is. Please help.
Your approach is okay, from doInBackground of your AsyncTask call a function that initiates the webrequests and wait for the result with . get(). Due to the fact, that the request are then, not running on the mainUi and blocking it, I see no problem in doing so.

Write JSON response to a text view

I am authenticating an external system via a REST API. The http authentication request is of the Basic Authorization form. The response is in JSON format.
I am running this code under an AsyncTask.
url The GET url of the API.
credentials is the authentication credentials. It is a string.
response is the text view.
getmessage is a string variable.
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic" + Base64.encode(credentials.getBytes(), Base64.DEFAULT ));
// I am reading the response here,
InputStreamReader in = new InputStreamReader(connection.getInputStream());
buf = new BufferedReader(in);
getmessage = buf.readLine();
// After making the request, I am updating the response to a text view on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
response.setText(getmessage);
}
});
I am unable to write the whole JSON data to the text view. I know that buf.readline returns the response till the end of a line. Right now I am only getting a part of the JSON response, "Not Authenticated:", but I need the whole response.
How do I update the whole JSON response to the text view (response)? If I loop the data using buf.readline in a loop then where can I use it? In which thread?
If there is anything unusual in my code. Please let me know.
I would suggest you to go trough AsyncTask
private class GetDataFromUrl extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic" + Base64.encode(credentials.getBytes(), Base64.DEFAULT ));
InputStreamReader in = new InputStreamReader(connection.getInputStream());
buf = new BufferedReader(in);
StringBuilder sb = new StringBuilder();
while ((getmessage = buf.readLine()) != null) {
sb.append(getmessage);
}
getmessage = sb.toString();
return getmessage;
}
protected void onPostExecute(String result) {
// Result will be available here (this runs on main thread)
// Show result in text view here.
response.setText(result);
}
}
To understand better, as you call AsyncTask, doInBackground runs on the new thread created. Where the network call in placed and data is parsed. Now, we need to access the data on the main thread to update the TextView so override onPostExecute inside AsyncTask that is taking result as a parameter, from doInBackground. Also if you notice..
private class GetDataFromUrl extends AsyncTask<URL, Integer, String>
Here URL is the type we are passing to our AsyncTask for doInBackground
String is what we passing from doInBackground to onPostExecute
and Integer is used to show progress for another method you can override i.e onProgressUpdate .. You can read more in the documentation liked above. Hope it was helpful.
You're only reading the first line of the response with readLine(). Call that in a loop until all lines are read, and append each new line to the previous.
If i understood correcly, you are trying to read all response data line by line. Can you try the following?
#Override
protected String doInBackGround(...){
. . .
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String response = sb.toString();
return response;
}
#Override
protected void onPostExecute(String response){
Textview tv = your_textview;
your_textview.settext(whatever_part_you_get_from_response);
}
Hope this helps.
Try this:
StringBuilder sb = new StringBuilder();
while ((getmessage = buf.readLine()) != null) {
sb.append(getmessage);
}
getmessage = sb.toString();
EDITED
In your code:
getmessage = buf.readLine();
in variable getmessage reads only first line of JSON. You need to read all lines and concatenate it. How to know did you read all lines or not?
Here is what documentation says about it:
public String readLine()
throws IOException
Returns:
A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached
As you can see, you should invoke this method, save result of it into variable, and check, if variable is not null, then you have read line of JSON. If variable is null, then you have read all JSON into variable and you have completely JSON String.
StringBuilder used to avoid creating unnecessary objects, read more about it here

When running 2 http AsyncTasks in parallel sometimes results are exchanged

I have a strange problem in my application.
I have an activity that fetches 2 or 3 things in parallel using AsyncTasks
When I simply do the following
new getMessages().execute("someID");
new getNotifications().execute("someID");
and the both AsyncTasks has code as follows:
(Both of them are identical except that the URL requested by each method is different).
Notice: I modified this code a little bit just to remove any unneeded extras like extra parameters sent in the http request
// in the other Async task "notifications" is changed with "messages"
public class getNotifications extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
Integer verified = 0;
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... args) {
// getRequestsCount just perfomrs http request and grabs JSON data
String result = getRequestsCount(args[0] , "notifications");
return result;
}
protected void onPostExecute(String result) {
// This is just a method that handles the result
// When I log result I found that results are exchanged.
displayResults(result);
}
}
public String getRequestsCount(String id, String type){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(GlobalSettings.apiURL + "/getcount/" + type );
Log.i("will contact",GlobalSettings.apiURL + "/getcount/" + type);
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));
String responseMessage = reader.readLine().toString().trim();
// Response is always 1 line of JSON data
Log.i("Response for "+type,responseMessage);
return responseMessage;
}
Now my problem is that sometimes results are exchanged.
i.e. getMessages recives the JSON data requested from getNotifications
and vice versa.

Categories

Resources