ArrayList to charsequence conversion issue when selecting an option - java

I populate an alerttdialog from a database. I store these values in an arrayList, convert them to an charsequence list then set them to my alertdialog builder. As shown:
This is a screenshot of my populated 'text template' options from my database:
At the moment when I click one of my options for example Call me. it displays as it should within a specified edittext. If I click on one of the other options such as 'Email me' this is ignored, only my first 'if' option Call me. will work as shown:
This leads me to believe for some reason only Call me has been added to my charsequence array but I'm not sure why. Here is my complete class. I am getting this issue at the longOnClick method. I have marked this issue area on the code below:
package com.example.flybase2;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ContactsEmail extends Activity implements OnClickListener, OnLongClickListener{
String emailPassed;
String emailAdd;
String emailSub;
String emailMess;
EditText setEmailAddress;
EditText setEmailSubject;
EditText setEmailMessage;
Button btnSendEmail;
int i;
CharSequence[] items;
DBHandlerTempComms addTemp = new DBHandlerTempComms(this, null, null);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emaillayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
emailPassed = extras.getString("passedEmailAdd");
}
setEmailAddress = (EditText) findViewById (R.id.inputEmailAddress);
setEmailAddress.setText(emailPassed);
setEmailSubject = (EditText) findViewById (R.id.inputEmailSubject);
setEmailMessage = (EditText) findViewById (R.id.inputEmailMessage);
btnSendEmail = (Button)findViewById(R.id.btnSendEmail);
btnSendEmail.setOnClickListener(this);
setEmailMessage.setOnLongClickListener(this);
}
#Override
public void onClick(View sendEmailClick) {
emailAdd = setEmailAddress.getText().toString();
emailSub = setEmailSubject.getText().toString();
emailMess = setEmailMessage.getText().toString();
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {emailAdd});
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSub);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, emailMess);
startActivity(Intent.createChooser(sendEmailIntent, "Send mail..."));
finish();
}
*********************ISSUE AREA********************
#Override
public boolean onLongClick(View v) {
addTemp.open();
Cursor getTemps = addTemp.setList();
addTemp.close();
if (getTemps != null) {
String[] from = new String[getTemps.getCount()];
startManagingCursor(getTemps);
if (getTemps.moveToFirst()) {
int count = 0;
do {
String userName = getTemps.getString(1);
from[count] = userName;
count++;
} while (getTemps.moveToNext());
}
ArrayList<String> content = new ArrayList<String>();
for (int a = 0; a < from.length; a ++)
{
content.add(from[a]);
}
items = content.toArray(new CharSequence[content.size()]);
}
Builder alertDialogBuilder = new AlertDialog.Builder(ContactsEmail.this);
alertDialogBuilder.setTitle("Message Templates:");
alertDialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Call me.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Text me.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Leaving the house now.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Leaving work now.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Create New Template +")) {
AlertDialog.Builder builder = new AlertDialog.Builder(ContactsEmail.this);
builder.setTitle("Type New Template:");
final EditText input = new EditText(ContactsEmail.this);
builder.setView(input);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
setEmailMessage.setText(value);
String templateValue = (String)value.toString();
addTemp.open();
addTemp.insertTemplate(templateValue);
addTemp.close();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
builder.show();
}
}
});
alertDialogBuilder.show();
return true;
}
}

Slightly embarrassing but I've just realized I have different strings comparing my IFs to the strings stored in the charsequence, so it is now working!

Related

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.

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.

How to display capital cities of checked countries in a multiple arraylist in an alertdialog using java

I'm new to Android studio programming. I wish to display checked country capitol cities from the second arraylist in another alertdialog. The following is my java code.
Please help me how to retrive the countries individual capitol cities
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<CharSequence> list = new ArrayList<CharSequence>();
List<CharSequence> list2 = new ArrayList<CharSequence>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for (int i=0;i<6;){
list.add(0, "Kenya");
list.add(1, "Uganda");
list.add(2, "Tanzania");
list.add(3, "S.Sudan");
list.add(4, "Rwanda");
list2.add(0, "Nairobi");
list2.add(1, "Kampala");
list2.add(2, "Der-es-salaam");
list2.add(3, "Juba");
list2.add(4, "Kigali");
View button = (View) findViewById(R.id.btnFindCapitol);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intialize readable sequence of char values
final CharSequence[] diagCountryList= list.toArray(new CharSequence[list.size()]);
//final CharSequence[] diagCapitolList = list2.toArray(new CharSequence[list2.size()]);
final AlertDialog.Builder countryDialog = new AlertDialog.Builder(MainActivity.this);
final AlertDialog.Builder capitolDialog = new AlertDialog.Builder(MainActivity.this);
countryDialog.setTitle("Select Item");
int count = diagCountryList.length;
boolean[] is_checked = new boolean[count];
// Creating multiple selection by using setMutliChoiceItem method
countryDialog.setMultiChoiceItems(diagCountryList, is_checked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
}
});
countryDialog.setCancelable(false);
countryDialog.setPositiveButton("Capitol cities",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ListView list = ((AlertDialog) dialog).getListView();
//Apply logic here
StringBuilder cityBuilder = new StringBuilder();
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
//if more than one item is checked separate them
if (checked) {
if (cityBuilder.length() > 0) cityBuilder.append("\n"+"\n");
cityBuilder.append(list.getItemAtPosition(i));
}
}
/*Check string builder is empty or not. If string builder is not empty.
It will display on the screen.
*/
if (cityBuilder.toString().trim().equals("")) {
capitolDialog.setMessage("Nothing was selected");
capitolDialog.show();
//stringBuilder.setLength(0);
}/* else if (cityBuilder.toString().trim().equals("")) {
capitolDialog.setTitle("The city");
capitolDialog.setMessage(cityBuilder);
capitolDialog.show();
}*/else {
capitolDialog.setTitle("The cities");
capitolDialog.setMessage(cityBuilder);
capitolDialog.show();
}
}
});
countryDialog.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = countryDialog.create();
alert.show();
}
});
}
}
Do the next, I've put comments for you to understand:
HashMap<Int, List<String>> map = new HashMap<Int, List<String>>();/*start;*/
ArrayList <String>test = new ArrayList<String>();/*create aux*/
test.add("uganda");
test.add("Kampala");
map.put(1, test);/*adding city and country 1*/
//Do this in a bucle for everyone, and you got the HashMap working
//to get
map.get(1);
Now you have a structure like: [1:{"uganda","Kampala"}], do a bucle to apply this to your case, and you will have a hashMap with all the numbers linked to the cities and countries, like this one, and just getting using the number as key, it will return the names as Value.

How to save my ListView when app closes

I've tried using both SharedPrefrences and also saving to internal storage but I cannot get the results I want. The only results I have achieved are crashes.
I have an app that generates a custom password based on user options, it then enters those password into an Arraylist if the user clicks a button to save the password. However, when the app closes all data is lost.
How do I save the populated ArrayList or ListView so when the user clicks views passwords they can see their previously saved passwords?
* MAIN ACTIVITY JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import static com.jrfapplications.passgen.SettingsPage.CustPass;
import static com.jrfapplications.passgen.SettingsPage.FBPass;
import static com.jrfapplications.passgen.SettingsPage.custword;
import static com.jrfapplications.passgen.SettingsPage.custwordend;
import static com.jrfapplications.passgen.SettingsPage.isEndWordChecked;
import static com.jrfapplications.passgen.SettingsPage.isHighCaseChecked;
import static com.jrfapplications.passgen.SettingsPage.isNumbChecked;
import static com.jrfapplications.passgen.SettingsPage.isSpecChecked;
import static com.jrfapplications.passgen.SettingsPage.isStartCustWordChecked;
import static com.jrfapplications.passgen.SettingsPage.passLength;
public class MainActivity extends AppCompatActivity implements Serializable {
//Buttons
Button btnGoToSet;
Button btnGenPass;
Button btnViewPass;
Button btnSavePass;
//TextView
TextView passView;
//Saved Pass Array
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
static ArrayList<String> SavedFacebookPasswords = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find Buttons
btnGoToSet = (Button) findViewById(R.id.settingsbtn);
btnGenPass = (Button) findViewById(R.id.genpass);
btnViewPass = (Button) findViewById(R.id.viewpassbtn);
btnSavePass = (Button) findViewById(R.id.SavePassBtn);
//Find TextView
passView = (TextView) findViewById(R.id.pwEditTxt);
//Button Functions
btnGoToSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SettingsPage.class));
}
});
btnGenPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generatePassword(generateCharSet());
}
});
btnSavePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CustPass == 1){
if (SavedCustomPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedCustomPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
if (FBPass == 1){
if (SavedFacebookPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedFacebookPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
}
});
btnViewPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, view_pass.class));
}
});
}
public char[] generateCharSet() {
String numbers = "0123456789";
String special = "!£$%^&*()";
String alphabetsLower = "abcdefghijklmnopqrstuvwxyz";
String alphabetsUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Add lower alphabets by default
StringBuilder finalCharset = new StringBuilder(alphabetsLower);
// Add special chars if option is selected
if (isSpecChecked == 1) {
finalCharset.append(special);
}
// Add upper case chars if option is selected
if (isHighCaseChecked == 1) {
finalCharset.append(alphabetsUpper);
}
// Add numbers if option is selected
if (isNumbChecked == 1) {
finalCharset.append(numbers);
}
// build the final character set
return finalCharset.toString().toCharArray();
}
public void generatePassword(char[] charset) {
final StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < passLength; i++) {
char c = charset[random.nextInt(charset.length)];
sb.append(c);
}
if (isStartCustWordChecked == 1 && isEndWordChecked == 1){
final String output = custword + sb.toString() + custwordend;
passView.setText(output);
}else if (isStartCustWordChecked == 1){
final String output = custword + sb.toString();
passView.setText(output);
}else if (isEndWordChecked == 1){
final String output = sb.toString() + custwordend;
passView.setText(output);
}else
{
final String output = sb.toString();
passView.setText(output);
}
}
}
* VIEW PASS JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class view_pass extends AppCompatActivity {
private ListView mListView1, mListView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pass);
mListView1 = (ListView)findViewById(R.id.listView1);
mListView2 = (ListView)findViewById(R.id.listView2);
mListView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedCustomPasswords));
mListView2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedFacebookPasswords));
ListUtils.setDynamicHeight(mListView1);
ListUtils.setDynamicHeight(mListView2);
}
public static class ListUtils {
public static void setDynamicHeight(ListView mListView) {
ListAdapter mListAdapter = mListView.getAdapter();
if (mListAdapter == null) {
// when adapter is null
return;
}
int height = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(mListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
for (int i = 0; i < mListAdapter.getCount(); i++) {
View listItem = mListAdapter.getView(i, null, mListView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
height += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = mListView.getLayoutParams();
params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
mListView.setLayoutParams(params);
mListView.requestLayout();
}
}
}
This can be done by simply storing the generated password into sqlite database. https://developer.android.com/training/basics/data-storage/databases.html
You can also use cursor loaders for a better performance.
https://developer.android.com/guide/components/loaders.html
Try using a DBMS, if you want it stored locally, I would recommend SQL, or cloud-based system like Firebase
Shared preferences and Gson, much simple.
I used shared preferences to to save my ArrayLists on close thanks for the direction guys!
Using this for my answer:
Android: keep values in list after app shutdown
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
SavedCustomPasswords = getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SavedCustomPasswords);
adapter.notifyDataSetChanged();
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor mEdit1 = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(SavedCustomPasswords);
mEdit1.putStringSet("list", set);
return mEdit1.commit();
}
public void onStop() {
saveArray();
super.onStop();
}
public ArrayList<String> getArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}

Android Class cast exception with radio group widget?

Building a small quiz application and have some issues with the code, it worked on a previous version but that got delete during a fresh install of windows, when i try open up the a activity for a quiz i keep getting an unexpected error and the log says after a few lines
Java.lang.classexception : android.widget.Radio Group
the code for the activity looks like this
package com.example.quizzards;
import java.io.FileNotFoundException;
import java.util.Arrays;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class GamesActivity extends Activity {
boolean rightWrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_games);
try {
#SuppressWarnings("unused")
Questions questions = new Questions(getApplicationContext());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
update();
Button answer = (Button) findViewById(R.id.AnswerButton);
answer.setOnClickListener(new OnClickListener()
{
public void onClick(View V)
{
RadioGroup allOptions = (RadioGroup) findViewById(R.id.questions);
int toCheck = allOptions.getCheckedRadioButtonId();
if (toCheck == -1) {
Toast.makeText(GamesActivity.this, "Please select an option.",
Toast.LENGTH_SHORT).show();
} else {
RadioButton selected = (RadioButton) findViewById(allOptions
.getCheckedRadioButtonId());
rightWrong = Questions.checkAnswer(selected.getText()
.toString());
if (rightWrong == true) {
Toast.makeText(GamesActivity.this, "Right!!!",
Toast.LENGTH_SHORT).show();
Questions.addPoint();
update();
} else {
Questions.incorrectTry();
int remainingTries = Questions.getRemainingTries();
if (remainingTries == 0) {
// Toast.makeText(MainActivity.this,
// "Your final score is " + Questions.getScore() + ".",
// Toast.LENGTH_SHORT).show();
Intent i = new Intent(GamesActivity.this,
ResultsActivity.class);
startActivity(i);
} else {
Toast.makeText(
GamesActivity.this,
"Wrong!!! " + remainingTries
+ " tries left.",
Toast.LENGTH_SHORT).show();
}
}
allOptions.clearCheck();
}
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(GamesActivity.this, PlayActivity.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.games, menu);
return true;
}
public void update()
{
if (Questions.finished()) {
Intent i = new Intent(GamesActivity.this,
ResultsActivity.class);
startActivity(i);
} else {
String[] aQuestion = Questions.getNextQuestion();
String[] temp = Arrays.copyOfRange(aQuestion, 1, aQuestion.length);
for (int i = 0; i < temp.length; i++) {
int r = (int) (Math.random() * (i + 1));
String swap = temp[r];
temp[r] = temp[i];
temp[i] = swap;
}
TextView textViewQuestion = (TextView) findViewById(R.id.questions);
textViewQuestion.setText(aQuestion[0]);
TextView textViewOption1 = (TextView) findViewById(R.id.option1);
textViewOption1.setText(temp[0]);
TextView textViewOption2 = (TextView) findViewById(R.id.option2);
textViewOption2.setText(temp[1]);
TextView textViewOption3 = (TextView) findViewById(R.id.option3);
textViewOption3.setText(temp[2]);
TextView textViewOption4 = (TextView) findViewById(R.id.option4);
textViewOption4.setText(temp[3]);
TextView runningTotal = (TextView) findViewById(R.id.runningTotal);
runningTotal.setText("Total: " + Questions.getScore());
}
}
}
The XML file contains a radio group and few radio buttons, when i try to run the code without any sort of radio buttons and comment out the code, works perfectly
Make sure all your RadioButtons and RadioGroup have different id's in the layout file.
Another small optimization would be to look for the RadioButtons inside RadioGroup as following.
RadioButton selected = (RadioButton) allOptions.findViewById(
allOptions.getCheckedRadioButtonId());

Categories

Resources