Related
I implemented the new autocomplete place sdk in an Android app but it does not show most of places for Nigeria. For example, when I enter spar PH it should show the location SPAR PH, Forces Avenue, Port Harcourt, Nigeria in the suggestion but doesn't. There are other examples that aren't working, too. This was working with the autocomplete Place API but not the new autocomplete .
activity code
public class LocationPickActivity extends BaseActivity
implements OnMapReadyCallback,
GoogleMap.OnCameraMoveListener,
GoogleMap.OnCameraIdleListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationPickIView {
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(new LatLng(-0, 0), new LatLng(0, 0));
private Location mLastKnownLocation;
protected GoogleApiClient mGoogleApiClient;
#BindView(R.id.appbar)
AppBarLayout appbar;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.source)
EditText source;
#BindView(R.id.destination)
EditText destination;
#BindView(R.id.destination_layout)
LinearLayout destinationLayout;
#BindView(R.id.home_address_layout)
LinearLayout homeAddressLayout;
#BindView(R.id.work_address_layout)
LinearLayout workAddressLayout;
#BindView(R.id.home_address)
TextView homeAddress;
#BindView(R.id.work_address)
TextView workAddress;
#BindView(R.id.locations_rv)
RecyclerView locationsRv;
#BindView(R.id.location_bs_layout)
CardView locationBsLayout;
#BindView(R.id.dd)
CoordinatorLayout dd;
boolean isEnableIdle = false;
#BindView(R.id.llSource)
LinearLayout llSource;
private boolean isLocationRvClick = false;
private boolean isSettingLocationClick = false;
private boolean mLocationPermissionGranted;
private GoogleMap mGoogleMap;
private String s_address;
private Double s_latitude;
private Double s_longitude;
private FusedLocationProviderClient mFusedLocationProviderClient;
private BottomSheetBehavior mBottomSheetBehavior;
private Boolean isEditable = true;
private UserAddress home, work = null;
private LocationPickPresenter<LocationPickActivity> presenter = new LocationPickPresenter<>();
private EditText selectedEditText;
private PlacesAutoCompleteAdapter mAutoCompleteAdapter;
//Base on action we are show/hide view and setResults
private String actionName = Constants.LocationActions.SELECT_SOURCE;
PlacesClient placesClient =null;
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
if (isEditable) if (!s.toString().equals("") && mGoogleApiClient.isConnected()) {
locationsRv.setVisibility(View.VISIBLE);
mAutoCompleteAdapter.getFilter().filter(s.toString());
if (mBottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED)
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
} else if (!mGoogleApiClient.isConnected()) Log.e("ERROR", "API_NOT_CONNECTED");
if (s.toString().equals("")) locationsRv.setVisibility(View.GONE);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
#Override
public int getLayoutId() {
return R.layout.activity_location_pick;
}
#Override
public void initView() {
buildGoogleApiClient();
ButterKnife.bind(this);
presenter.attachView(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Places.initialize(getApplicationContext(), getString(R.string.google_map_key));
placesClient = Places.createClient(this);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mBottomSheetBehavior = BottomSheetBehavior.from(locationBsLayout);
mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
}
});
mAutoCompleteAdapter = new PlacesAutoCompleteAdapter(this, R.layout.list_item_location, mGoogleApiClient, BOUNDS_INDIA);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
locationsRv.setLayoutManager(mLinearLayoutManager);
locationsRv.setAdapter(mAutoCompleteAdapter);
source.addTextChangedListener(filterTextWatcher);
destination.addTextChangedListener(filterTextWatcher);
source.setOnFocusChangeListener((view, hasFocus) -> {
if (hasFocus) selectedEditText = source;
});
destination.setOnFocusChangeListener((view, hasFocus) -> {
if (hasFocus) selectedEditText = destination;
});
destination.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
setResult(Activity.RESULT_OK, new Intent());
finish();
return true;
}
return false;
});
source.setText(MvpApplication.RIDE_REQUEST.containsKey(Constants.RIDE_REQUEST.SRC_ADD)
? TextUtils.isEmpty(Objects.requireNonNull(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.SRC_ADD)).toString())
? ""
: String.valueOf(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.SRC_ADD))
: "");
destination.setText(MvpApplication.RIDE_REQUEST.containsKey(Constants.RIDE_REQUEST.DEST_ADD)
? TextUtils.isEmpty(Objects.requireNonNull(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.DEST_ADD)).toString())
? ""
: String.valueOf(MvpApplication.RIDE_REQUEST.get(Constants.RIDE_REQUEST.DEST_ADD))
: "");
locationsRv.addOnItemTouchListener(new RecyclerItemClickListener(this, (view, position) -> {
if (mAutoCompleteAdapter.getItemCount() == 0) return;
final PlacesAutoCompleteAdapter.PlaceAutocomplete item = mAutoCompleteAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i("LocationPickActivity", "Autocomplete item selected: " + item.address);
List<Field> placeFields = Arrays.asList(Field.LAT_LNG);
);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
actionName = bundle.getString("actionName",Constants.LocationActions.SELECT_SOURCE);
if (!TextUtils.isEmpty(actionName) && actionName.equalsIgnoreCase(Constants.LocationActions.SELECT_SOURCE)) {
destination.setCursorVisible(false);
source.setCursorVisible(true);
source.requestFocus();
selectedEditText = source;
}else if (!TextUtils.isEmpty(actionName) && actionName.equalsIgnoreCase(Constants.LocationActions.SELECT_DESTINATION)){
source.setCursorVisible(false);
destination.setCursorVisible(true);
destination.setText("");
destination.requestFocus();
selectedEditText = destination;
}else if (!TextUtils.isEmpty(actionName) && actionName.equals(Constants.LocationActions.CHANGE_DESTINATION)){
llSource.setVisibility(View.GONE);
source.setHint(getString(R.string.select_location));
selectedEditText = destination;
}else if (!TextUtils.isEmpty(actionName) && (actionName.equals(Constants.LocationActions.SELECT_HOME)|| actionName.equals(Constants.LocationActions.SELECT_WORK))){
destinationLayout.setVisibility(View.GONE);
selectedEditText = destination;
source.setText("");
source.setHint(getString(R.string.select_location));
} else{
destinationLayout.setVisibility(View.VISIBLE);
llSource.setVisibility(View.VISIBLE);
source.setHint(getString(R.string.pickup_location));
selectedEditText = source;
}
}
presenter.address();
}
private void setLocationText(String address, LatLng latLng, boolean isLocationRvClick,
boolean isSettingLocationClick) {
if (address != null && latLng != null) {
isEditable = false;
selectedEditText.setText(address);
isEditable = true;
if (selectedEditText.getTag().equals("source")) {
s_address = address;
s_latitude = latLng.latitude;
s_longitude = latLng.longitude;
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.SRC_ADD, address);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.SRC_LAT, latLng.latitude);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.SRC_LONG, latLng.longitude);
}
if (selectedEditText.getTag().equals("destination")) {
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.DEST_ADD, address);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.DEST_LAT, latLng.latitude);
MvpApplication.RIDE_REQUEST.put(Constants.RIDE_REQUEST.DEST_LONG, latLng.longitude);
if (isLocationRvClick) {
// Done functionality called...
setResult(Activity.RESULT_OK, new Intent());
finish();
}
}
} else {
isEditable = false;
selectedEditText.setText("");
locationsRv.setVisibility(View.GONE);
isEditable = true;
if (selectedEditText.getTag().equals("source")) {
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.SRC_ADD);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.SRC_LAT);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.SRC_LONG);
}
if (selectedEditText.getTag().equals("destination")) {
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.DEST_ADD);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.DEST_LAT);
MvpApplication.RIDE_REQUEST.remove(Constants.RIDE_REQUEST.DEST_LONG);
}
}
if (isSettingLocationClick) {
hideKeyboard();
locationsRv.setVisibility(View.GONE);
}
}
#Override
public void onResume() {
super.onResume();
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
Log.v("Google API", "Connecting");
mGoogleApiClient.connect();
}
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
Log.v("Google API", "Dis-Connecting");
mGoogleApiClient.disconnect();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#OnClick({R.id.source, R.id.destination, R.id.reset_source, R.id.reset_destination, R.id.home_address_layout, R.id.work_address_layout})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.source:
break;
case R.id.destination:
break;
case R.id.reset_source:
selectedEditText = source;
source.requestFocus();
setLocationText(null, null, isLocationRvClick, isSettingLocationClick);
break;
case R.id.reset_destination:
destination.requestFocus();
selectedEditText = destination;
setLocationText(null, null, isLocationRvClick, isSettingLocationClick);
break;
case R.id.home_address_layout:
if (home != null)
setLocationText(home.getAddress(),
new LatLng(home.getLatitude(), home.getLongitude()),
isLocationRvClick, isSettingLocationClick);
break;
case R.id.work_address_layout:
if (work != null)
setLocationText(work.getAddress(),
new LatLng(work.getLatitude(), work.getLongitude()),
isLocationRvClick, isSettingLocationClick);
break;
}
}
#Override
public void onCameraIdle() {
try {
CameraPosition cameraPosition = mGoogleMap.getCameraPosition();
if (isEnableIdle) {
String address = getAddress(cameraPosition.target);
System.out.println("onCameraIdle " + address);
hideKeyboard();
setLocationText(address, cameraPosition.target, isLocationRvClick, isSettingLocationClick);
}
isEnableIdle = true;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCameraMove() {
System.out.println("LocationPickActivity.onCameraMove");
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
// Google map custom style...
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));
} catch (Resources.NotFoundException e) {
Log.d("Map:Style", "Can't find style. Error: ");
}
this.mGoogleMap = googleMap;
getLocationPermission();
updateLocationUI();
getDeviceLocation();
}
void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, task -> {
if (task.isSuccessful() && task.getResult() != null) {
mLastKnownLocation = task.getResult();
mGoogleMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(
mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()
), DEFAULT_ZOOM));
} else {
Log.d("Map", "Current location is null. Using defaults.");
Log.e("Map", "Exception: %s", task.getException());
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
public void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
mLocationPermissionGranted = true;
else
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_ACCESS_FINE_LOCATION);
}
private void updateLocationUI() {
if (mGoogleMap == null) return;
try {
if (mLocationPermissionGranted) {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mGoogleMap.setOnCameraMoveListener(this);
mGoogleMap.setOnCameraIdleListener(this);
} else {
mGoogleMap.setMyLocationEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionGranted = false;
if (requestCode == REQUEST_ACCESS_FINE_LOCATION)
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
updateLocationUI();
getDeviceLocation();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
Log.v("Google API Callback", "Connection Suspended");
Log.v("Code", String.valueOf(i));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.v("Error Code", String.valueOf(connectionResult.getErrorCode()));
Toast.makeText(this, "API_NOT_CONNECTED", Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED)
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
else super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.location_pick_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_done:
if (!TextUtils.isEmpty(actionName) && actionName.equals(Constants.LocationActions.SELECT_HOME) || actionName.equals(Constants.LocationActions.SELECT_WORK)){
Intent intent = new Intent();
intent.putExtra(Constants.RIDE_REQUEST.SRC_ADD, s_address);
intent.putExtra(Constants.RIDE_REQUEST.SRC_LAT, s_latitude);
intent.putExtra(Constants.RIDE_REQUEST.SRC_LONG, s_longitude);
setResult(Activity.RESULT_OK, intent);
finish();
} else {
setResult(Activity.RESULT_OK, new Intent());
finish();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onSuccess(AddressResponse address) {
if (address.getHome().isEmpty()) homeAddressLayout.setVisibility(View.GONE);
else {
home = address.getHome().get(address.getHome().size() - 1);
homeAddress.setText(home.getAddress());
homeAddressLayout.setVisibility(View.VISIBLE);
}
if (address.getWork().isEmpty()) workAddressLayout.setVisibility(View.GONE);
else {
work = address.getWork().get(address.getWork().size() - 1);
workAddress.setText(work.getAddress());
workAddressLayout.setVisibility(View.VISIBLE);
}
}
#Override
public void onError(Throwable e) {
handleError(e);
}
#Override
protected void onDestroy() {
presenter.onDetach();
super.onDestroy();
}
}
public class PlacesAutoCompleteAdapter extends RecyclerView.Adapter<PlacesAutoCompleteAdapter.PredictionHolder> implements Filterable {
private static final String TAG = "PlacesAutoAdapter";
private ArrayList<PlaceAutocomplete> mResultList = new ArrayList<>();
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private Context mContext;
private int layout;
private CharacterStyle STYLE_BOLD;
private CharacterStyle STYLE_NORMAL;
PlacesClient placesClient =null;
public PlacesAutoCompleteAdapter(Context context, int resource, GoogleApiClient googleApiClient, LatLngBounds bounds) {
mContext = context;
layout = resource;
mGoogleApiClient = googleApiClient;
mBounds = bounds;
STYLE_BOLD = new StyleSpan(Typeface.BOLD);
STYLE_NORMAL = new StyleSpan(Typeface.NORMAL);
if (!Places.isInitialized()) {
Places.initialize(context, context.getString(R.string.google_api_key));
}
placesClient = Places.createClient(context);
}
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
/**
* Returns the filter for the current set of autocomplete results.
*/
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutocomplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
//notifyDataSetInvalidated();
}
}
};
}
private ArrayList getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i("", "Starting autocomplete query for: " + constraint);
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
ArrayList<PlaceAutocomplete> resultList = new ArrayList<>();
placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getPrimaryText(STYLE_NORMAL),
prediction.getFullText(STYLE_BOLD)));
}
}).addOnFailureListener((exception) -> {
return resultList;
}
Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
#NonNull
#Override
public PredictionHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = Objects.requireNonNull(layoutInflater).inflate(layout, viewGroup, false);
return new PredictionHolder(convertView);
}
#Override
public void onBindViewHolder(#NonNull PredictionHolder mPredictionHolder, final int i) {
mPredictionHolder.area.setText(mResultList.get(i).area);
mPredictionHolder.address.setText(mResultList.get(i).address.toString()
.replace(mResultList.get(i).area + ", ", ""));
}
#Override
public int getItemCount() {
return (mResultList == null) ? 0 : mResultList.size();
}
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
class PredictionHolder extends RecyclerView.ViewHolder {
private TextView address, area;
PredictionHolder(View itemView) {
super(itemView);
area = itemView.findViewById(R.id.area);
address = itemView.findViewById(R.id.address);
}
}
public class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence address, area;
PlaceAutocomplete(CharSequence placeId, CharSequence area, CharSequence address) {
this.placeId = placeId;
this.area = area;
this.address = address;
}
#Override
public String toString() {
return area.toString();
}
}
}
The Place Picker is deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019, and will no longer be available after that date. You must install the compatibility library to continue using the Place Picker during the deprecation period. Once the deprecation period has ended, the Place Picker will no longer be available for use (including the version in the compatibility library).
I am facing a Null pointer Exception while calling Create report (which in turns calls its Asynctask "createReportTask" situated inside the Activity) But the application crashes giving NPE in the other fragment's Asynsc task (situated inside fragment) , I have tried passing context in constructor etc getContext(), getAcitivity() etc but all in vain. I am attaching Logs and Code please help!!
Logs:
05-24 12:56:11.505 14632-14632/com.example.aiousecurityapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aiousecurityapplication, PID: 14632
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.widget.Toast.<init>(Toast.java:121)
at android.widget.Toast.makeText(Toast.java:291)
at android.widget.Toast.makeText(Toast.java:281)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:439)
at com.example.aiousecurityapplication.Activities.EventsReportFragment$MakeRequestTask.onPostExecute(EventsReportFragment.java:377)
at android.os.AsyncTask.finish(AsyncTask.java:727)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:744)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Create Report Code:
public class CreateReport extends AppCompatActivity {
public EditText eventDate;
public EditText eventTime;
EditText reporterName;
EditText reporterCnic;
int flag = 0;
public static Calendar userCalendar;
private String Lat, Long;
private static final String[] BLOCK = new String[]{"Block 1", "Block 2", "Block 3", "Block 4", "Block 5"};
private static final String[] sampleDesc = new String[]{"Aag Lagi ha", "Darwaza Khula h", "Tala Ni Laga", "Lights / Fan On hain"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_report);
Button createReport = (Button) findViewById(R.id.createReport);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ActionBar ab = getSupportActionBar();
ab.setTitle("Create Report");
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Lat = bundle.getString("lat");
Toast.makeText(getContext(), "Latitude" + Lat, Toast.LENGTH_LONG).show();
Long = bundle.getString("Long");
}
createReport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (eventDescription.getText().toString().length() < 3) {
eventDescription.setError("Minimum 5 Letters");
Toast.makeText(getApplicationContext(),
"Please some Description", Toast.LENGTH_SHORT)
.show();
} else {
// creating new product in background thread
String blockname = blockName.getSelectedItem().toString().trim();
String eventEsc = eventEsclation.getSelectedItem().toString().trim();
String eventdesc = eventDescription.getText().toString().trim();
String cnic = reporterCnic.getText().toString().trim();
String userLat = Lat;
String userLong = Long;
String date = eventDate.getText().toString().trim();
String time = eventTime.getText().toString().trim();
new createReportTask().execute(blockname, eventEsc, eventdesc, cnic, userLat, userLong, date, time);
}
}
});
}
public class createReportTask extends AsyncTask<String, String, JSONObject> {
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Creating Report", "in Pre Execute");
pDialog = new ProgressDialog(CreateReport.this);
pDialog.setMessage("Creating Report");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
pDialog.dismiss();
Toast.makeText(CreateReport.this, "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 2) {
Toast.makeText(CreateReport.this, message, Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Creating product
*/
protected JSONObject doInBackground(String... args) {
String blockName = args[0] != null ? args[0] : "";
String eventEscalation = args[1];
String eventDesc = args[2];
String userCnic = args[3];
String userLat = args[4];
String userLong = args[5];
String date = args[6];
String time = args[7];
if (blockName.trim().length() != 0 && eventEscalation.trim().length() != 0
&& eventDesc.trim().length() != 0 && userCnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
//db field name in value side
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("page", "datasync"));
params.add(new BasicNameValuePair("blockName", blockName));
params.add(new BasicNameValuePair("eventEscalation", eventEscalation));
params.add(new BasicNameValuePair("eventDesc", eventDesc));
params.add(new BasicNameValuePair("userCnic", userCnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
// getting JSON Object
// Note that create product url accepts POST method
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} else {
return null;
}
}
}
}
Fragment Code:
public class EventsReportFragment extends Fragment {
static final int REQUEST_AUTHORIZATION = 1001;
private RecyclerView recyclerView;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private boolean mAlreadyStartedService = false;
private TextView mMsgView;
View rootView;
String latitude;
String longitude;
String myFormat1 = "yyyy-MM-dd";
String myFormat2 = "HH:mm:ss";
SimpleDateFormat mainSdf1 = new SimpleDateFormat(myFormat1, Locale.US);
SimpleDateFormat mainSdf2 = new SimpleDateFormat(myFormat2, Locale.US);
public EventsReportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mMsgView = (TextView) rootView.findViewById (R.id.msgView);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateReport.class);
intent.putExtra("lat", latitude);
intent.putExtra("long", longitude);
startActivity(intent);
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
startStep1();
}
/**
* Step 1: Check Google Play services
*/
private void startStep1() {
//Check whether this user has installed Google play service which is being used by Location updates.
if (isGooglePlayServicesAvailable()) {
//Passing null to indicate that it is executing for the first time.
startStep2(null);
} else {
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
}
}
/**
* Step 2: Check & Prompt Internet connection
*/
private Boolean startStep2(DialogInterface dialog) {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
promptInternetConnect();
return false;
}
if (dialog != null) {
dialog.dismiss();
}
if (checkPermissions()) { //Yes permissions are granted by the user. Go to the next step.
startStep3();
} else { //No user has not granted the permissions yet. Request now.
requestPermissions();
}
return true;
}
/**
* Show A Dialog with button to refresh the internet state.
*/
private void promptInternetConnect() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("title_alert_no_intenet");
builder.setMessage("msg_alert_no_internet");
String positiveText = "Refresh Button";
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Block the Application Execution until user grants the permissions
if (startStep2(dialog)) {
//Now make sure about location permission.
if (checkPermissions()) {
//Step 2: Start the Location Monitor Service
//Everything is there to start the service.
startStep3();
} else if (!checkPermissions()) {
requestPermissions();
}
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Step 3: Start the Location Monitor Service
*/
private void startStep3() {
//And it will be keep running until you close the entire application from task manager.
//This method will executed only once.
if (!mAlreadyStartedService && mMsgView != null) {
mMsgView.setText("Location_service_started");
//Start location sharing service to app server.........
Intent intent = new Intent(getContext(), LocationMonitoringService.class);
getActivity().startService(intent);
mAlreadyStartedService = true;
//Ends................................................
}
}
/**
* Return the availability of GooglePlayServices
*/
public boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(getContext());
if (status != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(getActivity(), status, 2404).show();
}
return false;
}
return true;
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
int permissionState1 = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
int permissionState2 = ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
}
/**
* Start permissions requests.
*/
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION);
boolean shouldProvideRationale2 =
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION);
// Provide an additional rationale to the img_user. This would happen if the img_user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale || shouldProvideRationale2) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale,
android.R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
});
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the img_user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
/**
* Shows a {#link Snackbar}.
*
* #param mainTextStringId The id for the string resource for the Snackbar text.
* #param actionStringId The text of the action item.
* #param listener The listener associated with the Snackbar action.
*/
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(
rootView.findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If img_user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission granted, updates requested, starting location updates");
startStep3();
} else {
showSnackbar(R.string.permission_denied_explanation,
R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
#Override
public void onDestroy() {
//Stop location sharing service to app server.........
getActivity().stopService(new Intent(getActivity(), LocationMonitoringService.class));
mAlreadyStartedService = false;
//Ends................................................
super.onDestroy();
}
public class MakeRequestTask extends AsyncTask<String, String, JSONObject> {
private Exception mLastError = null;
private JSONSenderReceiver jsonparser = new JSONSenderReceiver();
public MakeRequestTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
String cnic = args[0];
String userLat = args[1];
String userLong = args[2];
String date = args[3];
String time = args[4];
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (cnic.trim().length() != 0 && userLat.trim().length() != 0
&& userLong.trim().length() != 0 && date.trim().length() != 0 && time.trim().length() != 0) {
params.add(new BasicNameValuePair("page", "locationUpdate"));
params.add(new BasicNameValuePair("cnic", cnic));
params.add(new BasicNameValuePair("userLat", userLat));
params.add(new BasicNameValuePair("userLong", userLong));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("time", time));
}
return jsonparser.makeHttpRequest(AppConfig.URL_MAIN, "POST", params);
} catch (Exception e) {
e.printStackTrace();
mLastError = e;
cancel(true);
return null;
}
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result == null) {
Toast.makeText(getContext(), "No response from server.", Toast.LENGTH_SHORT).show();
return;
}
Log.d("Response from server: ", result.toString());
int success = Integer.parseInt(result.getString("status"));
String message = result.getString("message");
if (success == 1) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
} else if (success == 2){
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCancelled() {
}
}
}``
In onPostExecute check for activity is running before doing any work.
because onPostExecute may be called if activity was running not more
Try this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events_list, container, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LATITUDE);
longitude = intent.getStringExtra(LocationMonitoringService.EXTRA_LONGITUDE);
new MakeRequestTask().execute(AppSettings.getUserCnic(), latitude, longitude,
mainSdf1.format(Calendar.getInstance().getTime()),
mainSdf2.format(Calendar.getInstance().getTime()));
if (latitude != null && longitude != null) {
mMsgView.setText("msg_location_service_started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);
}
}
}, new IntentFilter(LocationMonitoringService.ACTION_LOCATION_BROADCAST)
);
//your remaining code here
}
Use following line:
String message = result.optString("message");
// it will returns the empty string ("") if the key you specify doesn't exist
instead of using
String message = result.getString("message");
// it will throws exception if the key you specify doesn't exist
replace getContext() with getActivity() inside your fragment
e.g replace
Toast.makeText(getContext(), "no_google_playservice_available", Toast.LENGTH_LONG).show();
with
`Toast.makeText(getActivity(), "no_google_playservice_available", Toast.LENGTH_LONG).show();`
and
LocalBroadcastManager.getInstance(getContext()).registerReceiver(
with
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
and so on if any.
I have found a tutorial about gps location service.
Every thing works fine.
The next thing I want to write is passing coordinates form app to mysql.
I have tried several tutorial about android mysql but i dont know how to applied them to this code.
What I am trying to achieve is to onLocationChanged send latitude and longitude to database.
Could someone tell me how to do this?
This is the code:
connect.php
<?php
define('HOST','localhost');
define('USER','');
define('PASS','');
define('DB','coordinates');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
insert.php
<?php
require_once('connect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$la = $_POST['la_string'];
$lo = $_POST['lo_string'];
$get_result = $con->query("INSERT INTO gps(la,lo) VALUES ('$la','$lo')");
if($get_result === true){
echo "Successfully Registered";
}else{
echo "Not Registered";
}
}else{
echo 'error';
}
?>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button start, stop, exit;
private TextView data_lo, text_lo, text_la, data_la;
private BroadcastReceiver broadcastReceiver;
private String la_string,lo_string;
#Override
protected void onResume() {
super.onResume();
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
data_la.setText("" + intent.getExtras().get("latitude"));
data_lo.setText("" + intent.getExtras().get("longitude"));
}
};
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);
data_la = (TextView) findViewById(R.id.data_la);
data_lo = (TextView) findViewById(R.id.data_lo);
text_la = (TextView) findViewById(R.id.text_la);
text_lo = (TextView) findViewById(R.id.text_lo);
exit = (Button) findViewById(R.id.exit);
if(!runtime_permissions())
enable_buttons();
}
private void enable_buttons() {
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}}
GPS_Service.java
public class GPS_Service extends Service {
private LocationListener locationListener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("latitude", location.getLatitude());
i.putExtra("longitude", location.getLongitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(locationListener);
}
}}
You have to make a call via HttpClient to your server and send your data through that as Post with your data encoded.
try{
String data = URLEncoder.encode("la_string", "UTF-8") + "=" +
URLEncoder.encode(data_la.text, "UTF-8");
data += "&" + URLEncoder.encode("lo_string", "UTF-8") + "=" +
URLEncoder.encode(data_lo.text, "UTF-8");
URL url = new URL(URL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response if you have something to do with it
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
You can see a complete example here: https://www.tutorialspoint.com/android/android_php_mysql.htm
First time I am using GoogleApiClient and want to upload all the text messages to google drive when the share button in the app is clicked. But the data is not uploading on the drive.
MainActivity :
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
SmsAdapter adapter;
FloatingActionButton fab;
Cursor c;
ExportTask task;
ArrayList<CustomSms> smslistSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
smslistSearch = new ArrayList<>();
rv = (RecyclerView) findViewById(R.id.messages_view);
LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
rv.setLayoutManager(llm);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i =new Intent(MainActivity.this,SendSms.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
final ArrayList<CustomSms> smslist, smsgrouplist;
smslist = new ArrayList<>();
smsgrouplist = new ArrayList<>();
//Fetch inobx sms message
c = getContentResolver().query(SmsApplication.INBOX_URI, null, null, null, null);
while (c.moveToNext()) {
String address = c.getString(c.getColumnIndexOrThrow("address"));
String date = c.getString(c.getColumnIndexOrThrow("date"));
String body = c.getString(c.getColumnIndexOrThrow("body"));
smslist.add(new CustomSms(address, date, body));
}
smslistSearch = smslist;
Map<String, CustomSms> map = new LinkedHashMap<>();
for (CustomSms ays : smslist) {
CustomSms existingValue = map.get(ays.address);
if(existingValue == null){
map.put(ays.address, ays);
}
}
smsgrouplist.clear();
smsgrouplist.addAll(map.values());
adapter = new SmsAdapter(MainActivity.this);
adapter.updateList(smsgrouplist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
ArrayList<CustomSms> smsinsidegroup = new ArrayList<CustomSms>();
String n = smsgrouplist.get(position).address;
for (int i = 0; i < smslist.size(); i++) {
if(smslist.get(i).address.equals(n))
smsinsidegroup.add(smslist.get(i));
}
Intent i = new Intent(MainActivity.this, ReadAllSms.class);
i.putParcelableArrayListExtra("messages", smsinsidegroup);
startActivity(i);
}
})
);
}
catch (Exception e)
{
e.printStackTrace();
}
}
class ExportTask extends AsyncTask<Void, Integer, Uri> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Exporting to file ...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(0);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Uri doInBackground(Void... params) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
fos = new FileOutputStream(f);
int count = c.getCount(), i = 0;
StringBuilder sb = new StringBuilder();
if (c.moveToFirst()) {
do {
sb.append(c.getString(c.getColumnIndex("address")))
.append("\n");
sb.append(c.getString(c.getColumnIndex("body")))
.append("\n");
sb.append("\n");
publishProgress(++i*100/count);
} while (!isCancelled() && c.moveToNext());
}
fos.write(sb.toString().getBytes());
return Uri.fromFile(f);
} catch (Exception e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Uri result) {
super.onPostExecute(result);
pDialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "Export task failed!",
Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);
}
}
#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_search) {
Intent i = new Intent(MainActivity.this,SearchActivity.class);
i.putParcelableArrayListExtra("search", smslistSearch);
startActivity(i);
return true;
}
if (id == R.id.action_share) {
/*Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);*/
task = new ExportTask();
task.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
if (task != null) {
task.cancel(false);
task.pDialog.dismiss();
}
super.onPause();
}
}
UploadData :
public class UploadData extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "upload_file";
private static final int REQUEST_CODE = 101;
private File textFile;
private GoogleApiClient googleApiClient;
public static String drive_id;
public static DriveId driveID;
FrameLayout rl;
TextView success;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_data);
rl = (FrameLayout) findViewById(R.id.frame);
success = (TextView) findViewById(R.id.success);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBackOrig));
textFile = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "connecting...");
googleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (googleApiClient != null) {
Log.i(TAG, "disConnecting...");
googleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Log.i(TAG, "In onActivityResult() - connecting...");
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "in onConnected() - connected");
Drive.DriveApi.newDriveContents(googleApiClient)
.setResultCallback(driveContentsCallback);
}
#Override
public void onConnectionSuspended(int cause) {
switch (cause) {
case 1:
Log.i(TAG, "Connection suspended - Cause: " + "Service disconnected");
break;
case 2:
Log.i(TAG, "Connection suspended - Cause: " + "Connection lost");
break;
default:
Log.i(TAG, "Connection suspended - Cause: " + "Unknown");
break;
}
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Error creating the new file of contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
new Thread() {
#Override
public void run() {
OutputStream outputStream = driveContents.getOutputStream();
addTextfileToOutputStream(outputStream);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("SmsBackup")
.setMimeType("text/plain")
.setDescription("This is a text file uploaded from device")
.setStarred(true).build();
Drive.DriveApi.getRootFolder(googleApiClient)
.createFile(googleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
private void addTextfileToOutputStream(OutputStream outputStream) {
byte[] buffer = new byte[1024];
int bytesRead;
try {
BufferedInputStream inputStream = new BufferedInputStream(
new FileInputStream(textFile));
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(UploadData.this,
"Error adding file to Drive", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(UploadData.this,
"File successfully added to Drive", Toast.LENGTH_SHORT).show();
showProgress(false);
rl.setBackgroundColor(getResources().getColor(R.color.colorBack));
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBack));
success.setVisibility(View.VISIBLE);
final PendingResult<DriveResource.MetadataResult> metadata
= result.getDriveFile().getMetadata(googleApiClient);
metadata.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
Metadata data = metadataResult.getMetadata();
drive_id = data.getDriveId().encodeToString();
driveID = data.getDriveId();
}
});
}
};
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
}
}
private void buildGoogleApiClient() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
progressBar.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
You might want to check on how you work with File Contents, first you might want to check if there is a value on the variable textFile that you have set.
The example below illustrates how to append "hello world" to the DriveContents.
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
} catch (IOException e) {
e.printStackTrace();
}
There is a related SO question - Upload text file to Google Drive using Android that you might want to check out. The answer in the question reminds the OP regarding how to feed the file with contents.
Lastly, you might want to check this github. This code show how to insert the content of the chat into a file and save it to the drive.
Hope this helps.
I have implemented Twilio in my android app for outgoing and incoming calls. But I'm facing an issue while getting incoming call with the background service. The issue is that I get calls in first 30-40 mins only. After sometime phone stops getting incoming calls. I tried so much. Please respond me soon. I'm sharing code with you too.
I get token from a background service which generates token after a time period.
IncomingCallService.java
public class IncomingCallService extends Service implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static Handler handler, handler_login;
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
Ringtone r;
Uri notification;
public static final String LOGIN_DETAILS = "XXXXXXXX";
AudioManager am;
Intent intent;
public static String DEFAULT_CLIENT_NAME = "developer";
static String Twilio_id = "",
INCOMING_AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT
+ MenuItems.Twilio_id;
Runnable newrun;
Activity context;
Context ctx;
static String op_id = "";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
handler_login = new Handler();
handler_login.postDelayed(new Runnable() {
#Override
public void run() {
Login();
handler_login.postDelayed(this, 20000);
}
}, 1000);
}
public void Login() {
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, true, true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.intent = intent;
// I know getIntent always return NULL in service
if (intent != null) {
op_id = intent.getStringExtra("operator_id");
onCallHandler();
}
return START_STICKY;
}
public void onCallHandler() {
handler = new Handler();
newrun = new Runnable() {
#Override
public void run() {
handler.removeCallbacks(newrun);
new IncomingTokenTask().execute();
if (phone.handleIncomingIntent(intent)) {
}
handler.postDelayed(this, 2000000);
}
};
handler.postDelayed(newrun, 8000000);
}
class IncomingTokenTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
}
}
The BasicPhone class of twilio
public class IncomingPhone implements DeviceListener, ConnectionListener {
private static final String TAG = "IncomingPhone";
static String decodedString = "";
static String capabilityToken = "";
// TODO: change this to point to the script on your public server
private static final String AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT+MenuItems.Twilio_id;
public interface LoginListener {
public void onLoginStarted();
public void onLoginFinished();
public void onLoginError(Exception error);
}
public interface BasicConnectionListener {
public void onIncomingConnectionDisconnected();
public void onConnectionConnecting();
public void onConnectionConnected();
public void onConnectionFailedConnecting(Exception error);
public void onConnectionDisconnecting();
public void onConnectionDisconnected();
public void onConnectionFailed(Exception error);
}
public interface BasicDeviceListener {
public void onDeviceStartedListening();
public void onDeviceStoppedListening(Exception error);
}
private static IncomingPhone instance;
public static final IncomingPhone getInstance(Context context) {
if (instance == null)
instance = new IncomingPhone(context);
return instance;
}
private final Context context;
private LoginListener loginListener;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private static boolean twilioSdkInited;
private static boolean twilioSdkInitInProgress;
private boolean queuedConnect;
private Device device;
private Connection pendingIncomingConnection;
private Connection connection;
private boolean speakerEnabled;
private String lastClientName;
private boolean lastAllowOutgoing;
private boolean lastAllowIncoming;
private IncomingPhone(Context context) {
this.context = context;
}
public void setListeners(LoginListener loginListener,
BasicConnectionListener basicConnectionListener,
BasicDeviceListener basicDeviceListener) {
this.loginListener = loginListener;
this.basicConnectionListener = basicConnectionListener;
this.basicDeviceListener = basicDeviceListener;
}
private void obtainCapabilityToken(String clientName,
boolean allowOutgoing, boolean allowIncoming) {
StringBuilder url = new StringBuilder();
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient httpclient = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory
.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(
httpclient.getParams(), registry);
#SuppressWarnings("unused")
DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
httpclient.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
url.append(AUTH_PHP_SCRIPT);
// This runs asynchronously!
new GetAuthTokenAsyncTask().execute(url.toString());
}
private boolean isCapabilityTokenValid() {
if (device == null || device.getCapabilities() == null)
return false;
long expTime = (Long) device.getCapabilities().get(
Capability.EXPIRATION);
return expTime - System.currentTimeMillis() / 1000 > 0;
}
//
private void updateAudioRoute() {
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(speakerEnabled);
}
public void login(final String clientName, final boolean allowOutgoing,
final boolean allowIncoming) {
if (loginListener != null)
loginListener.onLoginStarted();
this.lastClientName = clientName;
this.lastAllowOutgoing = allowOutgoing;
this.lastAllowIncoming = allowIncoming;
if (!twilioSdkInited) {
if (twilioSdkInitInProgress)
return;
twilioSdkInitInProgress = true;
Twilio.setLogLevel(Log.DEBUG);
Twilio.initialize(context, new Twilio.InitListener() {
#Override
public void onInitialized() {
twilioSdkInited = true;
twilioSdkInitInProgress = false;
obtainCapabilityToken(clientName, allowOutgoing,
allowIncoming);
}
#Override
public void onError(Exception error) {
twilioSdkInitInProgress = false;
if (loginListener != null)
loginListener.onLoginError(error);
}
});
} else {
obtainCapabilityToken(clientName, allowOutgoing, allowIncoming);
}
}
private void reallyLogin(final String capabilityToken) {
try {
if (device == null) {
device = Twilio.createDevice(capabilityToken, this);
Intent intent = new Intent(context, IncomingPhoneActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
device.setIncomingIntent(pendingIntent);
} else
device.updateCapabilityToken(capabilityToken);
if (loginListener != null)
loginListener.onLoginFinished();
if (queuedConnect) {
// If someone called connect() before we finished initializing
// the SDK, let's take care of that here.
connect(null);
queuedConnect = false;
}
} catch (Exception e) {
if (device != null)
device.release();
device = null;
if (loginListener != null)
loginListener.onLoginError(e);
}
}
public void setSpeakerEnabled(boolean speakerEnabled) {
if (speakerEnabled != this.speakerEnabled) {
this.speakerEnabled = speakerEnabled;
updateAudioRoute();
}
}
public void connect(Map<String, String> inParams) {
if (twilioSdkInitInProgress) {
// If someone calls connect() before the SDK is initialized, we'll
// remember
// that fact and try to connect later.
queuedConnect = true;
return;
}
if (!isCapabilityTokenValid())
login(lastClientName, lastAllowOutgoing, lastAllowIncoming);
if (device == null)
return;
if (canMakeOutgoing()) {
disconnect();
connection = device.connect(inParams, this);
if (connection == null && basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
"Couldn't create new connection"));
}
}
public void disconnect() {
IncomingPhoneActivity.incomingAlert = null;
if (connection != null) {
connection.disconnect(); // will null out in onDisconnected()
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnecting();
}
}
public void acceptConnection() {
if (pendingIncomingConnection != null) {
if (connection != null)
disconnect();
pendingIncomingConnection.accept();
connection = pendingIncomingConnection;
pendingIncomingConnection = null;
}
}
public void connecta(String phoneNumber) {
Toast.makeText(context, "Calling...", Toast.LENGTH_SHORT).show();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("group_id", "11");
// String capabilityToken;
try {
device = Twilio
.createDevice(decodedString, this /* DeviceListener */);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
device.disconnectAll();
} catch (Exception e) {
e.printStackTrace();
}
connection = device.connect(parameters, this);
if (connection == null) {
Log.w(TAG, "Failed to create new connection");
}
}
public void ignoreIncomingConnection() {
if (pendingIncomingConnection != null) {
pendingIncomingConnection.ignore();
}
}
public boolean isConnected() {
return connection != null
&& connection.getState() == Connection.State.CONNECTED;
}
public Connection.State getConnectionState() {
return connection != null ? connection.getState()
: Connection.State.DISCONNECTED;
}
public boolean hasPendingConnection() {
return pendingIncomingConnection != null;
}
public boolean handleIncomingIntent(Intent intent) {
Device inDevice = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection inConnection = intent
.getParcelableExtra(Device.EXTRA_CONNECTION);
if (inDevice == null && inConnection == null)
return false;
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
if (pendingIncomingConnection != null) {
Log.i(TAG, "A pending connection already exists");
inConnection.ignore();
return false;
}
pendingIncomingConnection = inConnection;
pendingIncomingConnection.setConnectionListener(this);
return true;
}
public boolean canMakeOutgoing() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.OUTGOING)
&& (Boolean) caps.get(Capability.OUTGOING);
}
public boolean canAcceptIncoming() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.INCOMING)
&& (Boolean) caps.get(Capability.INCOMING);
}
public void setCallMuted(boolean isMuted) {
if (connection != null) {
connection.setMuted(isMuted);
}
}
#Override
/* DeviceListener */
public void onStartListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStartedListening();
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(null);
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice, int inErrorCode,
String inErrorMessage) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(new Exception(
inErrorMessage));
}
#Override
/* DeviceListener */
public boolean receivePresenceEvents(Device inDevice) {
return false;
}
#Override
/* DeviceListener */
public void onPresenceChanged(Device inDevice, PresenceEvent inPresenceEvent) {
}
#Override
/* ConnectionListener */
public void onConnecting(Connection inConnection) {
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnecting();
}
#Override
/* ConnectionListener */
public void onConnected(Connection inConnection) {
updateAudioRoute();
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnected();
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnected();
} else if (inConnection == pendingIncomingConnection) {
pendingIncomingConnection = null;
if (basicConnectionListener != null)
basicConnectionListener.onIncomingConnectionDisconnected();
}
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection, int inErrorCode,
String inErrorMessage) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
inErrorMessage));
}
}
private class GetAuthTokenAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
IncomingPhone.this.reallyLogin(result);
}
#Override
protected String doInBackground(String... params) {
try {
capabilityToken = HttpHelper.httpGet(params[0]);
decodedString = capabilityToken.replace("\"", "");
} catch (Exception e) {
e.printStackTrace();
}
return decodedString;
}
}
}
And the activity which opens after getting incoming call via Service class.
public class IncomingPhoneActivity extends Activity implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static final Handler handler = new Handler();
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
private LinearLayout disconnect_btn;
private LinearLayout mainButton;
private ToggleButton speakerButton;
private ToggleButton muteButton;
private EditText logTextBox;
static AlertDialog incomingAlert;
private EditText outgoingTextBox;
private EditText clientNameTextBox;
private Button capabilitesButton;
private CheckBox incomingCheckBox, outgoingCheckBox;
Button call_btn, dis_call_btn, updateButton;
public static String AUTH_PHP_SCRIPT, rating1, rating2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_screen);
Intent intent = getIntent();
Operator_id = intent.getStringExtra("operator_id");
gps = new GPSTracker(IncomingPhoneActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// gps.showSettingsAlert();
latitude = 0.00;
longitude = 0.00;
}
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
AUTH_PHP_SCRIPT = "http://xxxxxxxxxxxxxx/getGenToken?group_id="
+ Operator_id + "&twilio_id=" + Twilio_id + "&latitude="
+ latitude + "&longitude=" + longitude;
disconnect_btn = (LinearLayout) findViewById(R.id.d_call);
mainButton = (LinearLayout) findViewById(R.id.call);
call_btn = (Button) findViewById(R.id.call_btn);
dis_call_btn = (Button) findViewById(R.id.d_call_btn);
mainButton.setOnClickListener(this);
call_btn.setOnClickListener(this);
dis_call_btn.setOnClickListener(this);
disconnect_btn.setOnClickListener(this);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
speakerButton = (ToggleButton) findViewById(R.id.speaker_btn);
speakerButton.setOnCheckedChangeListener(this);
muteButton = (ToggleButton) findViewById(R.id.mute_btn);
muteButton.setOnCheckedChangeListener(this);
logTextBox = (EditText) findViewById(R.id.log_text_box);
outgoingTextBox = (EditText) findViewById(R.id.outgoing_client);
clientNameTextBox = (EditText) findViewById(R.id.client_name);
clientNameTextBox.setText(DEFAULT_CLIENT_NAME);
capabilitesButton = (Button) findViewById(R.id.capabilites_button);
capabilitesButton.setOnClickListener(this);
outgoingCheckBox = (CheckBox) findViewById(R.id.outgoing);
incomingCheckBox = (CheckBox) findViewById(R.id.incoming);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (MenuItems.Speaker == true) {
speakerButton.setVisibility(View.VISIBLE);
} else {
speakerButton.setVisibility(View.INVISIBLE);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, outgoingCheckBox.isChecked(),
incomingCheckBox.isChecked());
}
private void syncMainButton() {
handler.post(new Runnable() {
public void run() {
if (IncomingPhone.decodedString.length() != 0) {
if (phone.isConnected()) {
switch (phone.getConnectionState()) {
default:
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case DISCONNECTED:
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case CONNECTED:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
case CONNECTING:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
}
} else if (phone.hasPendingConnection()) {
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
} else {
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
}
/*
* else { Toast.makeText(getApplicationContext(),
* "TRY AGAIN!", Toast.LENGTH_SHORT).show(); }
*/
}
}
});
}
public void onBackPressed() {
phone.disconnect();
incomingAlert = null;
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
in.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(in);
finish();
}
class TokenTask extends AsyncTask<Void, Void, Void> {
String message;
JSONObject jsonResponse;
int crash_app;
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(AUTH_PHP_SCRIPT);
try {
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
IncomingPhone.decodedString = IncomingPhone.capabilityToken
.replace("\"", "");
}
}
} catch (Exception e) {
crash_app = 5;
message = "Something went wrong. Please try again later.";
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (status.equals("success")) {
final Handler handler12 = new Handler();
handler12.postDelayed(new Runnable() {
public void run() {
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton
.setBackgroundResource(R.drawable.light_green_connect);
}
}, 3000);
}
if (status.equals("failure")) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
// mainButton.setBackgroundColor(Color.parseColor("#4ca64c"));
mainButton.setBackgroundResource(R.drawable.dark_green_connect);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
}
}
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
if (phone.handleIncomingIntent(getIntent())) {
showIncomingAlert();
addStatusMessage(R.string.got_incoming);
if (Utils.isNetworkAvailable(IncomingPhoneActivity.this)) {
syncMainButton();
} else {
Toast.makeText(IncomingPhoneActivity.this,
"No internet connection!!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (phone != null) {
phone.setListeners(null, null, null);
phone = null;
}
}
#Override
public void onClick(View view) {
if ((view.getId() == R.id.d_call) || (view.getId() == R.id.d_call_btn)) {
phone.disconnect();
incomingAlert = null;
phone.setSpeakerEnabled(false);
phone.setCallMuted(false);
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
startActivity(in);
finish();
}
if ((view.getId() == R.id.call) || (view.getId() == R.id.call_btn)) {
} else if (view.getId() == R.id.capabilites_button) {
phone.login(clientNameTextBox.getText().toString(),
outgoingCheckBox.isChecked(), incomingCheckBox.isChecked());
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (group.getId() == R.id.input_select) {
if (checkedId == R.id.input_number) {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_PHONE);
outgoingTextBox.setHint(R.string.outgoing_number);
} else {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_TEXT);
outgoingTextBox.setHint(R.string.outgoing_client);
}
outgoingTextBox.setText("");
}
}
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (button.getId() == R.id.speaker_btn) {
phone.setSpeakerEnabled(isChecked);
} else if (button.getId() == R.id.mute_btn) {
phone.setCallMuted(isChecked);
}
}
private void addStatusMessage(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
logTextBox.append('-' + message + '\n');
}
});
}
private void addStatusMessage(int stringId) {
addStatusMessage(getString(stringId));
}
private void showIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert == null) {
notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.play();
break;
case AudioManager.RINGER_MODE_VIBRATE:
long pattern[] = { 0, 500, 200, 300, 500 };
vibrator.vibrate(pattern, 0);
break;
case AudioManager.RINGER_MODE_NORMAL:
r.play();
break;
}
incomingAlert = new AlertDialog.Builder(
IncomingPhoneActivity.this)
.setTitle(R.string.incoming_call)
.setCancelable(false)
.setMessage(R.string.incoming_call_message)
.setPositiveButton(R.string.answer,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.acceptConnection();
disconnect_btn
.setVisibility(View.VISIBLE);
mainButton.setVisibility(View.GONE);
incomingAlert = null;
}
})
.setNegativeButton(R.string.ignore,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.ignoreIncomingConnection();
incomingAlert = null;
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(
DialogInterface dialog) {
phone.ignoreIncomingConnection();
}
}).create();
incomingAlert.show();
}
}
});
}
private void hideIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert != null) {
incomingAlert.dismiss();
incomingAlert = null;
}
}
});
}
#Override
public void onLoginStarted() {
addStatusMessage(R.string.logging_in);
}
#Override
public void onLoginFinished() {
addStatusMessage(phone.canMakeOutgoing() ? R.string.outgoing_ok
: R.string.no_outgoing_capability);
addStatusMessage(phone.canAcceptIncoming() ? R.string.incoming_ok
: R.string.no_incoming_capability);
syncMainButton();
}
#Override
public void onLoginError(Exception error) {
if (error != null)
addStatusMessage(String.format(getString(R.string.login_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.login_error_unknown);
syncMainButton();
}
#Override
public void onIncomingConnectionDisconnected() {
hideIncomingAlert();
addStatusMessage(R.string.incoming_disconnected);
syncMainButton();
}
#Override
public void onConnectionConnecting() {
addStatusMessage(R.string.attempting_to_connect);
syncMainButton();
}
#Override
public void onConnectionConnected() {
addStatusMessage(R.string.connected);
syncMainButton();
}
#Override
public void onConnectionFailedConnecting(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.couldnt_establish_outgoing_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.couldnt_establish_outgoing);
}
#Override
public void onConnectionDisconnecting() {
addStatusMessage(R.string.disconnect_attempt);
syncMainButton();
}
#Override
public void onConnectionDisconnected() {
addStatusMessage(R.string.disconnected);
syncMainButton();
}
#Override
public void onConnectionFailed(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.connection_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.connection_error);
syncMainButton();
}
#Override
public void onDeviceStartedListening() {
addStatusMessage(R.string.device_listening);
}
#Override
public void onDeviceStoppedListening(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.device_listening_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.device_not_listening);
}
}