logcat file showing errors - java

package com.example.ishan.complainbox;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageButton;
import android.view.View;
import android.widget.EditText;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v7.widget.AppCompatImageView;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.graphics.drawable.BitmapDrawable;
public class Crime extends MainActivity implements
View.OnClickListener,LocationListener {
GoogleMap googleMap;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView imgView,ivImage;
private String userChosenTask;
EditText street, city, pincode, detail;
Button btnsave;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
setContentView(R.layout.activity_crime);
// Get References of Views
street = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pincode = (EditText) findViewById(R.id.pin);
detail = (EditText) findViewById(R.id.detail);
imgView = (ImageView)findViewById(R.id.imgView);
btnsave = (Button) findViewById(R.id.save);
btnSelect = (Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String strt = street.getText().toString();
String cty = city.getText().toString();
String pin = pincode.getText().toString();
String det = detail.getText().toString();
Bitmap bitmap =
((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageInByte = baos.toByteArray();
btnsave = (Button) findViewById(R.id.save);
selectImage();
dbHandler.insertEntry(strt, cty, pin, det,imageInByte);
Toast.makeText(getApplicationContext(), "Complaint
Successfully Filed ", Toast.LENGTH_LONG).show();
}
});
ivImage = (ImageView) findViewById(R.id.img);
}
}
#Override
public void onRequestPermissionsResult ( int requestCode, String[]
permissions,
int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (userChosenTask.equals("Take Photo"))
cameraIntent();
else if (userChosenTask.equals("Choose from Library"))
galleryIntent();
} else
break;
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Crime.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=userChosenTask.checkPermission(Crime.this);
if (items[item].equals("Take Photo"))
{
userChosenTask ="Take Photo";
if(result)
cameraIntent();
}
else if (items[item].equals("Choose from Library"))
{
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
}
else if (items[item].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()
+ ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap
(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This is one activity class of my android project and this activity depends on another utility class....which is mentioned below:
The statement Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); shows an error in "imageView" and the statement boolean result=userChosenTask.checkPermission(Crime.this); shows an error on "checkPermission"...but I don't understand why...because checkPermission is already defined in the utility class....
package com.example.ishan.complainbox;
/**
* Created by ishan on 11/04/2017.
*/
import android.os.Build;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.DialogInterface;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED)
{
if
(ActivityCompat.shouldShowRequestPermissionRationale((MainActivity) context,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
AlertDialog.Builder alertBuilder = new
AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is
necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new
DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((MainActivity)
context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else
{
ActivityCompat.requestPermissions((MainActivity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else
{
return true;
}
}
}

In your manifests.xml, you need to include permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Related

Image is not generating/uploading in the server

I am developing an android app in which i want to save images on server(free server 000webhost).To do this i am encoding my image into string using base64. And sending this string with the POST method using volley.
But the image is not generating on the server side. Can anyone tell me what's wrong?
upload.php
<?php
$servername = "localhost";
$database = "id8258200_image";
$username = "id8258200_qmine1";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
if(isset($_POST["image"])){
$encoded_string = $_POST["image"];
$image_name="img";
$decoded_string = base64_decode($encoded_string);
$path = "image/$image_name.jpeg";
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
echo "success";
}
else {
echo "error";
}
?>
Mainactivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "https://qmine.000webhostapp.com/question/upload.php";
private int PICK_IMAGE_REQUEST = 1;
private Button buttonChoose;
private Button buttonUpload;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Log.d("tr", "qwerty" + encodedImage);
return encodedImage;
}
private void uploadImage() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "errorrrr", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> Params = new HashMap<String, String>();
String img = getStringImage(bitmap);
Log.d("qw", "aasas" + img);
Params.put("image", img);
return Params;
}
};
queue.add(request);
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
if (v == buttonView) {
viewImage();
}
}
private void viewImage() {
// startActivity(new Intent(this, ImageListView.class));
}
}
Code looks fine to me. Seems like a permission issue. Add these lines to top of your PHP script.
<?php
ini_set('display_errors', 1); // telling PHP to explicitly print all errors
error_reporting(E_ALL); // Show all notices, warnings and fatal errors
Second thing to check if the folder is having enough permission to write a file. Give write permission if not there and see if the code works.
Hope this helps. Happy coding!

Database isn't loaded on first run API 26

I created an app with database in assets folder . I wrote a code to copy database to SD Card and of course for android 6 + it needs run time permission. My problem : on first run after granting permission database isn't loaded but on second run there is no problem. Please help me to solve this issue .
UPDATE: Problem solved! now I have problem with favorite section. when I add something to favorite it can't be updated and I have to restart app and also with each run data is shown more than one time.
Here's my code :
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
} else if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
} else {
setupDB();
selectList();
selectFavorite();
Toast.makeText(MainActivity.this, "You grandet earlier",
Toast.LENGTH_LONG).show();
}
}
if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
} else if (!list.isEmpty()){
list.clear();
selectList();
}
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new
NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}
if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this,
ActivitySearch.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length >= 2 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED && grantResults[1] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Access granted",
Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
} else if (!list.isEmpty()){
list.clear();
selectList();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
You have just shown a toast after permissions are granted for the first time i.e. inside onRequestPermissionsResult. You will need to place the code to perform necessary operations inside there too.

app crashes on first run API 26

I created an app with database in assets folder . I wrote a code to copy database to sdcard and of course for android 6 + it needs run time permission. My problem : App copies database before asking for permission so for the first time app crashes but permission window is on screen and if you allow it on second run app works like charm . Please help me to solve this issue .
Here's my code :
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
public class MainActivity extends AppCompatActivity {
public static Context context;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
public static ArrayList<Structure> list = new ArrayList<Structure>();
public static ArrayList<Structure> favorite = new ArrayList<Structure>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
if(Build.VERSION.SDK_INT >= 23){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
,Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
}else if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
,Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
}else {
Toast.makeText(MainActivity.this,"You grandet
earlier",Toast.LENGTH_LONG).show();
}
}
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new
NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}
return true;
}
});
selectList();
selectFavorite();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length >= 2 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED && grantResults[1] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Access granted",
Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite(){
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()){
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList(){
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()){
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
It is quite simple. Move your Copy DB code into permission granted handling. If you do it in your onCreate prior to having permission you will crash. Bets of luck.
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
public class MainActivity extends AppCompatActivity {
public static Context context;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
public static ArrayList<Structure> list = new ArrayList<Structure>();
public static ArrayList<Structure> favorite = new ArrayList<Structure>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
if(Build.VERSION.SDK_INT >= 23){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
,Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
}else if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
,Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
}else {
Toast.makeText(MainActivity.this,"You grandet
earlier",Toast.LENGTH_LONG).show();
}
}
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length >= 2 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED && grantResults[1] ==
PackageManager.PERMISSION_GRANTED) {
setupDB();
setupNavDrawer();
Toast.makeText(MainActivity.this, "Access granted",
Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
private void setupDB(){
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void setupNavDrawer(){
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}
return true;
}
});
selectList();
selectFavorite();
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite(){
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()){
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList(){
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()){
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}

I'm trying to add GPS functionality to my android app, gps coordinates come out to 0.0, 0.0 every time

I'd like to check GPS both when the app is started and when the refresh button is hit, and use those data points, in the form of mLatitude and mLongitude to call the weather api. Eventually I'm going to geocode the city but right now for debugging purposes I'm outputting the GPS coordinates to the locationLabel textview.
my MainActivity.java:
package com.example.paxie.stormy.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.paxie.stormy.GPS_Service;
import com.example.paxie.stormy.R;
import com.example.paxie.stormy.weather.Current;
import com.example.paxie.stormy.weather.Day;
import com.example.paxie.stormy.weather.Forecast;
import com.example.paxie.stormy.weather.Hour;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
private double mLatitude;
private double mLongitude;
private BroadcastReceiver broadcastReceiver;
#Bind(R.id.timeLabel)
TextView mTimeLabel;
#Bind(R.id.temperatureLabel)
TextView mTemperatureLabel;
#Bind(R.id.humidityValue)
TextView mHumidityValue;
#Bind(R.id.precipValue)
TextView mPrecipValue;
#Bind(R.id.summaryLabel)
TextView mSummaryLabel;
#Bind(R.id.iconImageView)
ImageView mIconImageView;
#Bind(R.id.refreshImageView)
ImageView mRefreshImageView;
#Bind(R.id.progressBar)
ProgressBar mProgressBar;
#Bind(R.id.locationLabel)
TextView mLocationlabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
private void getForecast() {
if(!runtime_permissions())
checkGPS();
String apiKey = "1621390f8c36997cb1904914b726df52";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + mLatitude + "," + mLongitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e)
{
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(this, "Network is currently unavailable!", Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mLocationlabel.setText(mLatitude + " " + mLongitude);
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be:");
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ContextCompat.getDrawable(this, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimeZone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimeZone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
private void checkGPS() {
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mLatitude = (double) intent.getExtras().get("latitude");
mLongitude = (double) intent.getExtras().get("longitude");
}
};
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
}
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) {
getForecast();
} else {
runtime_permissions();
}
}
}
#Override
protected void onResume() {
super.onResume();
checkGPS();
}
}
my GPSservice.java:
package com.example.paxie.stormy;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
/**
* Created by paxie on 10/27/16.
*/
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
i.putExtra("longitude", location.getLongitude());
i.putExtra("latitude", location.getLatitude());
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,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Here are two things you can try:
1. Please ensure you have included the ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions in your manifest. If your app targets Android API 23 and above, you will need to include runtime permission handling.
2. Instead of having a LocationListener object as a class member, you should have your Service implement it as an interface and implement its onLocationChanged() method.
Apart from this, you really should consider using the location APIs' in Google Play Services, rather than those in AOSP (i.e. android.location).
See Making Your App Location-Aware

Call Camera class when input wrong password

I'm creating an Android app to capture image when input the wrong password so I created Camera class & Launcher class:
Camera.java
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Camera extends Activity{
private static final int CAMERA_REQUEST = 1888;
private static final int ACTION_TAKE_PHOTO = 1;
ImageView mimageView;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private boolean hasCamera() {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)){
return true;
} else {
return false;
}
}
private void takePicture(int actionCode){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch (actionCode){
case ACTION_TAKE_PHOTO:
boolean front_camera = hasCamera();
File f = null;
try {
if (front_camera){
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
}
else {
return;
};
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
}
startActivityForResult(intent,CAMERA_REQUEST);
mimageView.setVisibility(View.INVISIBLE);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
mimageView.setImageBitmap(mphoto);
takePicture(ACTION_TAKE_PHOTO);
}
}
}
Launcher.java
import android.app.KeyguardManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Vector;
public class Launcher extends Service implements View.OnClickListener, View.OnTouchListener{
WindowManager windowManager;
WindowManager.LayoutParams layoutparams;
RelativeLayout relativeLayout;
TextView text;
String password;
String password_saved;
String hint;
Vector<Long> hold_time;
long down_time[];
Vector<Vector<Float>> pressure;
Vector pressure_num[];
Vector<Vector<Float>> size;
Vector size_num[];
Button nums[]=null;
ImageButton clear;
ImageButton ok;
Vector<Vector<Float>> vecs;
Vector<Float> H_2;
#Override
public IBinder onBind(Intent intent){
return null;
}
#Override
public void onCreate(){
super.onCreate();
Log.d("Launcher","onCreate()");
KeyguardManager.KeyguardLock keyguardLock;
KeyguardManager keyguardManager=(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
keyguardLock=keyguardManager.newKeyguardLock("");
keyguardLock.disableKeyguard();
IntentFilter intentFilter=new IntentFilter("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(screenReceiver, intentFilter);
setUpLayout();
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
return Service.START_STICKY;
}
#Override
public void onDestroy(){
unregisterReceiver(screenReceiver);
Log.d("Service","Service stop!!!");
// startActivity(new Intent(Launcher.this,Launcher.class));
// KeyguardManager.KeyguardLock keyguardLock;
// KeyguardManager keyguardManager=(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
// keyguardLock=keyguardManager.newKeyguardLock("");
// keyguardLock.reenableKeyguard();
super.onDestroy();
}
private BroadcastReceiver screenReceiver=new BroadcastReceiver() {
public boolean wasScreenOn=true;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
Log.d("Launcher","action is "+action);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
wasScreenOn=false;
launchLock();
}else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
wasScreenOn=true;
}else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
launchLock();
}
}
};
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public int spTpPx(int sp) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
return Math.round(sp * displayMetrics.scaledDensity);
}
private void setUpLayout(){
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutparams= new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.RGBA_8888
);
nums=new Button[10];
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.back);
int marginPix=dpToPx(-16);
int paddingPix=dpToPx(20);
RelativeLayout.LayoutParams params[]=new RelativeLayout.LayoutParams[10];
for (int i=0;i<10;i++){
params[i]=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
params[i].bottomMargin=marginPix;
nums[i]=new Button(this);
nums[i].setId(i);
nums[i].setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
nums[i].setTextSize(TypedValue.COMPLEX_UNIT_SP, 35);
nums[i].setTypeface(null, Typeface.NORMAL);
nums[i].setTextColor(Color.parseColor("#a0333333"));
nums[i].setBackgroundColor(Color.parseColor("#00000000"));
nums[i].setOnClickListener(this);
nums[i].setOnTouchListener(this);
}
params[2].addRule(RelativeLayout.CENTER_IN_PARENT);
nums[2].setText(R.string.num_2);
params[5].addRule(RelativeLayout.CENTER_HORIZONTAL);
params[5].addRule(RelativeLayout.BELOW, 2);
nums[5].setText(R.string.num_5);
params[1].addRule(RelativeLayout.LEFT_OF, 2);
params[1].addRule(RelativeLayout.ABOVE,5);
nums[1].setText(R.string.num_1);
params[3].addRule(RelativeLayout.RIGHT_OF, 2);
params[3].addRule(RelativeLayout.ABOVE, 5);
nums[3].setText(R.string.num_3);
params[4].addRule(RelativeLayout.LEFT_OF, 2);
params[4].addRule(RelativeLayout.BELOW,2);
nums[4].setText(R.string.num_4);
params[6].addRule(RelativeLayout.RIGHT_OF, 2);
params[6].addRule(RelativeLayout.BELOW, 2);
nums[6].setText(R.string.num_6);
params[7].addRule(RelativeLayout.LEFT_OF, 5);
params[7].addRule(RelativeLayout.BELOW,5);
nums[7].setText(R.string.num_7);
params[8].addRule(RelativeLayout.BELOW, 5);
params[8].addRule(RelativeLayout.RIGHT_OF,4);
nums[8].setText(R.string.num_8);
params[9].addRule(RelativeLayout.BELOW, 5);
params[9].addRule(RelativeLayout.RIGHT_OF,5);
nums[9].setText(R.string.num_9);
params[0].addRule(RelativeLayout.BELOW, 8);
params[0].addRule(RelativeLayout.RIGHT_OF,7);
nums[0].setText(R.string.num_0);
RelativeLayout.LayoutParams clear_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
clear_param.addRule(RelativeLayout.BELOW,8);
clear_param.addRule(RelativeLayout.LEFT_OF, 8);
clear_param.setMargins(0, dpToPx(6), dpToPx(12), 0);
clear=new ImageButton(this);
clear.setId(R.id.clear);
clear.setImageResource(R.drawable.ic_action_cancel);
clear.setBackgroundColor(Color.parseColor("#00000000"));
clear.setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
clear.setLayoutParams(clear_param);
clear.setOnClickListener(this);
RelativeLayout.LayoutParams ok_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
ok_param.addRule(RelativeLayout.BELOW,8);
ok_param.addRule(RelativeLayout.RIGHT_OF, 8);
ok_param.setMargins(dpToPx(12), dpToPx(6), 0, 0);
ok=new ImageButton(this);
ok.setId(R.id.ok);
ok.setImageResource(R.drawable.ic_action_accept);
ok.setBackgroundColor(Color.parseColor("#00000000"));
ok.setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
ok.setLayoutParams(ok_param);
ok.setOnClickListener(this);
RelativeLayout.LayoutParams text_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
text_param.addRule(RelativeLayout.CENTER_HORIZONTAL);
text_param.addRule(RelativeLayout.ABOVE,2);
text=new TextView(this);
text.setId(R.id.text);
text.setLayoutParams(text_param);
text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
text.setTypeface(null, Typeface.NORMAL);
text.setTextColor(Color.parseColor("#a0333333"));
text.setBackgroundColor(Color.parseColor("#00000000"));
text.setPadding(dpToPx(30),dpToPx(30),dpToPx(30),dpToPx(30));
for (int i=0;i<10;i++){
nums[i].setLayoutParams(params[i]);
}
for (int i=0;i<10;i++){
relativeLayout.addView(nums[i]);
}
relativeLayout.addView(clear);
relativeLayout.addView(ok);
relativeLayout.addView(text);
}
private void launchLock(){
try {
//load password and vecs from file
FileInputStream fileInputStream=openFileInput("password");
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
password_saved=(String)objectInputStream.readObject();
vecs=(Vector<Vector<Float>>)objectInputStream.readObject();
H_2=(Vector<Float>)objectInputStream.readObject();
Log.d("password_saved",password_saved);
Log.d("vecs",vecs.toString());
Log.d("H_2",H_2.toString());
objectInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
Log.d("window manager", "file not found");
try{
windowManager.removeView(relativeLayout);
}catch (IllegalArgumentException e1){
Log.d("window manager","has no layout");
}
return;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
password="";
hint="";
hold_time=new Vector<Long>();
down_time=new long[10];
pressure=new Vector<Vector<Float>>();
pressure_num=new Vector[10];
size=new Vector<Vector<Float>>();
size_num=new Vector[10];
text.setText(hint);
for (int i=0;i<10;i++){
pressure_num[i]=new Vector<Float>();
size_num[i]=new Vector<Float>();
}
try {
windowManager.addView(relativeLayout,layoutparams);
}catch (RuntimeException e){
// e.printStackTrace();
Log.d("window manager","layout has already been added");
}
}
#Override
public void onClick(View view) {
int id=view.getId();
if (id==R.id.ok){
Log.d("launcher","ok");
Log.d("password",password);
Log.d("hold time",hold_time.toString());
Log.d("pressure",pressure.toString());
Log.d("size",size.toString());
try {
//turn password to md5
byte[] bytes = password.getBytes("UTF-8");
MessageDigest md=MessageDigest.getInstance("MD5");
bytes=md.digest(bytes);
password=new String(bytes);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Vector<Float> vec=new Vector<Float>();
for (long value:hold_time){
vec.add((float) value);
}
for (Vector<Float> values:pressure){
vec.add(Collections.max(values));
}
for (Vector<Float> values:size){
vec.add(Collections.max(values));
}
Log.d("vec",vec.toString());
Log.d("MD5",password);
boolean quit=true;
//if password is equal
Vector<Float> probs=new Vector<Float>();
if (password.equals(password_saved)){
for (int i=0;i<H_2.size();i++){
float p=0;
for (int j=0;j<vecs.size();j++){
//np.exp(-1./2.*(v_test[i]-v_train[i])**2/H_2[i])
p+=Math.exp(-1./2.*
(vec.elementAt(i)-vecs.elementAt(j).elementAt(i))*
(vec.elementAt(i)-vecs.elementAt(j).elementAt(i))/
H_2.elementAt(i)
);
}
p/=vecs.size();
probs.add(p*p);
}
Log.d("probs ",probs.toString());
Float sum_probs= new Float(0);
for (int i=0;i<probs.size()/3*2;i++){
sum_probs+=probs.elementAt(i);
}
Log.d("sum_probs ",sum_probs.toString());
if (sum_probs<0.25*probs.size()/3*2)
quit=false;
}else{
quit=false;
}
if (quit)
windowManager.removeView(relativeLayout);
else{
//if fail, then init
text.setText("Wrong password");
hint="";
password="";
hold_time=new Vector<Long>();
pressure=new Vector<Vector<Float>>();
size=new Vector<Vector<Float>>();
}
}else if (id==R.id.clear){
text.setText("Please enter again");
hint="";
password="";
hold_time=new Vector<Long>();
pressure=new Vector<Vector<Float>>();
size=new Vector<Vector<Float>>();
}else {
text.setText(hint+="*");
password+=Integer.toString(id);
Log.d("password",password);
}
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int id=view.getId();
if(motionEvent.getActionMasked()==MotionEvent.ACTION_DOWN){
down_time[id]= SystemClock.uptimeMillis();
pressure_num[id]=new Vector<Float>();
size_num[id]=new Vector<Float>();
}else if(motionEvent.getActionMasked()==MotionEvent.ACTION_UP){
hold_time.add(SystemClock.uptimeMillis()-down_time[id]);
pressure.add((Vector<Float>)pressure_num[id]);
size.add((Vector<Float>)size_num[id]);
}
pressure_num[id].add(motionEvent.getPressure());
size_num[id].add(motionEvent.getSize());
return false;
}
}
The problem is that I don't know how to call Camera class in Launcher class

Categories

Resources