Android Studio HttpURLConnection not posting data - android

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;
}
}

Related

Android - Call Thread synchronized on UI thread

I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
                         #Override
                         public void run () {
                             synchronized (syncJob) {
                                 String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
                                 txtState.setText (s);
                             }}});
                         }
                     });
                     t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.

RecyclerView Pagination not maintaining Scroll Position

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

How to avoid force close application in Android

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)

Android - HttpsURLConnection - BAD REQUEST

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();
}
}

Informationparsing from URL-Request not working / Didn't found TextView

i need your help. I want to send a URL Request, get response and create a JSON Object. My first try was totally wrong. Now I found a tutorial and made a new try.
My Activity looks like:
public class Patienten extends Activity {
//Beacon Elemente
private String UUID;
private String Major;
private String Minor;
private TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patienten);
output = (TextView) findViewById(R.id.output);
UpdateBeaconInformation();
Button cmdHit = (Button) findViewById(R.id.cmd_hit);
cmdHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
}
});
setTitle(Surname + ", " + FirstName);
// output.setText(output.getText().toString() + "Gefundener Patient:\n" + "Name: " + Surname + ", " + FirstName + "\nGeb.-Dat: " + Birthdate);
}
Then I created a new Java Class and built an asyncTask with it. But I can't access to the textview output in onPostExecute to update it.
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//http://kusber-web.de/JsonTest.txt
//http://nilsbenning.selfhost.me/PatientFinder.php?beacon_comID=5181f8a3-7354-46ac-b22d-952ec395ab06&beacon_major=12&beacon_minor=249
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
output.setText(result);
}
}
What is my mistake? Why I can't access to it? I saw it as a solution here but didn't get it to work:
https://stackoverflow.com/a/12252717/5743912
Hope you can help me now! :)
You probably want to fix this (remove leading slashes):
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
In your JSONTask you can reference members of Patienten by using Patienten.this. So in onPostExecute you should change this:
output.setText(result);
to:
Patienten.this.output.setText(result);

Categories

Resources