Using String doInBackground(String... args) - java

I am working on saving my data to a MySQL db. I read that you need to use a new thread to open the db. I have seen examples for using AsyncTask. How would I access the doInBackground method. I have tried a variety of different method call and either get an error or the program does not use the AsyncTask. Here is my code. I have tried different version of AddtoSQLDB db = new AddtoSQLDB()
and CreateNewProduct cn = new CreateNewProduct().
public class AddToMySQLDB extends Activity {
JSONParser jsonParser = new JSONParser();
// TODO Auto-generated method stub
// url to create new product
private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private ProgressDialog pDialog;
static String name = "";
static String company = "";
static String timeIn = "";
static String signature;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public static void setVariable(String sDate, String visitorsName2, String visitorsCompany2, byte[] signature2) {
name = visitorsName2;
company = visitorsCompany2;
timeIn = sDate;
}
class CreateNewProduct extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// getting JSON Object
// Note that create product url accepts POST method
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("timeIn", timeIn));
params.add(new BasicNameValuePair("signature", signature));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
/* Intent i = new Intent(getApplicationContext(),
AllProductsActivity.class);
startActivity(i);*/
// closing this screen
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}

You need to execute your AsyncTask:
CreateNewProduct cn = new CreateNewProduct();
cn.execute(""); //pass the params you want for doInBackground here

Related

Android convert EditText to String [duplicate]

This question already has answers here:
Method getText() must be called from the UI Thread (Android Studio)
(5 answers)
Closed 7 years ago.
I know how to convert the EditText to a string, no clue why it doesn't work.
String username = user.getText().toString();
user = (EditText)findViewById(R.id.username);
I am getting this error: "Method getText must be called from the UI thread, currently inferred thread is worker"
Full code:
public class Login extends Activity implements OnClickListener{
private EditText user;
private Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://testapp.comlu.com/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText)findViewById(R.id.username);
String aID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
bLogin = (Button)findViewById(R.id.login);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String androidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("androidID", androidID));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString());
// success tag for json
success = 1;
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,Menu.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
}
}
}
Any ideas?
Thanks,
Yoshi
I am getting this error: "Method getText must be called from the UI
thread, currently inferred thread is worker"
you could move
String username = user.getText().toString();
in your onClick method, and pass the String to the AsyncTask like
new AttemptLogin().execute(username);
When doInBackground is invoked you can access it trough String... args, E.g. args[0]
You cannot manipulate UI elements from background thread. You are trying to access the UI element in the doInBackground method:
String username = user.getText().toString();
Instead of that, you should pass the data to the async task like:
new AttemptLogin().execute(user.getText().toString());
Also you are starting an activity from the doInBackground method. You should move that piece of code to onPostExecute method.

How to use common request and response in soap asynctask throughout multiple activities android?

I am using Soap request and response using asynctask. I am sending json request and fetching the response. But How to use this asynctask to perform request and response in common class. So that I can use in multiple activites by passing request and fetch response. Please provide me solution. How to solve this?
So far I am doing like this. I wrote for single asynctask. But for another service call, I need to perform another asynctask. How to use this in common and perform.
I have commented in code for better understanding. Here is my code.
class A extend Activity{
private String sessionId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sortfilterclick);
new CommonElement().execute();
}
class CommonElement extends AsyncTask<String, String, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CommonElement.this);
dialog.show();
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... args) {
try {
// these are all common
SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.API_URL);
sessionId = Utils.readPreferences(CommonElement.this,Constants.SESSION_ID, null);
if (sessionId == null) {
SoapObject request = new SoapObject(Constants.NAMESPACE, "login");
request.addProperty("username", "Clothing");
request.addProperty("apiKey", "Clothing");
env.setOutputSoapObject(request);
androidHttpTransport.call("", env);
Object result = env.getResponse();
sessionId = result.toString();
Utils.savePreferences(SortFilterPopupActivity.this,
Constants.SESSION_ID, sessionId);
}// till this it's common
//here json reuest datas varies in json.put()...
SoapObject requests = new SoapObject(Constants.NAMESPACE, "call");//these are common
requests.addProperty("sessionId", sessionId);//these are common
requests.addProperty("resourcePath","sortap.Action"); //this will change for every property
JSONObject json = new JSONObject();// these will change
json.put("page", "1");
json.put("limit", "10");
json.put("name", sortName);
json.put("order", sortOrder);
json.put("id", "3");
json.put("cate_id", "4");
String params = json.toString();
requests.addProperty("args", params);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
//based on various request and response this varies.
if (results.toString() != null) {
JSONObject jsono = new JSONObject(results.toString());
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String id = object.getString("id");
String productName = object.getString("product_name");
String imageUrl = object.getString("image_url");
int productPrice = object.getInt("price");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
}

AsyncTask not completing as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a CreateUser class which creates a user. This worked correctly until I tried to add a new field for a password check.
In the task I'm checking to see if the password fields match and if they dont I cancel the execution and move to a toast.
It correctly checks the passwords and toasts when incorrect but if they match it still cancels execution and never completes creating a new user.
CODE:
public class Register extends Activity implements OnClickListener{
private EditText user, pass, confirmPass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "https://xxx.xxx.xxx.xxx/xxx.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
confirmPass = (EditText)findViewById(R.id.passwordConfirm);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String passwordCheck = confirmPass.getText().toString();
try {
//-----------------------------------------------------------------------------Password Check
if (password != passwordCheck) {
cancel(true);
}
if (!this.isCancelled()) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
pDialog.dismiss();
Toast.makeText(Register.this, "Passwords do not match", Toast.LENGTH_SHORT).show();
}
}}
In your doInBackground, you're comparing 2 strings using != this will only compare the memory addresses of the strings and therefore will evaluate to false even if the value of the two strings is the same. Change it to equals()

Json response is very slow android

I'm writing an Android application which will occasionally need to download a json string of around 1MB and containing around 1000 elements, and parse each of these into an SQLite database, which I use to populate a ListActivity.
Even though the downloading and parsing isn't something that needs to be done on every interaction with the app (only on first run or when the user chooses to refresh the data), I'm still concerned that the parsing part is taking too long, at around two to three minutes - it seems like an eternity in phone app terms!
I am using this code... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
Don't use Async-task in such case, use native java thread here.
new Thread(new Runnable() {
public void run() {
// Do your work .....
}
}).start();
When need to update UI. Yes! Android won't allow you to do that. so... solution is: USE Handler for that :)
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// Do Update your UI
}
});
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
You could use Google's GSON as well.
Try to use Jackson Library to manage your JSON. It is really efficient. You can find it here : http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
I am using it for a 400KB file is less than 1 second.
If you want a tuto this one looks good http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
This is how is read JSON into my listview in my app. The result is processed to my app in an average of 3 seconds on Wi-Fi and 5 seconds on 3G:
public class CoreTeamFragment extends ListFragment {
ArrayList> membersList;
private String url_all_leaders = //URL goes here
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_TEAM = "CoreTeam";
private static final String pid = "pid";
private static final String COL_NAME = "CoreTeam_Name";
private static final String COL_DESC = "CoreTeam_Desc";
private static final String COL_PIC = "CoreTeam_Picture";
JSONArray CoreTeam = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public CoreTeamFragment() {
}
public void onStart() {
super.onStart();
membersList = new ArrayList<HashMap<String, String>>();
new LoadAllMembers().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.leader_id))
.getText().toString();
Intent intent = new Intent(view.getContext(),
CoreTeamDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_coreteam,
container, false);
return rootView;
}
class LoadAllMembers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_leaders,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
CoreTeam = json.getJSONArray(TABLE_TEAM);
// looping through All Contacts
for (int i = 0; i < CoreTeam.length(); i++) {
JSONObject ct = CoreTeam.getJSONObject(i);
// Storing each json item in variable
String id = ct.getString(pid);
String name = ct.getString(COL_NAME);
String desc = ct.getString(COL_DESC);
String pic = ct.getString(COL_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_PIC, pic);
// adding HashList to ArrayList
membersList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(),
membersList,
R.layout.coreteam_item,
new String[] { pid, COL_NAME, COL_DESC, COL_PIC },
new int[] { R.id.leader_id, R.id.leaderName,
R.id.photo });
setListAdapter(adapter);
}
});
}
}
}
Use Volley or Retrofit lib.
Those lib are increasing the speed.
Volley:
JsonObjectRequest channels = new JsonObjectRequest(Method.POST,
Constants.getaccountstatement + Constants.key, statement_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}

database only showing zeros 0

I'm new to java and PHP, could someone please help my database only shows 0's ...
java code:
public class postData extends Activity {
//Progress Dialog
private ProgressDialog pDialog;
//JSONParser jsonParser = new JSONParser();
//url to update coordinates
private static String url_update_coordinates = "http://www.myurl.com";
//JSON Node names
private static final String TAG_SUCCESS = "Success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.post_coords);
final Context ctx = this;
//Create button
Button btnUploadCoordinates = (Button) findViewById(R.id.button5);
//Button click event
btnUploadCoordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// updating coordinates on background thread
new UploadCoordinates(ctx).execute();
}
});
}
//Background Async Task to upload coordinates
class UploadCoordinates extends AsyncTask <String, String, String> {
// Before starting background thread Show Progress Dialog
private Context ctx;
public UploadCoordinates(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(postData.this);
pDialog.setMessage("Uploading Coordinates...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
//Creating Coordinates
#Override
protected String doInBackground(String... params) {
JSONArray json = new JSONArray();
MySQLite dbhelper = new MySQLite(ctx);
Cursor data = dbhelper.getlocations();
while(data.moveToNext()) {
int _id = data.getInt(0);
double latitude = data.getDouble(1);
double longitude = data.getDouble(2);
double altitude = data.getDouble(3);
double speed = data.getDouble(4);
double timestamp = data.getDouble(5);
JSONObject jo = new JSONObject();
try{
jo.put("_id", _id);
jo.put("latitude", latitude);
jo.put("longitude", longitude);
jo.put("altitude", altitude);
jo.put("speed", speed);
jo.put("timestamp", timestamp);
} catch(JSONException e) {
}
json.put(jo);
}
String json_data = json.toString();
// Adding the data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("coords", json_data));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.myurl.com");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Check log for response
Log.d("Create response", json.toString());
return null;
}
// check for success tag
try {
int success = json_data.getInt(TAG_SUCCESS);
GIVING ME PROBLEMS HERE The method getInt(String) is undefined for the type String
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), GPSLoggerService.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//After completion background task Dismiss progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once done
pDialog.dismiss();
}
}
}
php script:
<?php
ini_set('error_reporting', E_ALL); ini_set('display_errors','1');
//include dbconnect class
require_once (__DIR__ . '/db_connect.php');
//connecting to db
$db = new DB_CONNECT();
//decode array
$arr = (isset($_POST['coords']));
$decarr = json_decode($arr, true);
$count = count($decarr);
$values = array(); //hold array values so we do one single insert
$update_values = array(); //holds values for the ON DUPLICATE KEY UPDATE
for ($x=0; $x <$count; $x++)
{
$newrec = $decarr[$x];
$_id = $newrec['_id']; $_id = mysql_real_escape_string($_id);
$latitude = $newrec['latitude']; $_id = mysql_real_escape_string($latitude);
$longitude = $newrec['longitude']; $_id = mysql_real_escape_string($longitude);
$timestamp = $newrec['timestamp']; $_id = mysql_real_escape_string($timestamp);
$altitude = $newrec['altitude']; $_id = mysql_real_escape_string($altitude);
$speed = $newrec['speed']; $_id = mysql_real_escape_string($speed);
//create insert array
$values[] = "('".$_id."','".$latitude."','".$longitude."','".$timestamp."','".$altitude."','".$speed."')";
//For the duplicate updates
$update_values[]=
"latitude=VALUES(latitude), longitude=VALUES(longitude), timestamp=VALUES(timestamp), altitude=VALUES(altitude), speed=VALUES(speed)";
}
//insert records
$sql = "INSERT INTO logs(_id, latitude, longitude, timestamp, altitude, speed)
VALUES ".implode(',', $values)." ON DUPLICATE KEY UPDATE ".implode(',',$update_values);
$result = mysql_query($sql);
?>
Been trying for hours and can't figure out where the problem is, maybe this will be a silly one for many of yous out there.
thank you in advance for all your help.
Regards
V
UPDATE - Not sure if I should do this, but it will be easier as all the code is already here, my error is between blockquote... can't get my head around to see where the problem lyes ... any help appreciated.
The problem is that you use isset function and assign it's return value to $arr variable, and then using it as an array.
You should use this function to determine if a variable is set and is not NULL: it returns true or false.
In your PHP code, instead of lines 10 and 11, try this:
$decarr = isset($_POST['coords']) ? json_decode($_POST['coords'], true) : array();

Categories