I am trying to send a POST request using Plivo (VoIP server) to send a SMS to my cell phone, but I just receive BAD REQUEST (Request Code 400).
The error I received is "error": "invalid json data sent in raw POST"
I can't find where it's wrong.
Can someone help me?
final AsyncTask<String, Void, Boolean> request = new AsyncTask<String, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... strings) {
Boolean retorno = true;
HttpsURLConnection request = null;
try {
request = (HttpsURLConnection) finalUrl.openConnection();
System.out.println("Define POST");
request.setRequestMethod("POST");
request.setUseCaches(false);
request.setDoOutput(true);
System.out.println("Define propriedades");
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
request.setRequestProperty("Accept-Charset", "UTF-8");
request.setRequestProperty("charset", "UTF-8");
System.out.println("Define autenticação");
String autenticacao = authID + ":" + authToken;
String basic = "Basic " + new String(Base64.encode(autenticacao.getBytes(), Base64.NO_WRAP));
request.setRequestProperty("Authorization", basic);
System.out.println("Define parâmetros");
JSONObject params = new JSONObject();
params.put("dst", numeroDestino);
params.put("src", numeroOrigem);
params.put("text", body);
System.out.println("Faz conexão e requisição");
request.connect();
OutputStreamWriter postParaEnvio = new OutputStreamWriter(request.getOutputStream());
postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8"));
postParaEnvio.flush();
postParaEnvio.close();
int codigoStatus = request.getResponseCode();
for (Map.Entry<String, List<String>> header : request.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
if (codigoStatus == 202) {
System.out.println("OK");
} else {
System.out.println("Falha");
System.out.println(codigoStatus);
retorno = false;
}
} catch (IOException e) {
System.out.println("Falha Exception");
e.printStackTrace();
retorno = false;
} catch (JSONException e) {
e.printStackTrace();
retorno = false;
} finally {
request.disconnect();
}
return retorno;
}
#Override
protected void onPostExecute(Boolean result) {
indicadorDeAtividade.dismiss();
if(result) {
} else {
mostrarErro(0, R.string.erroEnviarCodigo);
}
}
}.execute();
SOLVED
When sending Json object, it must be passed to String but it cannot be coded.
Modifing the line postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8")); to postParaEnvio.write(params.toString()); solved the problem.
I Think this may help you.
By the way,
My Dependencies : gradle->
compile 'com.android.support:appcompat-v7:23.4.0'
class BackGround extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String email = params[2];
String phone=params[3];
String data="";
int tmp;
try {
URL url = new URL("http://domain.com/yourFile.php");
String urlParams = "name="+name+"&password="+password+"&email="+email+"&phone="+phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("")){
s="Data Saved! Success...";
}
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
}
}
Related
I'm using Asynctask to pass the parameters of API. The Asynctask executing but the String Response in Asynctask PostExecute giving me a null for a device with SDK 23 and below. But when the device is equal or higher to SDK24(Nougat), it works perfectly and the data are being sent to the API however when the SDK is 23 and lower data are not being sent to API. Does anyone encounter this problem? Please enlighten me what I miss in my code or I do wrong code. Massive thank you.
private class sendToServerOfficial extends AsyncTask<String,Void,String> {
int statusCodeone;
String convert_txt_et_username = et_username.getText().toString();
String convert_txt_content = et_content.getText().toString();
#Override
protected String doInBackground(String... strings) {
try {
urlURL = new URL("http://www.testingsite.com/api/sendServer?/ip="+getIPAddress+"&phone_num="+getMobilePhoneNumber+"&user_text="+convert_txt_et_username+"&content_text="+convert_txt_content);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlURL.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","UTF-8");
httpURLConnection.connect();
statusCodeone = httpURLConnection.getResponseCode();
if (statusCodeone == 200) {
InputStream it = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
buff.close();
read.close();
return dta.toString();
}
}
catch (ProtocolException e) { e.printStackTrace(); }
catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return null;
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(MainActivity.this, response + "Form is submitted already" + urlURL, Toast.LENGTH_LONG).show();
txt_inputURL.setEnabled(true);
btnClick.setClickable(true);
txt_inputURL.getText().clear();
}
}
I am a newbie in android and I've been working around pagination with recyclercview. I am receiving my data from a server(running php) and returning it in a JSON format which brings the data in bunches like 1-10, 11-20... so on. I call notifyDataSetChanged with this. But the problem is recyclerview scrolls back to the top when retrieving more data instead of retaining the current position. How do I go about this?
When scrollbar gets to the bottom, it triggers the asynctask
AsynTask:
public class LoadRecharge extends AsyncTask<String, String, String> {
private boolean socketTimeout = false;
Context context;
public static final String TAG = "custom_message";
public AsyncResponse delegate = null;
private String server_url = "https://blockgator.com/mobile/endless.php";
public LoadRecharge(Context ctxt, AsyncResponse asyncResponse) {
delegate = asyncResponse;
context = ctxt;
}
#Override
protected String doInBackground(String... params) {
if (connectGoogle()) {
String post_data = "";
try {
URL url = new URL(server_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
post_data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
Log.e(TAG, "error: " + e.getMessage());
}
} else {
this.socketTimeout = true;
}
return null;
}
#Override
protected void onPreExecute() {
arr.add(null);
scrollAdapter.notifyItemInserted(arr.size() - 1);
}
#Override
protected void onPostExecute(String result) {
arr.remove(arr.size() - 1);
scrollAdapter.notifyItemRemoved(arr.size());
if (this.socketTimeout) {
Toast.makeText(context, "unable to connect to server", Toast.LENGTH_SHORT).show();
} else {
delegate.processFinish(result);
}
}
public boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setConnectTimeout(3000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
#Override
public void processFinish(String output) {
try {
JSONObject jsonObject = new JSONObject(output);
if (jsonObject.get("status").toString().equals("success")) {
JSONArray jsonarr = jsonObject.getJSONArray("data");
String columns[] = {"id", "bill_amount", "bill_price", "variation"};
for (int i = 0; i < jsonarr.length(); i++) {
ArrayList<String> temp = new ArrayList<>();
for (String column : columns) {
temp.add(jsonarr.getJSONObject(i).getString(column));
}
arr.add(temp);
setAdapter(arr);
}
} else if (jsonObject.get("status").toString().equals("end")) {
total = "end";
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "exception from json", Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
Toast.makeText(this, "Unable to connect to server...", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Null from json", Toast.LENGTH_LONG).show();
}
}
public void setAdapter(ArrayList<ArrayList<String>> arr) {
recycler.setAdapter(scrollAdapter);
scrollAdapter.notifyDataSetChanged();
scrollAdapter.setLoading();
scrollAdapter.setOnItemClickListener(this);
scrollAdapter.setOnLoadMoreListener(this);
}
Remove this line recycler.setAdapter(scrollAdapter); You need to set your adapter just once either in Activity's onCreate method or Fragment's onCreateView method.
In setAdapter() you dont need to do recycler.setAdapter(scrollAdapter); again, just do it at the beginning
I do something similar, but reversed, working as chat
messages.addAll(0, oldMessages);
mAdapter.notifyItemRangeInserted(0, oldMessages.size());
mAdapter.notifyItemChanged(oldMessages.size());
mAdapter.setLoaded();
Im adding the old messages of the char to the messages.
Then notifing the adapter I have updated the source
I uses the 0 to put at the beginning
I've tried searching the internet for solution unfortunately I could not find the answer. I tried using try catch to catch error exception but still it won't work.
Here's my code. I have private class LoginTask
private class LoginTask extends AsyncTask<String,String,JSONObject> {
private String[] privateCredentials;
private String privateRequest;
private String errorMessage = "";
//initialize all here
//constructor
LoginTask(String[] credentials,String request) {
this.privateRequest = request;
this.privateCredentials = credentials;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if(this.privateRequest=="login"){
try {
String response = result.getString("status");
if(response.equals("ok")){
onLoginSuccess(result.getString("username"),result.getString("full_name"),result.getInt("user_id"));
}else{
onLoginFails();
}
} catch (JSONException e) {
if(errorMessage!=""){
Toast ts;
ts = Toast.makeText(LoginActivity.this,errorMessage,Toast.LENGTH_LONG);
ts.show();
}
//e.printStackTrace();
}
}
}
#Override
protected JSONObject doInBackground(String... params) {
String result = "";
JSONObject resultObj = null;
HttpURLConnection con = null;
BufferedReader br = null;
JSONObject cred = new JSONObject();
if(this.privateRequest=="login"){
try {
cred.put("username", this.privateCredentials[0]);
cred.put("password", this.privateCredentials[1]);
URL url = new URL(params[0]);
con = (HttpURLConnection) url.openConnection();
;
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream outputStream = con.getOutputStream();
outputStream.write(cred.toString().getBytes());
InputStream stream = con.getInputStream();
br = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
//get the result
JSONObject jsonObj = new JSONObject(buffer.toString());
resultObj = jsonObj;
// return buffer.toString();
}catch (JSONException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
} catch (ProtocolException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} catch (IOException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} finally {
if(con!=null) {
con.disconnect();
}
}
return resultObj;
}
return null;
}
}
And here's my event listener code in the login activity.
//when clicking the login button
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do now the login process
userText.setVisibility(view.INVISIBLE);
passwordText.setVisibility(view.INVISIBLE);
tvRegister.setVisibility(view.INVISIBLE);
umlogo.setVisibility(view.INVISIBLE);
//set textviews to invisible
/* tv[0].setVisibility(view.INVISIBLE);
tv[1].setVisibility(view.INVISIBLE);*/
//set also the button to invisible
loginBtn.setVisibility(view.INVISIBLE);
//set visible the progress bar
pb.setVisibility(view.VISIBLE);
//set now the user login credentials
credentials[0] = userText.getText().toString();
credentials[1] = passwordText.getText().toString();
loginTask = new LoginTask(credentials,"login");
//loginTask.execute("http://10.0.2.2/sampleRequest.php");
//loginTask.execute("http://10.0.2.2/motorpool_june_2016_laravel/public/mobile/login");
loginTask.execute("http://128.199.105.49/mobile/login");
//SessionHolder.login(credentials, la);
}
});
However it is still not working. Please help. :(
You can't compare Strings with == in java. You must write it like below:
if(this.privateRequest.equals("login")){
== tests for reference equality (whether they are the same object)
I am trying to post data to my localhost by using AsyncTask which is accessible on 10.0.3.2:8787 by Genymotion and 127.0.0.1:8787 by Localhost. But, it seems to not post anything. Below is my code;
private class LocationUpdateTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String _url = "http://10.0.3.2:8787/user_locations/save";
HttpURLConnection httpClient = null;
try {
for (int i = 0; i < params.length; i++) {
String urlParameters = params[i];
System.out.println(urlParameters); // Prints fine here.
URL url = new URL(_url);
httpClient = (HttpURLConnection) url.openConnection();
httpClient.setRequestMethod("POST");
httpClient.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpClient.setRequestProperty("Content-Language", "en-US");
httpClient.setUseCaches(false);
httpClient.setDoInput(true);
httpClient.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(httpClient.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (httpClient != null) {
httpClient.disconnect();
}
}
return null;
}
}
public class LocationUpdaterListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
//String text = "Lat: " + location.getLatitude() + "\nLong: " + location.getLongitude();
//Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
HashMap<String, String> postDataParams=new HashMap<String, String>();
postDataParams.put("fuid", profileId);
postDataParams.put("lat", String.valueOf(location.getLatitude()));
postDataParams.put("lng", String.valueOf(location.getLongitude()));
postDataParams.put("alt", String.valueOf(location.getAltitude()));
postDataParams.put("br", String.valueOf(location.getBearing()));
postDataParams.put("acc", String.valueOf(location.getAccuracy()));
String urlParameters = null;
try {
urlParameters = "fuid=" + URLEncoder.encode(postDataParams.get("fuid"), "UTF-8")+
"&lat="+URLEncoder.encode(postDataParams.get("lat"), "UTF-8")+
"&lng="+URLEncoder.encode(postDataParams.get("lng"), "UTF-8")+
"&alt="+URLEncoder.encode(postDataParams.get("alt"), "UTF-8")+
"&br="+URLEncoder.encode(postDataParams.get("br"), "UTF-8")+
"&acc="+URLEncoder.encode(postDataParams.get("acc"), "UTF-8");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlParameters != null){
new LocationUpdateTask().execute(urlParameters);
}
}
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
No exception thrown whatsoever. If I do it normally by accessing through browser and pass the parameter, it works just fine. So, I assume something must be wrong with my code.
So, which is wrong in my code? Or anything I should try to see why this is not working?
Any suggestion is appreciated.
I've finally got it working. I don't know why but It looks like I have to let HttpURLConnection to call getInputStream at the very last of the code, like;
InputStream is = httpClient.getInputStream();
or
// getResponseCode also calls getInputStream.
int responseCode = httpClient.getResponseCode();
So, finally my code looks like this,
private class LocationUpdateTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String _url = "http://10.0.3.2:8787/user_locations/save";
HttpURLConnection httpClient = null;
try {
for (int i = 0; i < params.length; i++) {
String urlParameters = params[i];
URL url = new URL(_url);
httpClient = (HttpURLConnection) url.openConnection();
httpClient.setRequestMethod("POST");
httpClient.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpClient.setRequestProperty("Content-Language", "en-US");
httpClient.setUseCaches(false);
httpClient.setDoInput(true);
httpClient.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(httpClient.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//InputStream is = httpClient.getInputStream();
int responseCode = httpClient.getResponseCode();
}
}
catch (Exception e) {
//Log.e("TAG", "Exception", e.fillInStackTrace());
e.printStackTrace();
}
finally {
if (httpClient != null) {
httpClient.disconnect();
}
}
return null;
}
}
I'm really bad at googling things I want so I decided to ask here. My question is is it possible to show a progress bar while fetching the data from the database? I'm using the typical code when fetching data(Pass value to php and the php will do the query and pass it again to android)
Edit(I have tried adding proggressdialog but the problem now is the loaded data will appear first before the progress dialog here's my AsyncTask code)
public class getClass extends AsyncTask<String, Void, String> {
public getClass()
{
pDialog = new ProgressDialog(getActivity());
}
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}
Have you tried using an AsyncTask?
You can show your progress bar on the preExecute method and then hide it on postExecute. You can do your querying inside the doInBackground method.
In addition to what #torque203 pointed, I would suggest you to check
http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
this method was created for that purpose, showing progress to the user.
From developers docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
#Override
protected void onPreExecute() {
//show progress bar here
}
protected Long doInBackground(URL... urls) {
//Pass value to PHP here
//get values from your PHP
}
protected void onPostExecute(Long result) {
//Here you are ready with your PHP value. Dismiss progress bar here.
}
}
public void onPreExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void doInBackground() {
//do your JSON Coding
}
public void onPostExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
public class getClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}