ANDROID: Code not working after inserting Date string to GET Url - java

I am making a android client that reports its location to my server after every 10 seconds.
For server I'm using dynamic DNS. I have to sent latitude, longitude and time-stamp as GET parameters.
I made the following working code:
package in.kirancity.trackapp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView textLat;
TextView textLong;
TextView textRes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView)findViewById(R.id.textLat);
textLong = (TextView)findViewById(R.id.textLong);
textRes = (TextView)findViewById(R.id.textRes);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);
}
class myLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location arg0)
{
if(arg0 != null)
{
double plong = arg0.getLongitude();
double plat = arg0.getLatitude();
String url = "http://vishalhome.myftp.org/insert.php?la="+Double.toString(plat)+"&ln="+Double.toString(plong)+"&d='Arbitrary'";
textLat.setText(Double.toString(plat));
textLong.setText(Double.toString(plong));
new RequestTask().execute(url);
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
class RequestTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
TextView tv=(TextView)findViewById(R.id.textRes);
tv.setText(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This code works fine for me. But instead of sending actual time-stamp i sent "Arbitrary" string.
After successfully executing asyncTask, the values are inserted and Response is: "inserted"(Returned by my php page).
But when I'm trying this in onLocationChanged:
String url = "http://vishalhome.myftp.org/insert.php?la="+Double.toString(plat)+"&ln="+Double.toString(plong)+"&d=\'";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
url = url + currentDateandTime + "\'";
the application crashes on location change event.
I tried to put try catch blocks, but no clue of problem.
I think problem is coming out after new RequestTask(url) is called.
Please assist !

I think you should encode the url before using it. Try this:
currentDateandTime = URLEncoder.encode(currentDateandTime, "utf-8");
url = url + currentDateandTime + "\'";
Please see URL encoding in Android

Related

dialog box apeearing continuously while loading image in loop from php mysql

Here is my java code for loading a title, description, date and an image from Mysql through Php in a loop. Everything loading perfectly except image. When I load image the loading dialog box displaying and I can see only one image in the background but the loading dialogue box is still appearing. I'm new in android so I need experts help like you.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog = new ProgressDialog(getActivity());
pDialog.dismiss();
}
pDialog.dismiss();
}
}
your code seems to be ok.
also check some option like volley
Try something like following
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
To call this
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
To dismiss dialog show the dialog only once before for loop and dismiss it after for loop
Hope it will help :)

Android: how to restart a method with a button click

I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Unable to send GPS coordinates to server

I am trying to send GPS coordinates to server got by my app,it is showing GPS coordinates correctly, but unable to send it to server, the problem is in my MainActivity.java
Here is my code
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
int lat,lng;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_location);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
private class LoadServerASYNC extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80"); //your php file path
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", "1.0256"));
nameValuePairs.add(new BasicNameValuePair("lng", "1.0256"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
I am not getting what is the problem
You are not initializing and executing the LoadServerAsync anywhere.
If you want to send coordinates every time you update the text views, you should do this:
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
LoadServerASYNC task = new LoadServerASYNC();
task.execute();
}
And you should call postData method inside doInBackground();

Can't access methods/variables in a different classes

I'm trying to get the body of this link to be stored in String HTML and then load it to the WebView. (Parsing the code is done with Jsoup). When I press the button, the debugger shows me String HTML = re.fixCode(); and says "Debug Current Instruction Pointer".
I have tried many things, like passing the string in a method and passing the string as it. But the same thing happens over and over. My conclusion is that it doesn't pass the method/variables to my other classes? (Hope you understand that last bit)
And if that is the case how do I access them? Through intents?
So to be clear, I want to get the body, pass it on to a string and then load it in the WebView. Thanks!
Main class
public class MainActivity extends Activity {
private String uri = "http://www.novasoftware.se/webviewer/%28S%28muz0tu55twfd43zkqrlejb55%29%29/design1.aspx?schoolid=18200&code=83310";
private RequestTask re;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
final WebView web = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RequestTask().execute(uri);
loadWeb();
}
});
}
private void loadWeb() {
**String HTML = re.fixCode();**
System.out.println(HTML);
// web.loadData(re.fixedHtml, "text/html", null);
}
}
RequestTask class
package com.dir.schema;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.os.AsyncTask;
public class RequestTask extends AsyncTask<String, String, String>{
public String html, fixedHtml;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
html = result;
fixCode();
}
public String fixCode() {
Document doc = Jsoup.parse(html);
return fixedHtml = doc.body().toString();
}
}
You're calling re.fixCode(), but re hasn't been set to anything. I expect you're getting a null pointer error at this point.
I think you want to rewrite your onClick() method like so:
public void onClick(View v) {
re = new RequestTask();
re.execute(uri);
loadWeb();
}

Sending json Post date in android with parameter

I'm trying to make a POST request with Android, but I'm not succeeding. I think the problem is in how to set the parameters for resquisição and Header. Below is my method I do the request ...
public void testPostDate() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
Gson gson = new Gson();
CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo",
"descrição", 10.00, 30.00);
CrimePOST crimePost = new CrimePOST();
crimePost.setCrime(crime);
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs="));
String json = gson.toJson(crimePost);
String paramString = URLEncodedUtils.format(params, Utils.ENCODE);
try {
HttpPost post = new HttpPost(
"http://safe-sea-4024.herokuapp.com/crimes/mobilecreate"
+ "?" + paramString);
post.setHeader("Content-Type", "application/json");
StringEntity entitty = new StringEntity(json);
entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(entitty);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = toString(in);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This method is responsible for converting an inputStream to String
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
Really I am passing the Header correctly?
You have to do this in an AsyncTask
I wrote this tutorial while back. it does send json data via HTTP Post to a url. Check it out. Original post can be found here:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity implements LocationListener{
private TextView textView =null;
LocationManager locationManager=null;
Location location=null;
protected String url;
protected JSONObject jsonData=null;
private EditText urlText=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gpsEnabled!=true) {
Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
textView = (TextView)findViewById(R.id.textView);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
urlText = (EditText)findViewById(R.id.urlTextbox);
Button submitButton = (Button)findViewById(R.id.submitUrl);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (urlText.getText()!=null) {
url=urlText.getText().toString();
System.out.println(url);//for testing only, not required
Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString());//not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public class HttpPostHandler extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = null;
try {
dataEntity = new StringEntity(jsonData.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(dataEntity);
httpPost.setHeader("Content-Type", "application/json");
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Categories

Resources