I am attempting to start a new Intent inside onPostExecute() method after an AsyncTask. The app always crashes however and there are no error logs. The System.out.println() calls return the expected output.
#Override
protected JSONObject doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Use the email address minus the '#' prefix as temp username.
String[] uList = (mEmail.split("#"));
String mUsername = uList[0];
Serverrequest request = new Serverrequest();
JSONObject userObj = request.getJSON(
"http://10.0.2.2:3700/api/login", mUsername, mPassword);
if (userObj != null) {
// Account exists, return user
return userObj;
} else {
System.out.println("Null response");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// TODO: register the new account here.
JSONObject newUser = new JSONObject();
try {
newUser.put("username", "Charlie");
} catch (JSONException e) {
}
return newUser;
}
#Override
protected void onPostExecute(final JSONObject user) {
try {
mAuthTask = null;
showProgress(false);
System.out.println(user);
String username = user.getString("username");
System.out.println(username);
SharedPreferences prefs = getSharedPreferences("wordsmith", MODE_PRIVATE);
prefs.edit().putString("username", username).apply();
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(LoginActivity.this, StartScreenActivity.class);
intent.putExtra("user", user.toString());
LoginActivity.this.finish();
startActivity(intent);
Related
I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Can't create handler inside thread that has not called Looper.prepare() Android
(2 answers)
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 3 years ago.
So i'm into a tutorial at Udemy "The Complete Android N Developer Course" and trying to make lecture 86 about a weather app.
I use the API from here https://openweathermap.org/current#cityid and use JSON to get the data needed.
The app is working properly when i input a correct city name, but when the input is wrong or empty the app crashes without catching any exceptions.
I don't know why it is crashing and where to look. So i give you all the code i wrote. I tried to implement if statements here and there to try and find it but without any luck.
I would like to know where the problem is and how to fix it so the app doesn't crash anymore.
Thanks in advance.
public class MainActivity extends AppCompatActivity {
EditText editText;
String city = "";
TextView textView;
public void getWeather (View view) {
try {
city = URLEncoder.encode(editText.getText().toString(), "UTF-8");
if (editText.getText().toString() == "") {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
textView.setText("Please enter a city.");
} else {
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=c6ef169a79d84674ef7e1414301eb5c4");
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
} catch (UnsupportedEncodingException e1) {
Toast.makeText(MainActivity.this, "UnsupportedEncodingException", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (getWeather)", Toast.LENGTH_SHORT).show();
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = null;
in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPart = jsonArray.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
textView.setText(message);
} else {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
Toast.makeText(MainActivity.this, "JSONException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (onPostExecute)", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
}
}
It is because you're trying to changes UI with background thread inside the doInBackground(Params...) method of AsyncTask with this line:
try {
...
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
You should not call Toast inside the doInBackground(Params...). Do that inside the onPostExecute(Result).
You can avoid that by either ignoring the error or returning specific text in doInBackground. Something like this:
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
...
try {
...
return result;
} catch (MalformedURLException e1) {
result= "MalformedURLException";
} catch (IOException e2) {
result= "IOException";
} catch (Exception e) {
// do nothing and returning empty
result= "Exception";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// check if there is an error
String errorMessage = "";
switch(result) {
case "MalformedURLException":
errorMessage = "MalformedURLException";
break;
case ""IOException":
errorMessage = "IOException";
break;
case "Exception":
errorMessage = "Exception";
break;
}
// there is an error, show a message.
if(!errorMessage.isEmpty()) {
Toast.makeText(MainActivity.this, "Could not find weather: " + errorMessage, Toast.LENGTH_SHORT).show();
return; // stop the process.
}
// do something when no error found.
}
}
When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.
I am sending android user location lat and longitude to server together with registration ID and other parameters as json object in Asynctask(a nested class of the activity). But the Location object(that had values at the start of the app) instantiated in the activity as such
location = LocationServices.FusedLocationApi
.getLastLocation(mgoogleapiclient);
is returning null in the Asynctask Class. Can someone explain to me why? Do I have to use separate class to get user location and send it in another asynctask or service(which doesn't make sense from architectural standpoint)?
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
PostData pdata = new PostData();
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
pdata.execute(String.valueOf(latitude), String.valueOf(longitude));
}
I am retrieving this from the AsyncTask class as such:
json.put("latitude", String.valueOf(args[1]));
json.put("longitude", String.valueOf(args[2]));
But when I debug it, I am getting the getting the registration ID which I sent to the AsyncTask class from another method.
I hope I am making myself clear.
#Override
protected String doInBackground(String... args) {
try {
try {
URL url;
HttpURLConnection urlConn;
url = new URL ("myphp.php");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setChunkedStreamingMode(0);
urlConn.setRequestMethod("POST");
urlConn.connect();
//get google account
AccountManager am = AccountManager.get(getBaseContext()); // "this" references the current Context
Account[] accounts = am.getAccountsByType("com.google");
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("regID", String.valueOf(args[0]));
json.put("Google account", accounts[0].name);
json.put("name", "Amanda");
json.put("tel", "2069994444");
json.put("latitude", String.valueOf(args[1]));
json.put("longitude", String.valueOf(args[2]));
String postData=json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex){
ioex.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code");
}
return null;
}
The following is how I sent the registration ID
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (!regid.isEmpty()) {
PostData pd = new PostData();
pd.execute(regid);
} else {
//register
registerInBackground();
}
The problem is that you are sending two separate sets of varargs to the AsyncTask at different times.
You should be sending all necessary data to the AsyncTask when you call execute() in order for it to have the data is needs.
So, you need to get all of the data ready, and send it in one call to execute(), something like this:
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (!regid.isEmpty() && mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
PostData pd = new PostData();
pd.execute(regid, String.valueOf(latitude), String.valueOf(longitude));
} else {
//register if regid is empty
if (regid.isEmpty()){
registerInBackground();
}
}
Also, there is no need to call String.valueOf() on your String arguments that are passed in to doInBackground(), so you can remove those calls:
#Override
protected String doInBackground(String... args) {
try {
try {
URL url;
HttpURLConnection urlConn;
url = new URL ("myphp.php");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setChunkedStreamingMode(0);
urlConn.setRequestMethod("POST");
urlConn.connect();
//get google account
AccountManager am = AccountManager.get(getBaseContext()); // "this" references the current Context
Account[] accounts = am.getAccountsByType("com.google");
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("regID", args[0]); //modified
json.put("Google account", accounts[0].name);
json.put("name", "Amanda");
json.put("tel", "2069994444");
json.put("latitude", args[1]); //modified
json.put("longitude", args[2]); //modified
String postData=json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex){
ioex.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code");
}
return null;
}
Edit: It sounds like you should register a location listener in order to explicitly request a location. Here is sample code that you can use as a reference in order to register a location listener in your code:
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
Log.d("locationtesting", "accuracy: " + location.getAccuracy() + " lat: " + location.getLatitude() + " lon: " + location.getLongitude());
Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();
//unregister here if you only need one location update:
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
private void startReceivingLocationUpdates() {
if (locationManager == null) {
locationManager = (android.location.LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
if (locationManager != null) {
try {locationManager.requestLocationUpdates(android.location.LocationManager.NETWORK_PROVIDER, 1000, 0F,
(android.location.LocationListener) listener);
}
catch (SecurityException ex)
{
Log.i(TAG, "fail to request location update, ignore", ex);
}
catch (IllegalArgumentException ex)
{
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
try {
locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 1000, 0F,
(android.location.LocationListener) listener);
//if (listener != null) listener.showGpsOnScreenIndicator(false);
}
catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
}
catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
Log.d(TAG, "startReceivingLocationUpdates");
}
}
This solved the null pointer exception on my Location object, I got it from here
I have had this problem and i cant figure out how to sort this out. I am using android studio to compile my project. The problem im having is that i can only send the Login information once with success which is weird for me. I am not an advanced android programmer.
Here is the code that im having the problem with:
public void postData(String valueIWantToSend) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_URL);
try {
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("username", user.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", pass.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
JSONArray jsonArray = null;
HttpEntity entity = null;
String responsestr = null;
JSONObject json = null;
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
entity = response.getEntity();
try {
responsestr = EntityUtils.toString(entity);
Toast.makeText(getApplicationContext(),
"We have good response string",
Toast.LENGTH_SHORT)
.show();
jsonArray = new JSONArray(responsestr);
} catch (JSONException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Integer success = 0;
for (int i=0; i<jsonArray.length(); i++)
{
json = null;
try {
json = jsonArray.getJSONObject(i);
success = json.getInt("success");
Toast.makeText(getApplicationContext(),
"We Have a good return",
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1){
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
}
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
}
Now as i said it works once then it becomes non responsive if you retry loging in or correcting the username password?
Really not sure how to fix this. If i have left out any information let me know and i will be happy to provide it to you.
Edit 1(Could be a long night):
Ok i have seen that the post works each time before the application goes non responsive. it seems as if it only retrieves the data once and then never again even if the application is closed and reopened. it will only work again if i recompile from Android studio then it goes back to its non responsive sate :(.
Edit 2:
Sorry Guys here is how i call the async task from an onClick event attached to the login button
public void sendMessage(View view){
String s1, s2;
s1 = user.getText().toString();
s2 = pass.getText().toString();
if ((s1.matches("")) || (s2.matches(""))) {
Toast.makeText(this, "Please fill out all fields.", Toast.LENGTH_SHORT).show();
} else {
//Intent intent = new Intent(this, com.example.studentpa.Dashboard.class);
//startActivity(intent);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(s1);
}
}
i have found the solution to my problem, Please see the comments for the changes made, also here is the code that now works.
public void loginMethod(View view) {
em = email.getText().toString();
ps = pass.getText().toString();
if (isConnected()) {
if (em.contains(" ") || ps.contains(" ")) {
Toast.makeText(getApplicationContext(), "No spaces are allowed in either field", Toast.LENGTH_SHORT).show();
} else if (em.matches("") || ps.matches("")) {
Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
} else {
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(em);
email.setEnabled(false);
pass.setEnabled(false);
}
} else {
Toast.makeText(getApplicationContext(), "You are not connected to the internet", Toast.LENGTH_SHORT).show();
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double> {
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
if (strResponse.isEmpty()){
Toast.makeText(getApplicationContext(), "We have no response from the server", Toast.LENGTH_LONG).show();
} else {
try {
jsonArray = new JSONArray(strResponse);
} catch (JSONException e){
e.printStackTrace();
}
JSONObject json;
json = null;
Integer success = 0;
for (int i=0; i<jsonArray.length(); i++)
{
json = null;
try {
json = jsonArray.getJSONObject(i);
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1){
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
} else if (success == 0){
Toast.makeText(getApplicationContext(), "Incorrect Login Details", Toast.LENGTH_SHORT).show();
}
}
email.setEnabled(true);
pass.setEnabled(true);
pb.setVisibility(View.GONE);
}
protected void onProgressUpdate(Integer... progress) {
pb.setProgress(progress[0]);
}
public void postData(String s1) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.gbes.co.za");
HttpEntity entity;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", em));
nameValuePairs.add(new BasicNameValuePair("password", ps));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
strResponse = EntityUtils.toString(entity);
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (HttpHostConnectException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit:
Hey Guys Here is the server code:
The database connection is hidden for server protection
<?php
$uName=$_POST['username'];
$pWord=$_POST['password'];
$squl = "SELECT * FROM `usr` WHERE `uE`='".$uName."' && `uP`='".$pWord."' LIMIT 1";
$query = mysql_query($squl);
if (mysql_num_rows($query) == 1)
{
date_default_timezone_set('Africa/Johannesburg');
while($rows = mysql_fetch_array($query)){
$logincount=$rows['uLC'];
$logincount=$logincount + 1;
$uid=$rows['ID'];
}
$nowtime = date("Y-m-d H:i:s");
$loginsql = "UPDATE `users` SET `uLC`=$logincount, `uLL`='$nowtime'";
$query = mysql_query($loginsql);
$login_ok = true;
} else {
$login_ok = false;
}
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die("[".json_encode($response)."]");
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die("[".json_encode($response)."]");
}
mysql_close($db);
header('Content-Type: text/html; charset=utf-8');
?>