Skip to content

Commit

Permalink
Get Coordinates
Browse files Browse the repository at this point in the history
  • Loading branch information
arjunadhikary committed Oct 15, 2020
1 parent fb74d5f commit 78bf28e
Show file tree
Hide file tree
Showing 9 changed files with 213 additions and 64 deletions.
4 changes: 3 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ android {
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
testImplementation 'junit:junit:4.13'
Expand All @@ -43,5 +43,7 @@ dependencies {
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation'com.google.android.gms:play-services-location:17.1.0'


}
3 changes: 2 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
android:allowBackup="true"
Expand All @@ -12,7 +14,6 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".DialogBox"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Expand Down
233 changes: 181 additions & 52 deletions app/src/main/java/com/arjun/weather/MainActivity.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,42 @@
package com.arjun.weather;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.arjun.weather.Model.FiveDaysWeather;
import com.arjun.weather.Model.ItemHourly;
import com.arjun.weather.RecyclerView.Adapter;
import com.arjun.weather.Model.Main;
import com.arjun.weather.RecyclerView.MainAdapter;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
Expand All @@ -31,8 +45,10 @@
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity implements DialogBox.sendLocation {
private EditText userSearch;
private FiveDaysWeather fiveDaysWeather;
FusedLocationProviderClient providerClient;
private int perm_id = 101;
private double lat, longs;
private FiveDaysWeather fiveDaysWeather = new FiveDaysWeather();
private Weather weather;
private String baseUrl = "https://api.openweathermap.org/data/2.5/";

Expand All @@ -41,11 +57,11 @@ public class MainActivity extends AppCompatActivity implements DialogBox.sendLoc
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// userSearch = findViewById(R.id.search);
// Button send = findViewById(R.id.send);
// send.setOnClickListener(sendListener);
getSupportActionBar().setElevation(0);
setRecyclerView();
Objects.requireNonNull(getSupportActionBar()).setElevation(0);
buildRetroift(baseUrl, "Butwal");
providerClient = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();



}
Expand All @@ -56,67 +72,180 @@ private void setRecyclerView() {
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(llm);
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.onDraw(c, parent, state);
}

@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
outRect.right = 20;
}
});
recyclerView.setAdapter(adapter);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.top_list,menu);
return super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.top_list, menu);
return super.onCreateOptionsMenu(menu);
}


@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
DialogBox box = new DialogBox();
box.show(getSupportFragmentManager(),"Search_Location");
box.show(getSupportFragmentManager(), "Search_Location");


return super.onOptionsItemSelected(item);
}

private void buildRetroift(String baseUrl, String userData) {
Log.d("Base_Url", "onClick: " + baseUrl);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
weather = retrofit.create(Weather.class);
String appid = "API_KEY";
// getAllData(userData, appid);
Log.d("Base_Url", "onClick: " + baseUrl);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
weather = retrofit.create(Weather.class);
String appid = "";
getAllData(userData, appid);

}
}


private void getAllData(String search, String apiKey) {

private void getAllData(String search,String apiKey) {
Call<FiveDaysWeather> weatherCall = weather.getAllWeatherData(search, apiKey,"metric");
weatherCall.enqueue(new Callback<FiveDaysWeather>() {
@Override
public void onResponse(Call<FiveDaysWeather> call, Response<FiveDaysWeather> response) {
if (!response.isSuccessful()) {
Log.e("TAG", "onResponse: " + response.code());
return;
}
Log.e("TAG", "onResponse:Data received " );
assert response.body() != null;
fiveDaysWeather = response.body();
Log.e("TAG", "onResponse:Total Data "+response.body().getList().size());
setRecyclerView();
Call<FiveDaysWeather> weatherCall = weather.getAllWeatherData(search, apiKey, "metric");
weatherCall.enqueue(new Callback<FiveDaysWeather>() {
@Override
public void onResponse(Call<FiveDaysWeather> call, Response<FiveDaysWeather> response) {
if (!response.isSuccessful()) {
Log.e("TAG", "onResponse: " + response.code());
return;
}
Log.e("TAG", "onResponse:Data received ");
assert response.body() != null;
fiveDaysWeather = response.body();
Log.e("TAG", "onResponse:Total Data " + response.body().getList().size());
Log.e("data", "onBindViewHolder: " + fiveDaysWeather.getCity().getName());
setRecyclerView();
}

@Override
public void onFailure(Call<FiveDaysWeather> call, Throwable t) {
Log.e("TAG", "onResponse: " + t.getMessage());
}
});
@Override
public void onFailure(Call<FiveDaysWeather> call, Throwable t) {
Log.e("TAG", "onResponse: " + t.getMessage());
}
});

}
}

@Override
public void sendUserLocation(String location) {
Toast.makeText(this, "Location:"+location, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Location:" + location, Toast.LENGTH_SHORT).show();
buildRetroift(baseUrl, location);
}

private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;

}

private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, perm_id);
}

private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

@Override
public void
onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if (requestCode == perm_id) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}else{
Toast.makeText(this,
"This app requires Location Permission to work correctly",
Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onResume() {
super.onResume();
if (checkPermission()) { getLastLocation();}
}

private void getLastLocation(){
// check if permissions are given
if (checkPermission()) {
// check if location is enabled
if (isLocationEnabled()) {
// getting last location from FusedLocationClient object
providerClient.getLastLocation().addOnCompleteListener(task -> {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
}
else {
lat= location.getLatitude();
longs=location.getLongitude();
Toast.makeText(MainActivity.this, "Lat:"+lat+" long:"+longs, Toast.LENGTH_SHORT).show();
}
});
}

else {
Toast.makeText(this, "Please turn on your location...", Toast.LENGTH_LONG).show();
Intent intent
= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
else {
// if permissions aren't available,request for permissions
requestPermissions();
}
}

@SuppressLint("MissingPermission")
private void requestNewLocationData(){
// Initializing LocationRequest object with appropriate methods
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);

// setting LocationRequest
// on FusedLocationClient
providerClient = LocationServices.getFusedLocationProviderClient(this);

providerClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}

private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult){
Location mLastLocation = locationResult.getLastLocation();
lat =mLastLocation.getLatitude();
longs= mLastLocation.getLongitude();
}
};

}
16 changes: 14 additions & 2 deletions app/src/main/java/com/arjun/weather/RecyclerView/MainAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,21 @@
import androidx.recyclerview.widget.RecyclerView;

import com.arjun.weather.Model.FiveDaysWeather;
import com.arjun.weather.Model.ItemHourly;
import com.arjun.weather.R;
import com.bumptech.glide.Glide;

import java.security.Permission;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {

FiveDaysWeather fiveDaysWeather;
public static final String data ="Data";
Context context;
interface setDataActivity{
void setPosition(int position);

}

public MainAdapter(FiveDaysWeather itemHourlyList, Context context){
this.fiveDaysWeather = itemHourlyList;
Expand All @@ -34,13 +42,17 @@ public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(view);
}


@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Glide.with(context)
.load("https://openweathermap.org/img/wn/[email protected]")
.into(holder.icon1);
holder.tempmin.setText("22");
holder.tempmax.setText("23");

Log.e(data, "onBindViewHolder: "+fiveDaysWeather.getCity().getName().toString() );
//If position only 8,16,24,32,40
holder.tempmin.setText(String.valueOf(fiveDaysWeather.getList().get(position).getMain().getTempMin()));
holder.tempmax.setText(String.valueOf(fiveDaysWeather.getList().get(position).getMain().getTempMax()));
}

@Override
Expand Down
7 changes: 4 additions & 3 deletions app/src/main/res/drawable/border.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<corners android:radius="5dp" />
<solid android:color="@android:color/white" />
<corners
android:topRightRadius="15dp"
android:topLeftRadius="15dp"/>
<stroke
android:width="1dp"
android:color="#000000" />
android:color="#6C6868" />
</shape>
Loading

0 comments on commit 78bf28e

Please sign in to comment.