Cleaning up Android Main Activity Code - java

I'm a real noob when it comes to Java and OOP in general. I'm having issues with my app crashing and I think it's because my Main Activity is cluttered and my overall program is not structured properly. Can anyone advise me on how to clean up the following code to make things run smoother and have a better app structure? I think I need to separate things into different classes and keep most of the functions in different classes, but I'm new and really not sure. I keep getting an ANR error when I run the app on a phone (keyDispatchingTimedOut error) and I think my unorganized code is causing this. Any help would be great! Thanks.
package com.example.www;
public class MainActivity extends Activity {
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
private Button send_button;
EditText msgTextField;
private LocationManager locManager;
private LocationListener locListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature( Window.FEATURE_NO_TITLE );
setContentView(R.layout.main);
mDrawer.open();
final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
final String phone = shared.getString("PHONE", "");
String usr_id = shared.getString("USR_ID", null);
if(phone == null) {
TextView text = (TextView)findViewById(R.id.textView1);
text.setText("Please Enter Your Phone Number");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Enter Your Phone Number");
alert.setMessage("You must enter your phone number in order to use this application");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
if (value.length() == 10) {
Editor editor = shared.edit();
editor.putString("PHONE", value);
editor.commit();
}
}
});
alert.show();
}
Button profile = (Button) findViewById(R.id.button1);
profile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, PreferencesActivity.class));
}
});
if (usr_id == null) {
char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
Random r = new Random(System.currentTimeMillis());
char[] id = new char[8];
for (int i = 0; i < 8; i++) {
id[i] = chars[r.nextInt(chars.length)];
}
usr_id = new String(id);
Editor editor = shared.edit();
editor.putString("USR_ID", usr_id);
editor.commit();
}
final String usr_id1 = shared.getString("USR_ID", "none");
send_button = (Button)findViewById(R.id.button2);
send_button.setOnClickListener(new OnClickListener() {
private boolean running = false;
private CountDownTimer timer;
public void onClick(View v) {
if(!running)
{
running = true;
timer = new CountDownTimer(4000, 1000) {
#Override
public void onFinish() {
send_button.setText("GPS Sent");
startLocation();
sendId(usr_id1, phone);
}
#Override
public void onTick(long sec) {
send_button.setText("CANCEL (" + sec / 1000 + ")");
}
}.start();
}
else
{
timer.cancel();
send_button.setText("Send GPS");
running = false;
}
}
});
}
private void startLocation()
{
//get a reference to the LocationManager
locManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get the last known position
Location loc =
locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//show the last known position
//showPosition(loc);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location location) {
showPosition(location);
}
public void onProviderDisabled(String provider){
//labelState.setText("Provider OFF");
}
public void onProviderEnabled(String provider){
//labelState.setText("Provider ON ");
}
public void onStatusChanged(String provider, int status, Bundle extras){
//Log.i("", "Provider Status: " + status);
//labelState.setText("Provider Status: " + status);
}
};
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
private void showPosition(Location loc) {
if(loc != null)
{
Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));
send(loc);
}
}
private void send(Location loc)
{
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
final String usr_id2 = shared.getString("USR_ID", "none");
if (lat != "0" && lon != "0")
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example1.php");
//HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat"
nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line
nameValuePairs.add(new BasicNameValuePair("id", usr_id2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
private void sendId(String usr_id1, String phone)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
//HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive_user.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
nameValuePairs.add(new BasicNameValuePair("id", usr_id1));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
mCloseButton.setOnClickListener( new OnClickListener() {
public void onClick( View v )
{
mDrawer.animateClose();
}
});
mOpenButton.setOnClickListener( new OnClickListener() {
public void onClick( View v )
{
if( !mDrawer.isOpened() )
mDrawer.animateOpen();
}
});
}
#Override
public void onContentChanged()
{
super.onContentChanged();
mCloseButton = (Button) findViewById( R.id.button_open );
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer );
}
}

I would encapsulate the LocationListener in a totally different class. That should shorten up most of your code and leave you with a manageable chunk to work with.
Additionally, you seem to have some HTTP post or web-request methods in your MainActivity. Take those out and put them in a different class as well. Name it something like ActivityServer or something akin to that.
In your ActivityServer class, you should make a callback and asynchronous interfaces so that you don't block the UI thread when doing web requests.

Related

Gcm Notification only comes in my own device

I am new in Gcm and I want to send notification using gcm to my spacific users of my app but notification comes only in my own device
Here is my code
MainActivity.java
public class MainActivity extends ActionBarActivity {
private GoogleCloudMessaging gcm;
String regid;
CheckBox isdriver;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
String user_name = "";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String TAG = "MainActivity";
String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";
Utils utils;
private Context context = MainActivity.this;
private ProgressDialog pb;
private EditText username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
utils = new Utils(this);
isdriver = (CheckBox) findViewById(R.id.isDriver);
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
} catch (IOException ex) {
msg = ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
Log.i(TAG, "onPostExecute : " + msg);
if (!msg.equalsIgnoreCase("SERVICE_NOT_AVAILABLE")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("server_response", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
} else {
utils.showToast("Error : " + msg
+ "\nPlease check your internet connection");
hidePB();
}
}
// Define the Handler that receives messages from the thread and
// update the progress
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString(
"server_response");
if ((null != aResponse)) {
Log.i(TAG, " sendRegistrationIdToBackend();");
sendRegistrationIdToBackend();
} else {
}
}
};
}.execute(null, null, null);
}
/**
* Sends the registration ID to your server over HTTP, so it can use
* GCM/HTTP or CCS to send messages to your app. Not needed for this demo
* since the device sends upstream messages to a server that echoes back the
* message using the 'from' address in the message.
*/
public void sendRegistrationIdToBackend() {
Log.i(TAG, "sendRegistrationIdToBackend");
Thread thread = new Thread() {
#Override
public void run() {
try {
httpclient = new DefaultHttpClient();
// yahan reg id ki server webserivcice dalegi
httppost = new HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/save_reg_id.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username",
user_name));
nameValuePairs.add(new BasicNameValuePair("reg_id", regid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
Log.i(TAG, "Response : " + response);
if (response != null) {
if (response
.equalsIgnoreCase("Username already registered")) {
utils.showToast("Username already registered");
hidePB();
} else {
if (response
.equalsIgnoreCase("New Device Registered successfully")) {
utils.savePreferences(Utils.UserName, user_name);
// Persist the regID - no need to register
// again.
utils.storeRegistrationId(regid);
utils.showToast("Device registration successful");
}
}
}
} catch (Exception e) {
hidePB();
Log.d(TAG, "Exception : " + e.getMessage());
}
}
};
thread.start();
}
public void onClick(View view) {
if (view.getId() == R.id.btnsave) {
username = (EditText) findViewById(R.id.username);
user_name = username.getText().toString().trim();
if (user_name.length() > 0) {
Log.d(TAG, "startRegistration");
showPB("Registering the device");
startRegistration();
/*if(isdriver.isChecked()){
Log.i(TAG,"Driver reg id");
Log.d(TAG, utils.getFromPreferences(user_name));
}*/
Intent i = new Intent(MainActivity.this,BookingActivity.class);
i.putExtra("username",user_name);
i.putExtra("regid",regid);
startActivity(i);
} else {
Log.d(TAG, "Username empty");
}
}
}
void startRegistration() {
if (checkPlayServices()) {
// If this check succeeds, proceed with normal processing.
// Otherwise, prompt user to get valid Play Services APK.
Log.i(TAG, "Google Play Services OK");
gcm = GoogleCloudMessaging.getInstance(this);
regid = utils.getRegistrationId();
/*if(isdriver.isChecked()){
utils.savePreferences(user_name, regid);
Log.d(TAG,utils.getFromPreferences(user_name));
}*/
System.out.println(regid);
if (regid.isEmpty()) {
registerInBackground();
} else {
Log.i(TAG, "Reg ID Not Empty");
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Log.i(TAG, "No Google Play Services...Get it from the store.");
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
void showPB(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pb = new ProgressDialog(MainActivity.this);
pb.setMessage(message);
pb.show();
}
});
}
void hidePB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pb != null && pb.isShowing())
pb.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BookingActivity.java
public class BookingActivity extends ActionBarActivity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
Utils utils;
Intent i;
static String TAG = "GCM DEMO";
String user_name;
String regid;
String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
i = getIntent();
registerReceiver(broadcastReceiver, new IntentFilter(
"CHAT_MESSAGE_RECEIVED"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
String message = b.getString("message");
Log.i(TAG, " Received in Activity " + message + ", NAME = "
+ i.getStringExtra("username"));
}
};
public void onClick(final View view) {
if (view == findViewById(R.id.booking)) {
sendMessage();
//clearMessageTextBox();
}
}
public void sendMessage() {
final String messageToSend = "Driver you are now booked by: "+i.getStringExtra("username");
if (messageToSend.length() > 0) {
Log.i(TAG, "sendMessage");
Thread thread = new Thread() {
#Override
public void run() {
try {
httpclient = new DefaultHttpClient();
httppost = new
HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/gcm_engine.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("message",
messageToSend));
nameValuePairs.add(new BasicNameValuePair(
"registrationIDs", i.getStringExtra("regid")));
nameValuePairs.add(new BasicNameValuePair("apiKey",
API_KEY));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
Log.i(TAG, "Response : " + response);
if (response.trim().isEmpty()) {
Log.d(TAG, "Message Not Sent");
}
} catch (Exception e) {
Log.d(TAG, "Exception : " + e.getMessage());
}
}
};
thread.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_booking, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Utils.java
public class Utils {
static Context context;
public static final String TAG = "Utils";
public static final String UserName = "UserName";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
public Utils(Context context) {
Utils.context = context;
}
public SharedPreferences getGCMPreferences() {
return context.getSharedPreferences(((ActionBarActivity) context)
.getClass().getSimpleName(), Context.MODE_PRIVATE);
}
public void savePreferences(String key, String value) {
final SharedPreferences prefs = getGCMPreferences();
Log.i(TAG, key + " : " + value);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public String getFromPreferences(String key) {
final SharedPreferences prefs = getGCMPreferences();
String value = prefs.getString(key, "");
if (value.isEmpty()) {
Log.i(TAG, key + " not found.");
return "";
}
return value;
}
String getRegistrationId() {
final SharedPreferences prefs = getGCMPreferences();
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
Integer.MIN_VALUE);
int currentVersion = getAppVersion();
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
static int getAppVersion() {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
public void storeRegistrationId(String regId) {
final SharedPreferences prefs = getGCMPreferences();
int appVersion = Utils.getAppVersion();
Log.i(TAG, "Saving regId on app version " + appVersion);
Log.i(TAG, "Reg ID : " + regId);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public String getCurrentIPAddress() {
return "http://192.168.0.101/";
}
public void showToast(final String txt) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, txt, Toast.LENGTH_LONG).show();
}
});
}
}
In my app user login as simple user or login as driver if user login and register with gcm and press booked button notification send to specific driver
It is just because you are calling your own device id to get notified,Please check out the backend , all the registered users must have their own device id's . Make sure their is different device id generated while a new Registration happens.

Android: Start thread, join it and interrupt doesn't work well

I have a problem and I can't find the solution on the internet. I saw a lot of examples but no one really answered to my problem.
I have a login page and then, after checked if the both fields (login/pass) are filled, try to connect by another thread.
public class LoginActivity extends AppCompatActivity {
private EditText login = null;
private EditText password = null;
private RadioButton radioButton = null;
private Button button = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (EditText)findViewById(R.id.loginEditText);
password = (EditText)findViewById(R.id.passwordEditText);
radioButton = (RadioButton)findViewById(R.id.saveRadioButton);
button = (Button)findViewById(R.id.ConnectionButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (login.getText().toString().equals("")
|| password.getText().toString().equals("")) {
alert(getString(R.string.alertDialoguErrorTitle), getString(R.string.UnfilledFieldLogin));
} else {
boolean haveToSave = radioButton.isChecked();
User user = User.getUser(login.getText().toString(), password.getText().toString());
try {
Intranet.login.start();
Intranet.login.join();
Intranet.login.interrupt();
Intranet.login.join();
} catch (InterruptedException e) {
alert(getString(R.string.alertDialoguErrorTitle), e.toString());
login.setText("");
password.setText("");
} finally {
if (!user._token.equals("")) {
if (haveToSave) {
// SAVE DATA
}
finish();
} else {
login.setText("");
password.setText("");
alert(getString(R.string.alertDialoguErrorTitle), getString(R.string.badLoginPassword));
}
}
}
}
});
}
public void alert(String title, String message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// nothing
}
});
alertDialog.show();
}
}
// The class using on the other thread
public class Intranet {
public static int responseCode = 0;
public static String responseString = "";
public static Thread login = new Thread(new Runnable() {
private OkHttpClient client = new OkHttpClient();
private String url = "https://epitech-api.herokuapp.com/login";
private User user = User.getUser();
public void run() {
try {
// Build the request
RequestBody formBody = new FormEncodingBuilder()
.add("login", user._login)
.add("password", user._password)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
// Reset the response code
responseCode = 0;
// Make the request
responses = client.newCall(request).execute();
if ((responseCode = responses.code()) == 200) {
// Get response
String jsonData = responses.body().string();
// Transform reponse to JSon Object
JSONObject json = new JSONObject(jsonData);
// Use the JSon Object
user._token = json.getString("token");
}
} catch (IOException e) {
responseString = e.toString();
} catch (JSONException e) {
responseString = e.toString();
}
;
}
});
}
I tried a lot of solutions with join() which wait the end of the thread. But finally, all time at the second time, when I try to connect myself, an exception comes up (The thread is already started). So how can this thread still running if it's interrupted before continuing?

How to stop the android application sending the pending location to webserver when i clicked on the logout button?

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

How to make following java code Async Task

How to merge following code with Async Task. I see lots of tutorials and make changes in code but unable to do completly. This code is completely fine and working proper but some one advise me to make it Async Task so that when login successful message disappear Move_to_next method is called to start new activity. so please someone add async task code in it so that its work proper.
Code-
public class LoActivity extends Activity {
Intent i;
Button signin;
TextView error;
CheckBox check;
String name="",pass="";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById (R.id.signin);
editTextId = (EditText) findViewById (R.id.editTextId);
editTextP = (EditText) findViewById (R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username","0" );
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if(Str_check.equals("yes"))
{
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
check.setChecked(true);
}
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it's now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString("checked", "yes");
editor.commit();
}
else
{
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next()
{
startActivity(new Intent(LoActivity.this, QnActivity.class));
}
}
All you need to add asyctask call in your signin button click the code is following
Context mContext=this;
String[] result = new String[2];
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
AsyncGetAccessToken aSyncGetToken=new AsyncGetAccessToken();
aSyncGetToken.execute()}});
Make a private class AsyncTask:
private class AsyncGetAccessToken extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... Data) {
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
result[0] = response.getStatusLine().getStatusCode()+"";
result[1] = buffer .toString();
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showLoading();
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
hideLoading();
}
}
for stop loading:
private void hideLoading()
{
if (pDialogTh.isShowing()) {
pDialogTh.cancel();
}
}
for start loading :
private ProgressDialog pDialogTh = null;
private void showLoading()
{
// if(pDialog==null)
pDialogTh = ProgressDialog.show(mContext, "", "Loading...",
true, true);
pDialogTh.setCancelable(false);
if (!pDialogTh.isShowing()) {
pDialogTh.show();
}
}
Try this way
I have edit in your code just copy paste and try
public class LoActivity extends Activity {
Intent i;
Button signin;
TextView error;
CheckBox check;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes")) {
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
check.setChecked(true);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals("")) {
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
} else {
new LoginTask().execute();
}
}
});
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now
// checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked()) {
editor.putString("checked", "yes");
editor.commit();
} else {
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next() {
startActivity(new Intent(LoActivity.this, QnActivity.class));
}
private class LoginTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y') {
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
} else {
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
}
}
Try this:
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}else{
RequestClient reqClient = new RequestClient(ClassName.this);
String AppResponse = null;
AppResponse = reqClient.execute().get()
}
In App response you will get your response change the data type of it as per your requirement.
Create a class RequestClient.java
public class RequestClient extends AsyncTask<String, Void, String>{
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
Im new on android, so in my (little reserchs) ive learn that, if we want make some task that includs network access, or other heavy operation, we need do this on some async task. So in my opinion u can do something like this:
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
...
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
...
YourAsyncClass test = new YourAsyncClass(this);
//you can give various string parameters, in this case, u can send the url, make it an constant
test.execute(YOUR_URL_LIKE_CONSTANT);
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
...
And your YourAsynClass may be like this:
public class YourAsynClass extends AsyncTask<String, Void, String> {
...
public YourAsynClass () {
...
}
//this method is executed before the real task
#Override
protected void onPreExecute() {
super.onPreExecute();
...
//here you can call some load dialog box
}
#Override
protected String doInBackground(String... params){
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
return buffer.toString();
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
//u can hide the load dialog here
}

fetching data from an URL asynchronously

Hi I am writting an android application to get information from a url and show it in a ListView. All are working well. but it takes long time to show the View because i read the file from url on onCreate() method.
I want read from the URL asynchronously, so view response time will not harmed.
Am I using the ProgressBar correctly?.
public class cseWatch extends Activity {
TextView txt1 ;
Button btnBack;
ListView listView1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresult);
Button btnBack=(Button) findViewById(R.id.btn_bck);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent MyIntent1 = new Intent(v.getContext(),cseWatchMain.class);
startActivity(MyIntent1);
}
});
ArrayList<SearchResults> searchResults = GetSearchResults();
//after loaded result hide progress bar
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
final ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}//end of onCreate
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr;
InputStream in;
try{
txt1 = (TextView) findViewById(R.id.txtDisplay);
txt1.setText("Sending request...");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.myurl?reportType=CSV");
HttpResponse response = httpclient.execute(httpget);
in = response.getEntity().getContent();
txt1.setText("parsing CSV...");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
reader.readLine(); //IGNORE FIRST LINE
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
sr = new SearchResults();
String precent = String.format("%.2g%n",Double.parseDouble(RowData[12])).trim();
double chng=Double.parseDouble(RowData[11]);
String c;
if(chng > 0){
sr.setLine2Color(Color.GREEN);
c="▲";
}else if(chng < 0){
sr.setLine2Color(Color.rgb(255, 0, 14));
c="▼";
}else{
sr.setLine2Color(Color.rgb(2, 159, 223));
c="-";
}
sr.setName(c+RowData[2]+"-"+RowData[1]);
DecimalFormat fmt = new DecimalFormat("###,###,###,###.##");
String price = fmt.format(Double.parseDouble(RowData[6])).trim();
String tradevol = fmt.format(Double.parseDouble(RowData[8])).trim();
sr.setLine1("PRICE: Rs."+price+" TRADE VOL:"+tradevol);
sr.setLine2("CHANGE:"+c+RowData[11]+" ("+precent+"%)");
results.add(sr);
txt1.setText("Loaded...");
// do something with "data" and "value"
}
}
catch (IOException ex) {
Log.i("Error:IO",ex.getMessage());
}
finally {
try {
in.close();
}
catch (IOException e) {
Log.i("Error:Close",e.getMessage());
}
}
}catch(Exception e){
Log.i("Error:",e.getMessage());
new AlertDialog.Builder(cseWatch.this).setTitle("Watch out!").setMessage(e.getMessage()).setNeutralButton("Close", null).show();
}
return results;
}
}
AsyncTask should be used to move the heavylifting away from UI thread. http://developer.android.com/reference/android/os/AsyncTask.html
I think you should use a runable.
demo code:
final ListView lv = (ListView) findViewById(R.id.listView1);
Handler handler = new Handler(app.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
}, 1000);
try it.^-^

Categories