Database isn't loaded on first run API 26 - java

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.

Related

Why is my .putExtra not passing information?

I am creating an app similar to a notes app. I have an activity that is called AddEditUserActivity, and, as its name implies, it adds OR edits a user (the object that I created). When I click on a user on the RecyclerView, I am supposed to go to the AddEditUserActivity and see the 5 fields full with the info of the selected user with the title of the activity as "Edit User". When I create a new user, I am supposed to go to the same activity, but with the fields empty, and "Add User" as the title. Creating a user works fine, but when I try to edit it, the activity appears with "Add User" as a title and all the fields empty.
The strange thing is that I implemented some Toast messages like "User updated" and "User Created", and they show when they are supposed to. I think that the problem is in the MainActivity. When I click on a user, I putExtra to an Intent and then call startActivityForResult(EDIT_USER_REQUEST, intent). In the AddEditUserActivity, inside onCreate, I specified that if the intent has a specific extra (the id) then it means that I am updating the user. But it ignores that part. So I would really appreciate it if you could help me.
Here is my MainActivity:
package com.example.citadelentrance;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final int ADD_USER_REQUEST = 1;
public static final int EDIT_USER_REQUEST = 2;
private UserViewModel userViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton addUserButton = findViewById(R.id.button_add_user);
addUserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddEditUserActivity.class);
startActivityForResult(intent, ADD_USER_REQUEST);
}
});
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final UserAdapter adapter = new UserAdapter();
recyclerView.setAdapter(adapter);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
userViewModel.getAllUsers().observe(this, new Observer<List<User>>() {
#Override
public void onChanged(#Nullable List<User> users) {
adapter.submitList(users);
}
});
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
userViewModel.delete(adapter.getUserAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "User deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
adapter.setOnItemClickListener(new UserAdapter.OnItemClickListener() {
#Override
public void onItemClick(User user) {
Intent intent = new Intent(MainActivity.this, AddEditUserActivity.class);
intent.putExtra(AddEditUserActivity.EXTRA_ID, user.getId());
intent.putExtra(AddEditUserActivity.EXTRA_NAME, user.getName());
intent.putExtra(AddEditUserActivity.EXTRA_FAMILY, user.getFamily());
intent.putExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE, user.getLicensePlate());
intent.putExtra(AddEditUserActivity.EXTRA_DOCUMENT, user.getDocument());
intent.putExtra(AddEditUserActivity.EXTRA_ADDRESS, user.getAddress());
intent.putExtra(AddEditUserActivity.EXTRA_TIME, user.getTime());
startActivityForResult(intent, EDIT_USER_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_USER_REQUEST && resultCode == RESULT_OK) {
assert data != null;
String name = data.getStringExtra(AddEditUserActivity.EXTRA_NAME);
String family = data.getStringExtra(AddEditUserActivity.EXTRA_FAMILY);
String licensePlate = data.getStringExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE);
String document = data.getStringExtra(AddEditUserActivity.EXTRA_DOCUMENT);
String address = data.getStringExtra(AddEditUserActivity.EXTRA_ADDRESS);
String time = data.getStringExtra(AddEditUserActivity.EXTRA_TIME);
User user = new User(
name,
family,
licensePlate,
document,
address,
time
);
userViewModel.insert(user);
Toast.makeText(this, "User saved", Toast.LENGTH_SHORT).show();
} else if (requestCode == EDIT_USER_REQUEST && resultCode == RESULT_OK) {
assert data != null;
int id = data.getIntExtra(AddEditUserActivity.EXTRA_ID, -1);
if (id == -1) {
Toast.makeText(this, "User couldn't be updated", Toast.LENGTH_SHORT).show();
return;
}
String name = data.getStringExtra(AddEditUserActivity.EXTRA_NAME);
String family = data.getStringExtra(AddEditUserActivity.EXTRA_FAMILY);
String licensePlate = data.getStringExtra(AddEditUserActivity.EXTRA_LICENSE_PLATE);
String document = data.getStringExtra(AddEditUserActivity.EXTRA_DOCUMENT);
String address = data.getStringExtra(AddEditUserActivity.EXTRA_ADDRESS);
String time = data.getStringExtra(AddEditUserActivity.EXTRA_TIME);
User user = new User(
name,
family,
licensePlate,
document,
address,
time
);
user.setId(id);
userViewModel.update(user);
Toast.makeText(this, "User updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "User not saved", Toast.LENGTH_SHORT).show();
}
}
}
And here the AddEditUserActivity:
package com.example.citadelentrance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.time.LocalDateTime;
import java.util.Objects;
public class AddEditUserActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.example.citadelentrance.EXTRA_ID";
public static final String EXTRA_NAME = "com.example.citadelentrance.EXTRA_NAME";
public static final String EXTRA_FAMILY = "com.example.citadelentrance.EXTRA_FAMILY";
public static final String EXTRA_LICENSE_PLATE = "com.example.citadelentrance.EXTRA_LICENSE_PLATE";
public static final String EXTRA_DOCUMENT = "com.example.citadelentrance.EXTRA_DOCUMENT";
public static final String EXTRA_ADDRESS = "com.example.citadelentrance.EXTRA_ADDRESS";
public static final String EXTRA_TIME = "com.example.citadelentrance.EXTRA_TIME";
private EditText editTextName, editTextFamily,
editTextLicensePlate, editTextDocument, editTextAddress;
private TextView textViewTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
editTextName = findViewById(R.id.edit_text_name);
editTextFamily = findViewById(R.id.edit_text_family);
editTextLicensePlate = findViewById(R.id.edit_text_license_plate);
editTextDocument = findViewById(R.id.edit_text_document);
editTextAddress = findViewById(R.id.edit_text_address);
textViewTime = findViewById(R.id.text_view_time);
Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.drawable.ic_close);
Intent intent = new Intent();
if (intent.hasExtra(EXTRA_ID)) {
setTitle("Edit User");
editTextName.setText(intent.getStringExtra(EXTRA_NAME));
editTextFamily.setText(intent.getStringExtra(EXTRA_FAMILY));
editTextLicensePlate.setText(intent.getStringExtra(EXTRA_LICENSE_PLATE));
editTextDocument.setText(intent.getStringExtra(EXTRA_DOCUMENT));
editTextAddress.setText(intent.getStringExtra(EXTRA_ADDRESS));
textViewTime.setText(intent.getStringExtra(EXTRA_TIME));
} else {
setTitle("Add User");
textViewTime.setText(LocalDateTimeConverter.toDateString(LocalDateTime.now()));
Log.println(Log.ASSERT, "CS50x", "Add user activity");
}
}
private void saveUser() {
String name = getTextFromEdit(editTextName);
String family = getTextFromEdit(editTextFamily);
String licensePlate = getTextFromEdit(editTextLicensePlate);
String document = getTextFromEdit(editTextDocument);
String address = getTextFromEdit(editTextAddress);
String time = textViewTime.toString();
if (name.isEmpty() || family.isEmpty() || licensePlate.isEmpty() ||
document.isEmpty() || address.isEmpty()) {
Toast.makeText(this, "Please don't leave empty fields", Toast.LENGTH_SHORT).show();
return;
}
Intent data = new Intent();
data.putExtra(EXTRA_NAME, name);
data.putExtra(EXTRA_FAMILY, family);
data.putExtra(EXTRA_LICENSE_PLATE, licensePlate);
data.putExtra(EXTRA_DOCUMENT, document);
data.putExtra(EXTRA_ADDRESS, address);
data.putExtra(EXTRA_TIME, time);
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if (id != -1) {
data.putExtra(EXTRA_ID, id);
Log.println(Log.ASSERT, "CS50x", "id != -1");
}
setResult(RESULT_OK, data);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_save_user, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.save_user) {
saveUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private String getTextFromEdit(EditText editText) {
return editText.getText().toString().trim();
}
}
#arget's comment is correct - you need to change this:
Intent intent = new Intent();
to this
Intent intent = getIntent();
or use it directly instead.
Another thing, why don't you make the user class implement Parcelable, and pass the user around instead of all its properties? It would make the code a cleaner.

Comparing the User Input Edit Text with SQLite Database Android Java

Hello I am making a teacher assistant app, the app uses SQLite database and allows teacher to take attendance by adding updating and removing students, the student ID is generated everytime a new student is added, now here is the thing how to display error message if the input from the teacher doesn't match a student ID in database instead of making my app crash.
StudentOperations
package com.appcreator.isa.theteacherassistantapp.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
import java.util.ArrayList;
import java.util.List;
public class StudentOperations
{
public static final String LOGTAG = "STD_MNGMNT_SYS";
SQLiteOpenHelper dbhandler;
SQLiteDatabase database;
private static final String[] allColumns = {
StudentDatabaseHandler.COLUMN_SID,
StudentDatabaseHandler.COLUMN_EID,
StudentDatabaseHandler.COLUMN_FIRST_NAME,
StudentDatabaseHandler.COLUMN_LAST_NAME,
StudentDatabaseHandler.COLUMN_STUDY,
StudentDatabaseHandler.COLUMN_ATTENDANCE
};
public StudentOperations(Context context)
{
dbhandler = new StudentDatabaseHandler(context);
}
public void open()
{
Log.i(LOGTAG,"Database Opened");
database = dbhandler.getWritableDatabase();
}
public void close()
{
Log.i(LOGTAG, "Database Closed");
dbhandler.close();
}
public Student addStudent(Student Student)
{
ContentValues values = new ContentValues();
values.put(StudentDatabaseHandler.COLUMN_EID, Student.getEnrlomentID());
values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME,Student.getFirstname());
values.put(StudentDatabaseHandler.COLUMN_LAST_NAME,Student.getLastname());
values.put(StudentDatabaseHandler.COLUMN_STUDY, Student.getStudy());
values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, Student.getAttendance());
long insertSID = database.insert(StudentDatabaseHandler.TABLE_STUDENTS,null,values);
Student.setStudentID(insertSID);
return Student;
}
// Getting single Student
public Student getStudent(long id)
{
Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,StudentDatabaseHandler.COLUMN_SID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
if (cursor != null)
cursor.moveToFirst();
Student e = new Student(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
// return Student
return e;
}
public List<Student> getAllStudents()
{
Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,null,null,null, null, null);
List<Student> students = new ArrayList<>();
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
Student student = new Student();
student.setStudentID(cursor.getLong(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_SID)));
student.setEnrlomentID(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_EID)));
student.setFirstname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_FIRST_NAME)));
student.setLastname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_LAST_NAME)));
student.setStudy(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_STUDY)));
student.setAttendance(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_ATTENDANCE)));
students.add(student);
}
}
// return All Students
return students;
}
// Updating Student
public int updateStudent(Student student)
{
ContentValues values = new ContentValues();
values.put(StudentDatabaseHandler.COLUMN_EID, student.getEnrlomentID());
values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME, student.getFirstname());
values.put(StudentDatabaseHandler.COLUMN_LAST_NAME, student.getLastname());
values.put(StudentDatabaseHandler.COLUMN_STUDY, student.getStudy());
values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, student.getAttendance());
// updating row
return database.update(StudentDatabaseHandler.TABLE_STUDENTS, values,
StudentDatabaseHandler.COLUMN_SID + "=?",new String[] { String.valueOf(student.getStudentID())});
}
// Deleting Student
public void removeStudent(Student student)
{
database.delete(StudentDatabaseHandler.TABLE_STUDENTS, StudentDatabaseHandler.COLUMN_SID + "=" + student.getStudentID(), null);
}
}
The Main Activity
package com.appcreator.isa.theteacherassistantapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
public class MainActivity extends AppCompatActivity
{
private Button addStudentButton;
private Button editStudentButton;
private Button deleteStudentButton;
private StudentOperations studentOps;
private static final String EXTRA_STUDENT_ID = "TEMP";
private static final String EXTRA_ADD_UPDATE = "TEMP";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addStudentButton = (Button) findViewById(R.id.button_add_student);
editStudentButton = (Button) findViewById(R.id.button_edit_student);
deleteStudentButton = (Button) findViewById(R.id.button_delete_student);
addStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndUpdateStudent();
}
});
deleteStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndRemoveStudent();
}
});
}
public void getStudentIDAndUpdateStudent()
{
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().trim().length() > 0)
{
// get user input and set it to result
// edit text
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}).create()
.show();
}
public void getStudentIDAndRemoveStudent(){
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().trim().length() > 0)
{
// get user input and set it to result
// edit text
//studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}).create()
.show();
}
#Override
protected void onResume()
{
super.onResume();
studentOps = new StudentOperations(MainActivity.this);
studentOps.open();
}
#Override
protected void onPause()
{
super.onPause();
studentOps.close();
}
}
Logcat
10-17 03:42:09.750 11105-11105/com.appcreator.isa.theteacherassistantapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appcreator.isa.theteacherassistantapp, PID: 11105
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.appcreator.isa.theteacherassistantapp.Database.StudentOperations.getStudent(StudentOperations.java:71)
at com.appcreator.isa.theteacherassistantapp.MainActivity$5.onClick(MainActivity.java:144)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Updated Main Activity
package com.appcreator.isa.theteacherassistantapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
public class MainActivity extends AppCompatActivity
{
private Button addStudentButton;
private Button editStudentButton;
private Button deleteStudentButton;
private StudentOperations studentOps;
private static final String EXTRA_STUDENT_ID = "TEMP";
private static final String EXTRA_ADD_UPDATE = "TEMP";
private static final String TAG = "Student Exits";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addStudentButton = (Button) findViewById(R.id.button_add_student);
editStudentButton = (Button) findViewById(R.id.button_edit_student);
deleteStudentButton = (Button) findViewById(R.id.button_delete_student);
addStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndUpdateStudent();
}
});
deleteStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndRemoveStudent();
}
});
}
public boolean check_existence(String stud_id)
{
SQLiteOpenHelper db = new StudentDatabaseHandler(this);
SQLiteDatabase database = db.getWritableDatabase();
String select = "SELECT * FROM students WHERE studentID =" + stud_id;
Cursor c = database.rawQuery(select, null);
if (c.moveToFirst())
{
Log.d(TAG,"Student Exists");
return true;
}
if(c!=null)
{
c.close();
}
database.close();
return false;
}
public void getStudentIDAndUpdateStudent()
{
LayoutInflater li = LayoutInflater.from(this);
final View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().isEmpty())
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
else
{
// get user input and set it to result
// edit text
if (check_existence(userInput.getText().toString()) == true)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}
}).create()
.show();
}
public void getStudentIDAndRemoveStudent()
{
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().isEmpty())
{
Toast.makeText(MainActivity.this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
else
{
if(check_existence(userInput.getText().toString()) == true)
{
// get user input and set it to result
// edit text
//studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Invalid Input" , Toast.LENGTH_SHORT).show();
}
}
}
}).create()
.show();
}
#Override
protected void onResume()
{
super.onResume();
studentOps = new StudentOperations(MainActivity.this);
studentOps.open();
}
#Override
protected void onPause()
{
super.onPause();
studentOps.close();
}
}
You can make a new method to do the work with boolean data type and if it returns false, you might want to display it to the user via Toast or anything like that.
It may look like this in code:
public boolean check_existence(String stud_id) {
SQLiteDatabase db = this.getWritableDatabase();
String select = "SELECT * FROM table_name WHERE column_name ='" + stud_id;
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
Log.d(TAG,"User exits");
return true;
}
if(c!=null) {
c.close();
}
db.close();
return false;
}
You can now just call the method and if it returns false you may just display what you want using Toast.

Android FFMPEG - Low FPS & File Size is massive

I am new to Android app development and I have been asked to make a video splitter app. I am trying to use FFMPEG, but the library size is massive and makes the .APK file 140MB. How can I solve this? Similar apps are around 15MBs in size.
Also, the framerate starts at ~30FPS and drops to around 2.2FPS over time when trying to split a 30 second long video into two parts. How can I solve this? This is my code currently:
package splicer.com.splicer;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.github.hiteshsondhi88.libffmpeg.ExecuteBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.FFmpeg;
import com.github.hiteshsondhi88.libffmpeg.LoadBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegNotSupportedException;
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;
private FFmpeg ffmpeg;
static {
System.loadLibrary("native-lib");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ffmpeg = FFmpeg.getInstance(getApplicationContext());
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onFailure() {}
#Override
public void onSuccess() {}
#Override
public void onFinish() {}
});
} catch(FFmpegNotSupportedException e) {
e.printStackTrace();
}
textView = (TextView) findViewById(R.id.textView);
textView.setY(200);
textView.setHeight(700);
textView.setMovementMethod(new ScrollingMovementMethod());
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openGallery();
}
});
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public void openGallery() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String [] {Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, 100);
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode == RESULT_OK && requestCode == 100) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(getBaseContext(), intent.getData());
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long splitCount = Long.valueOf(time) / 1000 / 15;
if(splitCount > 1) {
final String path = getRealPathFromURI(getBaseContext(), Uri.parse(intent.getData().toString()));
for(int a = 0, start = 0; a < splitCount; ++a, start += 15) {
// I am only testing with .mp4s atm, this will change before production
final String targetPath = path.replace(".mp4", "_" + (a + 1) + ".mp4");
ffmpeg.execute(new String [] {
"-r",
"1",
"-i",
path,
"-ss",
String.valueOf(start),
"-t",
String.valueOf(start + 15),
"-r",
"24",
targetPath
}, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onProgress(String message) {
textView.setText("onProcess: " + message);
}
#Override
public void onFailure(String message) {
textView.setText("onFailure: " + message + " --- " + path);
}
#Override
public void onSuccess(String message) {
textView.setText("onSuccess:" + message);
MediaScannerConnection.scanFile(getBaseContext(),
new String [] { targetPath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {}
});
}
#Override
public void onFinish() {}
});
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
retriever.release();
}
}
}
}
I don't believe everything here is as optimal as it could be, but I'm just trying to prove the concept at the moment. Any help in the right direction would be amazing, thank you!

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);
}
}
}

logcat file showing errors

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" />

Categories

Resources