I have a thread that sends GPS coordinates to a database every six seconds and I have a check that verifies that the user is within a defined area. If the user is not within the location, I want an alert dialog that notifies them that they are out of range, and if they are within the area I want a dialog that tells them they are within range. I have the checks working properly, but I have tried and I'm pretty sure that I can't add the dialog on the background thread. I have read a bit about using handlers but I'm not sure how to implement one. If you have any suggestions I would appreciate it! Thanks.
This is how I call FindLocation.java from my main activity (MainActivity.java):
new FindLocation(getBaseContext()).start(usr_id1); //sends a user id with it
Below is FindLocation.java
public class FindLocation extends Thread {
public boolean inJurisdiction;
public boolean AlertNotice = false;
private LocationManager locManager;
private LocationListener locListener;
Context ctx;
public String userId;
public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void start(String userId) {
this.userId = userId;
super.start();
}
#Override
public void run() {
Looper.prepare();
final String usr = userId;
//get a reference to the LocationManager
locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
Double latitude = loc.getLatitude();
Double longitude = loc.getLongitude();
if (latitude >= 39.15296 && longitude >= -86.547546 && latitude <= 39.184901 && longitude <= -86.504288 || inArea != false) {
Log.i("Test", "Yes");
inArea = true;
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", usr));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String ct_name = json_data.getString("phoneID");
Log.i("User ID", ct_name);
if(ct_name == usr) {
locManager.removeUpdates(locListener);
}
else{
locManager.removeUpdates(locListener);
Log.i("User ID", "NONE");
}
}
}
catch(Exception e){
//Log.e("log_tag", "Error converting result "+e.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
try {
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2);
nameValuePairs1.add(new BasicNameValuePair("lat", lat));
nameValuePairs1.add(new BasicNameValuePair("lon", lon));
nameValuePairs1.add(new BasicNameValuePair("id", usr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
httpclient.execute(httppost);
Log.i("SendLocation", "Yes");
}
catch (ClientProtocolException g) {
// TODO Auto-generated catch block
} catch (IOException f) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
Log.i("Test", "No");
inArea = false;
}
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener);
Looper.loop();
}
}
It is a little difficult to read the entire code, but I will show you how to display an AlertDialog from a background Thread:
Create a handler inside onCreate(), or onResume()... something that runs on the UI-Thread:
...onCreate(){
//...
mHandler=new Handler();
}
Then inside your Thread() just use:
mHandler.post(new Runnable() {
public void run(){
//Be sure to pass your Activity class, not the Thread
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
//... setup dialog and show
}
});
runOnUiThread(new Runnable() {
public void run() {
//your alert dialog here..
}
});
new Handler().post(new Runnable{
public void run(){
//create your AlertDialog here..
}
});
see more here
Related
I am trying to get the response code for the HttpReponse.
I have changed the method for getting the response but it is not working.
Before I used this try & catch:
(url is parameter for function)
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (params != null) {
method.setEntity(new UrlEncodedFormEntity(params));
}
HttpResponse response = httpclient .execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputStreamToString(inputStream);
return result;
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
But this code gave me a runtime error in HttpResponse response = httpclient .execute(method);
So I changed my code:
public class RegisterActivity extends Activity {
String username;
String password;
InputStream is = null;
String result = null;
String line = null;
int code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText usernamefield = (EditText) findViewById(R.id.username_reg);
final EditText passwordfield = (EditText) findViewById(R.id.password_reg);
Button reg_btn = (Button) findViewById(R.id.reg_btn);
reg_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = usernamefield.getText().toString();
password = passwordfield.getText().toString();
insert();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", usernamefield.getText().toString()));
params.add(new BasicNameValuePair("password", passwordfield.getText().toString()));
params.add(new BasicNameValuePair("action", "insert"));
}
});
}
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", "insert"));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.10/ferdos/service.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch (Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch (Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.e("Fail 3", e.toString());
}
}}
Please help me with this code to solve my problem.
Thats what Google says.
To avoid creating an unresponsive UI, don't perform network operations on the UI thread. By default, Android 3.0 (API level 11) and higher requires you to perform network operations on a thread other than the main UI thread; if you don't, a NetworkOnMainThreadException is thrown.
You need to execute your HTTP requests in separate thread. This can be done in a AsyncTask.
In your case you need to update UI after the downloading is finished. Use a listener to notify the UI thread
public interface ResultsListener {
public void onResultsSucceeded(String result);
}
This is an example from Google developers guide. I edited it and it calls the listener when the result is finished.
private class HttpRequestTask extends AsyncTask<URL, Integer, String> {
public void setOnResultsListener(ResultsListener listener) {
this.listener = listener;
}
protected String doInBackground(URL... urls) {
int count = urls.length;
for (int i = 0; i < count; i++) {
String httpResult = // Do your HTTP requests here
// Escape early if cancel() is called
if (isCancelled()) break;
}
return httpResult;
}
// use this method if you need to show the progress (eg. in a progress bar in your UI)
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// this method is called after the download finished.
protected void onPostExecute(String result) {
showDialog("Downloaded " + result);
listener.onResultsSucceded(result);
}
}
Now you can execute the task by calling new HttpRequestTask().execute(url) in your Activity. Your activity needs to implement the ResultsListener. Inside the onResultsSucceeded method you can update your UI elements.
You see, you can use the AsyncTask in your example pretty well. You just need some reformatting of your code.
I use AsyncTask but dont working again
please check my code
public class RegisterActivity extends Activity {
EditText editusername;
EditText editpassword;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
editusername = (EditText) findViewById(R.id.username_reg);
editpassword = (EditText) findViewById(R.id.password_reg);
Button reg_btn = (Button) findViewById(R.id.reg_btn);
reg_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = editusername.getText().toString();
password = editpassword.getText().toString();
new RegisterAsyncTask().execute();
}
});
}
class RegisterAsyncTask extends AsyncTask<Void, Void, Boolean> {
private void postData(String username, String password) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", "insert"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch (Exception e)
{
Log.e("log_tag", "Error: " + e.toString());
}
}
#Override
protected Boolean doInBackground(Void... params) {
postData(username, password);
return null;
}
}}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm new in android and I want to send editText value using JSON to server . I get this error "StringIndexOutOfBoundsException" and I don't know how can fix it. Here is My code :
JSONParser.java
package com.example.bookstore;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
HttpClient httpclient = getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpclient.execute(httpPost);
if(httpResponse != null){
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}else if(method.equals("GET")){
// request method is GET
HttpClient httpclient = getNewHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpclient.execute(httpGet);
if(httpResponse != null){
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
if(reader != null){
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
Sale.java
package com.example.bookstore;
public class Sale extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText BookName;
EditText AuthorName;
EditText Publication;
EditText Price;
EditText BookGenre;
// url to create new product
private static String url_create_product = "https://5.144.130.36/android/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.sale);
BookName = (EditText) findViewById(R.id.BookName);
AuthorName = (EditText) findViewById(R.id.AuthorName);
Publication = (EditText) findViewById(R.id.Publication);
Price = (EditText) findViewById(R.id.Price);
BookGenre = (EditText) findViewById(R.id.BookGenre);
Button confirm = (Button) findViewById(R.id.Confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewBook().execute();
}
});
}
class CreateNewBook extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Sale.this);
pDialog.setMessage("Book Submition");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
String B_Name = BookName.getText().toString();
String Au_Name = AuthorName.getText().toString();
String Pub = Publication.getText().toString();
String Pr = Price.getText().toString();
String B_Genre = BookGenre.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("B_Name", B_Name));
params.add(new BasicNameValuePair("Au_Name", Au_Name));
params.add(new BasicNameValuePair("Pub", Pub));
params.add(new BasicNameValuePair("Pr", Pr));
params.add(new BasicNameValuePair("B_Genre", B_Genre));
// getting JSON Object
// Note that create product url accepts POST method
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) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Logcat
04-29 11:13:59.536: E/AndroidRuntime(784):
java.lang.StringIndexOutOfBoundsException: length=58; regionStart=-1;
regionLength=1
04-29 11:13:59.536: E/AndroidRuntime(784): at
java.lang.String.startEndAndLength(String.java:583)
04-29 11:13:59.536: E/AndroidRuntime(784): at
java.lang.String.substring(String.java:1464)
04-29 11:13:59.536: E/AndroidRuntime(784): at
com.example.bookstore.JSONParser.makeHttpRequest(JSONParser.java:109)
I have MySSLSocketFactory class to certification that I don't think any problem exists in there.
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
Why do you add 1 to the last index? if you receive a String where the last } is really on the last index, you have a OutOfBounds.
I will edit my answer after you will paste your logs, however I think that the issue is with the :
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or with a similar fragment with string operations.
Change this line to:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{");
stringBuilder.append(StringUtils.substringBeforeLast(StringUtils.substringAfter(json, "{"), "}"));
stringBuilder.append("}");
jObj = new JSONObject(stringBuilder.toString());
This piece is entirely StringOutOfBoundsException and NullPointerException safe.
According to: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
Im trying to store an intent from an android app to a database and I'm having some issues converting it into a string and storing it in the database.Its connecting to the database and the id is incrementing.
Ive stored the intents inside the string.xml file like this:
<string name="key_username">username</string>
<string name="key_pet_name">pet_name</string>
I took the intent from another actvity like this:
Intent i = newIntent(Hamster.this,Death.class); i.putExtra(getString(R.string.key_username),Username); i.putExtra(getString(R.string.key_pet_name), Petname);
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
overridePendingTransition(0, 0);
startActivity(i);
And this is the code I'm using to connect to the database:
public class Death extends Activity {
public static String Petsname,Username ;
private ImageView dead;
private Button submit;
private TextView hamsters_death;
public static final String TAG = "Death";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.death);
final Intent intent = getIntent();
submit = (Button) findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Username = intent.getStringExtra(getString(R.string.key_username));
String Petname = intent.getStringExtra(getString(R.string.key_pet_name));
Log.d(TAG, Username);
Log.d(TAG,Petname);
new SummaryAsyncTask().execute(new FormData());
}
});
}
}
class SummaryAsyncTask extends AsyncTask<FormData, Void, JSONArray> {
Intent intent;
public String Username;
public String Petname;
public void postData(String Username, String Petname)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8888/Hamster_website/hamster.php");
try{
ArrayList<NameValuePair> form_items = new ArrayList<NameValuePair>(2);
form_items.add(new BasicNameValuePair("Username", Username));
form_items.add(new BasicNameValuePair("Petname", Petname));
httppost.setEntity(new UrlEncodedFormEntity(form_items));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: " + e.toString());
}
}
protected JSONArray doInBackground(FormData... params) {
postData(Username, Petname);
return null;
}
}
class FormData {
public JSONArray PostForm() {
{
String url = "http://10.0.2.2:8888/Hamster_website/hamster.php";
HttpEntity httpEntity = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//JSONArray =
for (int i = 0; i < jsonArray.length(); i++) {
Log.d("JSON DEBUG", jsonArray.get(i).toString());
}
} catch (JSONException jse) {
jse.printStackTrace();
}
return jsonArray;
}
}
}
I'm trying to add an AsyncTask to the following class but I'm not sure where to start. I would like to encapsulate the entire class if possible. I'm new to Android and Java so I really have no idea about what I'm doing. The following class works, and I can send all the information to my database properly. Each time the user's location is updated, the program first checks a table in the database for the user ID; if it does not exist in the table the GPS coordinates are sent, but if the user ID is in the table, the coordinates are not sent and the program stops sending location updates. This works like it should, but it locks up my UI and throws an ANR error when attempting to interact. I know that I need to implement an AsyncTask, but I need some guidance. Below is the complete code for the class. Any help would be great!
public class FindLocation {
protected static final Context SendLocation = null;
private LocationManager locManager;
private LocationListener locListener;
Context ctx;
public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void startLocation(final Context context, String usr_id2) {
final String usr = usr_id2;
//get a reference to the LocationManager
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", usr));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String ct_name = json_data.getString("phoneID");
if(ct_name == usr) {
locManager.removeUpdates(locListener);
}
}
}
catch(Exception e){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
try {
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2);
nameValuePairs1.add(new BasicNameValuePair("lat", lat));
nameValuePairs1.add(new BasicNameValuePair("lon", lon));
nameValuePairs1.add(new BasicNameValuePair("id", usr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
httpclient.execute(httppost);
}
catch (ClientProtocolException g) {
// TODO Auto-generated catch block
} catch (IOException f) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener);
}
}
All you should have to do is:
modify FindLocation class by extending asynctask
change startLocation for an override of doInBackground.
Then call the execute method of your asynctask instead of startLocation.
Also, in your case, an asynctask may not be the best. Usually you use an asynctask because you want to do something in the background and then, when the task is done, update some ui components with the result of the background operation. Here, as you just want something in the background but no UI update, you could be better using a normal thread :
make you class extend thread
change startLocation for an override of run
start your thread instead of calling startLocation
--Update with details --
This could be simpler but the idea to get more familiar with asyncTask ia a good one too.
public class LocationFinder extends Thread {
public LocationFinder( Context ctx ) {
this.ctx = ctx;
}
public void start( String userId ) {
this.userId = userId;
super.start();
}
//defensive programming : prevent your thread from beeing started in an undesired way
#Override
public void start() {
throw new IllegalStateException( "LocationFinder can't be started using start(). Prefer start( int )." );
}
public void run() {
//remaining of the code of startLocation except the first line.
}
}
to use your thread then do in an activity :
new LocationFinder( this ).start( userId );
private class BackgroundLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Long doInBackground() {
dialog = new ProgressDialog(ctx);
dialog.show();
}
protected void doInBackground() {
// do all your stuff here that doesn't modify the UI
}
protected void onPostExecute(Long result) {
// do what you need to to the UI
dialog.dismiss();
}
Then to create an instance call new BackgroundLoader().execute(); in your onCreate() method