I'm trying to show a progress dialog while adding a row to a database table, but the problem is that the progress dialog is only showing for 1 second and the application crashes after that, can anyone help me please ?
public void onClick(View arg0) {
// TODO Auto-generated method stub
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
final EditText wholepost=(EditText)findViewById(R.id.wholepost);
final String post_type=spinner.getSelectedItem().toString();
final String post_type2=post_type.replace(" ", "%20");
final String post1=wholepost.getText().toString();
String post2=post1.replace(" ", "%20");
final String post3=post2.replace("\n","%0D");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
final String now = df.format(new Date());
if(post1.equals(null))
{
Toast.makeText(getBaseContext(), "Please write a post before clicking on the button",Toast.LENGTH_LONG).show();
}
else
{
if(post1.length()<15)
{
Toast.makeText(getBaseContext(), "Post is too small",Toast.LENGTH_LONG).show();
}
else
{
if(post1.length()>500)
{Toast.makeText(getBaseContext(), "Post should be smaller",Toast.LENGTH_LONG).show();}
else
{
pd.show();
Thread th=new Thread(new Runnable() {
public void run() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.1.38/test/Addpost.php?username="+username+"&fname="+firstname+"&lname="+lastname+"&dop="+now+"&content="+post3+"&type="+post_type2+"");
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstN",firstname));
nameValuePairs.add(new BasicNameValuePair("LastN",lastname));
nameValuePairs.add(new BasicNameValuePair("Content",post1));
nameValuePairs.add(new BasicNameValuePair("type",post_type));
nameValuePairs.add(new BasicNameValuePair("Dateofp",now));
nameValuePairs.add(new BasicNameValuePair("username",username));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200)
{
entity=response.getEntity();
if(entity !=null)
{
Toast.makeText(getBaseContext(),"POST SUCCESFULLY ADDED",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getBaseContext(),"ERROR RERTY OR CHECK YOUR CONNECTION",Toast.LENGTH_LONG).show();
}
wholepost.setText("");
}
catch(Exception ex)
{Toast.makeText(getBaseContext(),"CONNECTION ERROR",Toast.LENGTH_LONG).show();}
pd.dismiss();
}
});
th.start();
}}
}
}
else
{
Toast.makeText(getBaseContext(),"Please make sure you're connected to the internet",Toast.LENGTH_LONG).show();
}
}
});
Use Asyntask or otherewise Sleep your thread
Related
when I sent post login data use login button like this :
loginbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String user = email.getText().toString().trim();
final String pwd = password.getText().toString().trim();
if (email.getText().toString().equals("")) {
Utils.toast(context, "Username empty...");
} else if (password.getText().toString().equals("")) {
Utils.toast(context, "Password empty...");
} else if (!isValidEmail(user)) {
email.setError("Invalid Email");
} else if (user.length() < 2) {
Utils.toast(context, "Username to short...");
} else if (pwd.length() < 2) {
Utils.toast(context, "Password to short...");
} else if (!isValidPassword(pwd)) {
password.setError("Invalid Password");
} else {
progress.setVisibility(View.VISIBLE);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(user, pwd);
}
}
});
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "UserLoginTask";
#Override
protected String doInBackground(String... params) {
String user = params[0];
String pwd = params[1];
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("email", user ));
postParameters.add(new BasicNameValuePair("password", pwd ));
String responseString = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.219:90/auth/login");
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(response.getEntity());
Utils.log("daftar isi: " + responseAsText);
JSONObject loginjson = new JSONObject(responseAsText);
Utils.log("json object: " + loginjson);
String roleString = loginjson.getString("role");
Utils.log("role: " + roleString);
if(roleString.equals("member")){
Intent intent = new Intent(context, home.class);
startActivity(intent);
}else if(roleString.equals("studio")){
Intent intent = new Intent(context, VendorDashboard.class);
startActivity(intent);
}
}
catch (Exception e)
{
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
#Override
protected void onPostExecute(String message) {
//process message
}
}
actually it will get feedback JSON response like this :
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNCIsImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMC4yMTk6OTBcL2F1dGhcL2xvZ2luIiwiaWF0IjoiMTQ0NTI0NzIyMSIsImV4cCI6IjE0NDY0NTY4MjEiLCJuYmYiOiIxNDQ1MjQ3MjIxIiwianRpIjoiNTY4MDEyZDUwNTg1NDFjM2UzNGVjMGViYzMzZDkzMGQifQ.zw5c5kLIlvPYIMhEzEnF_fCOu77XTq2prcDtSHJY7bk","role":"studio"}
How to get role (JSON response feedback) so I can use if and else if statement after execute HTTP Post Request (after Utils.toast(context, responseAsText);)?
Update after I used asynctask, it did not produce error onclick.
Update it is done. Thanks mr.shreyash.
Question closed.
I want to send data from Java Android to mysql php server.
This is my code for button click:
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
String result="";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
try {
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", username));
nameValuePairs.add(new BasicNameValuePair("PassWord", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line;
InputStream instream = entity.getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
while ((line = bf.readLine()) != null ) {
sb.append(line).append("\n");
}
result = sb.toString();
Log.i("Read from server", result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
status.setText(username);
//Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
//startActivity(intent);
}
This is my code in login.php:
<?php
include("connect.php");
//define $myusername and $mypassword
$myusername = $_POST['UserName'];
$mypassword = $_POST['PassWord'];
//to protect mysql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$mypassword = $mypassword;
$sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
echo $sql;
$result = mysql_query($sql);
//mysql_num_row is counting table row
$count = mysql_num_rows($result);
echo "<script> alert('".$count."')</script>";
if($count == 1)
{
session_start();
$row = mysql_fetch_array($result);
//$_SESSION['login'] = $myusername;
$_SESSION['id_member'] = $row['id_member'];
header('Location: login.php');
}
else
{
header('Location: default.php');
}
?>
I add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />
But the application was stopped after i run it. I don't know where is the error.
Try doing your networking in an ASyncTask so that your networking isnt done on the UIThread, i think thats why your crashing
something like this
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
}
protected Void doInBackground(Void ...params)
{
loginPost();//View view); // View view replace
// i think even having view as a parameter will crash
// doinbackground method you have to change it i think
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Back to UIThread, i think handle status.setText(username);
// from here and take it out of your loginPost() method UI operations will
// crash doInBackground(Void ...params)
}
}
then call it in your code like this
new TheTask().execute();
EDIT: well all of your views and whatnot will crash doinbackground method use on PreExecute and OnpostExecute for begining and ending with UIOperations
You need to use AsyncTask.
public class UserLogin extends AsyncTask<ArrayList<String>, Void, String> {
protected String doInBackground(ArrayList<String>... userdata) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/script.php");
String result = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", userdata[0].get(0)));
nameValuePairs.add(new BasicNameValuePair("pass", userdata[0].get(1)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
result = total.toString();
}
catch(NoHttpResponseException e){
Log.d("resultLoginError", e.getMessage());
}
catch(Exception e){
Log.d("resultLoginOther", e.toString());
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String result) {
Log.d("resultOnLogin", "LOGGED?");
}
}
public String Login(String user, String pass) throws InterruptedException, ExecutionException{
ArrayList<String> userdata = new ArrayList<String>();
userdata.add(user);
userdata.add(pass);
return new UserLogin().execute(userdata).get();
}
This is what I personally use for login.
script.php is a PHP file that handles POST values (Username and password) and sends back confirmation to app.
On logout button click, a flag is set to zero in my database through http post but i had implemented location listener in the same page (MainActivity.Java) so when a location is updated, it changes the flag value in database to 1.
My Problem is even after i clicked on the logout button, some pending location values are passed to webserver and hence the flag is turned to 1. My question is, how to stop the locationlistner sending pending values after the "logout" button click?
below is my "MainActivity.java" implemented with LocationListner and Logout button also present in same class.
public class MainActivity extends Activity implements LocationListener
{
LocationManager locationManager;
String latitude;
String longitude;
String reverseString=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtLoc = (TextView) findViewById(R.id.textView1);
final int pswd= SaveSharedPreference.getUserId(getBaseContext());
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
try
{
if (SaveSharedPreference.getVehiclenm(getBaseContext()).length()>0)
{
final String vname=SaveSharedPreference.getVehiclenm(getBaseContext());
// Log.v("Set vname",""+vname);
TextView setuser=(TextView) findViewById(R.id.vname);
setuser.setText(vname);
}
if (SaveSharedPreference.getVhColor(getBaseContext()).length()>0)
{
final String vclr=SaveSharedPreference.getVhColor(getBaseContext());
// Log.v("Set vcolor",""+vclr);
TextView setvclr=(TextView) findViewById(R.id.vcolor);
setvclr.setText(vclr);
}
if (SaveSharedPreference.getNumPlate(getBaseContext()).length()>0)
{
final String vplate=SaveSharedPreference.getNumPlate(getBaseContext());
// Log.v("Set vplate",""+vplate);
TextView setvplt=(TextView) findViewById(R.id.nplate);
setvplt.setText(vplate);
}
}
catch (Exception e) {
Log.e("my error", e.toString());
}
Button lgt= (Button) findViewById(R.id.btn_lgt);
lgt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ServerConnection.ip+"logout.jsp");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Log.v("pswd id for logout:",""+pswd);
nameValuePairs.add(new BasicNameValuePair("password", ""+pswd));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
reverseString = response.trim();
// Log.v("Response device id from logout",reverseString);
}
catch (Exception e) {
// Log.e("logout error:",e.toString());
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (AppStatus.getInstance(getBaseContext()).isOnline(getBaseContext())) {
Toast.makeText(getBaseContext(), "Logout Error", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
}
} });
}
if(reverseString!=null){
SaveSharedPreference.clearUserDetails(getBaseContext());
Intent myIntent= new Intent (getBaseContext(),login.class);
startActivity(myIntent);
finish();
}
}
}).start();
}
});
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
TextView txtLoc = (TextView) findViewById(R.id.textView1);
if(latitude==String.valueOf(location.getLatitude())&&longitude==String.valueOf(location.getLongitude()))
{
return;
}
latitude=String.valueOf(location.getLatitude());
longitude=String.valueOf(location.getLongitude());
final int driver_id=SaveSharedPreference.getUserId(getBaseContext());
Thread thread = new Thread() {
#Override
public void run() {
//JSONObject j = new JSONObject();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ServerConnection.ip+"updatedata.jsp");
try {
//j.put("lat",latitude);
//j.put("lon", longitude);
//Toast.makeText(getBaseContext(), ""+j.toString(), Toast.LENGTH_LONG).show();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("lat", latitude));
nameValuePairs.add(new BasicNameValuePair("lon", longitude));
nameValuePairs.add(new BasicNameValuePair("password", ""+pswd));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a jsp application
String reverseString = response.trim();
// Log.v("Response of password",reverseString);
//Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("jsonLocation 0:",e.toString());
}
}
};
thread.start();
// Log.d("Test","test");
//txtLat.setText(location.getLatitude().+location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
// Log.d("Latitude", "disable");
Toast.makeText(getBaseContext(), "Please turn on GPS", Toast.LENGTH_SHORT).show();
Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
// Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
// Log.d("Latitude","status");
}
}
How to stop the locationlistner sending pending location values to webserver after i clicked the logout button?
Any piece of code is appreciated as am new to android and thanks in advance.
When you logout, you need to tell LocationManager that you no longer want updates. Something like --
locationManager.removeUpdates(MainActivity.this)
in your logout button onClickListener.
See LocationManager.removeUpdates
I am designing a service class to update data into the server periodically. Everything is working fine, but I have to send the current UTC date time in this format "MM/dd/yyyy HH:mm:ss" to the server. I have tried a number of ways to achieve this, but they are not giving me the desired results.
Source code of the class:
public class MyAlarmService extends Service {
String device_id;
// GPSTracker class
GPSTracker gps;
String date_time;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();
//---get a Record---
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//Toast.makeText(this, "Service Destroyed.", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
//Toast.makeText(this, "Service Started.", Toast.LENGTH_LONG).show();
//create class object
gps = new GPSTracker(this);
// check if GPS enabled
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String locationUsing = gps.getLocationUsing();
final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = tm.getDeviceId();
// Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// aGMTCalendar.getTimeInMillis(); //or getTimeInMillis()
**Date d = new Date(year);
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());**
// get_date();
**SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
java.util.Date date = null;
System.out.println(dateFormatGmt.format(date));
Toast.makeText(getApplicationContext(),""+date, Toast.LENGTH_LONG).show();**
//Toast.makeText(getApplicationContext(),"Device ID: "+deviceid+ " Time: "+ s+"\nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Log.w( "\nLat: " , ""+latitude);
Log.w( "\nLong: " , ""+longitude);
if(haveNetworkConnection())
{
// sendPostRequest(deviceid,date_time,""+latitude,""+longitude);
// ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
//
// nameValuePairs.add(new BasicNameValuePair("lat",""+latitude));
// nameValuePairs.add(new BasicNameValuePair("lng",""+longitude));
//
//
// try
// {
// HttpClient httpclient = new DefaultHttpClient();
// //HttpPost httppost = new HttpPost("http://eatcastle.com/security_system_portal/api/getting_lat_lng.php");
// HttpPost httppost = new HttpPost("http://google.com");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// HttpResponse response = httpclient.execute(httppost);
// String responseBody = EntityUtils.toString(response.getEntity());
//
// //Toast.makeText( getApplicationContext(),""+responseBody,Toast.LENGTH_LONG).show();
// }
// catch (Throwable t)
// {
// Log.d("Error",""+t);
// }
}
else
{
Toast.makeText( getApplicationContext(),"No Internet connection or Wifi available",Toast.LENGTH_LONG).show();
}
}
else
{
// GPS or Network is not enabled
Toast.makeText(getApplicationContext(), "No Network no GPS", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
// Toast.makeText(this, "Service binded", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
//=======================================================================================================
//check packet data and wifi
//=======================================================================================================
private boolean haveNetworkConnection()
{
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo)
{
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
//=======================================================================================================
//checking packet data and wifi END
//=======================================================================================================
void get_date()
{
}
//sending async post request
private void sendPostRequest(String deviceid, String date_time,String latitude, String longitude) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramDeviceid = params[0];
String paramDate_time = params[1];
String paramLatitude = params[2];
String paramLongitude = params[3];
//System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
//Therefore we use only the web page URL as the parameter of the HttpPost argument
HttpPost httpPost = new HttpPost("http://google.com");
// Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
//uniquely separate by the other end.
//To achieve that we use BasicNameValuePair
//Things we need to pass with the POST request
BasicNameValuePair DeviceidBasicNameValuePair = new BasicNameValuePair("stringLoginUser", paramDeviceid);
BasicNameValuePair Date_timeBasicNameValuePAir = new BasicNameValuePair("stringLoginPwd", paramDate_time);
BasicNameValuePair LatitudeBasicNameValuePAir = new BasicNameValuePair("stringLoginPwd", paramLatitude);
BasicNameValuePair LongitudeBasicNameValuePAir = new BasicNameValuePair("stringLoginPwd", paramLongitude);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(DeviceidBasicNameValuePair);
nameValuePairList.add(Date_timeBasicNameValuePAir);
nameValuePairList.add(LatitudeBasicNameValuePAir);
nameValuePairList.add(LongitudeBasicNameValuePAir);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(deviceid, date_time,latitude,longitude);
}
}
How should I pick up the current utc date time in the above mentioned format and send it to the server?
P.S.: Sometimes while implementing different methods, I also found an IDE error saying new Date() constructor is not defined.
You can use System.currentTimeMillis() , this will return a long number of miliseconds starting from January 1, 1970 00:00:00 UTC. You can use DateFormats to convert Dates to Strings in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
Why are you assigning null to your date value..?
Check this out:
Date formattedDate = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd, hh:mm a", Locale.US);
String time = sdf.format(formattedDate);
i want to ask a question which may is very simple for some of you.
How can i figure out, whether my Application has an internet connection?
I want to connect to an MySQL Database and when there is no Internet, there should be an AlertDialog.
new AsyncTask() {
ProgressDialog dialog = ProgressDialog.show(AppActivity.this, "Lade", "Daten werden abgerufen...", true);
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
max = Name.size()-1;
kontrolle = new boolean [max*2];
pb.setMax(max/2);
java.util.Arrays.fill(kontrolle, false);
bilder();
}
#Override
protected Object doInBackground(Object... arg0)
{
// TODO Auto-generated method stub
dialog.show();
getData();
return null;
}
}.execute();
private void getData()
{
String result = "";
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://.../read.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = "";
while((line= reader.readLine())!=null)
{
sb.append(line+"n");
}
is.close();
result = sb.toString();
result.trim();
}
catch(Exception e)
{
Log.e("log-tag","Error"+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
ID.add((String) json_data.get("id"));
Name.add((String) json_data.get("name"));
Pts.add((String)json_data.get("pts"));
}
}
catch(Exception e)
{
Log.e("log-tag","Error2"+e.toString());
}
}
How can i achieve that? i have no idea
i thought this
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
would do the work, but when i have no connection (because i set my phone in flight mode) there is just an endless ProgressDialog :(
As Jon Taylor mentioned this is a duplicate question
you can use the following code to do this
this method checks whether mobile is connected to internet and returns true if connected and displays an alert box if not:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
AlertDialog.Builder altDialog= new AlertDialog.Builder(this);
altDialog.setMessage("No network connection!");
return false;
} else
return true;
}
add this to the manifest file,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
EDIT: To get the network type you can use this code snippet:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}