java.lang.IllegalStateException: Couldn't read row 0, col -1 - java

I have problem with android programming.
I have three Classes.
Main2_Activity Class
public class Main2_Activity extends Activity{
ArrayList<Estekhare> estekhareHa = new ArrayList<Estekhare>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt_soore = (TextView) findViewById(R.id.txt_soore);
final TextView txt_aye = (TextView) findViewById(R.id.txt_aye);
final TextView txt_safhe = (TextView) findViewById(R.id.txt_safhe);
final TextView txt_koli = (TextView) findViewById(R.id.txt_koli);
final TextView txt_moamele = (TextView) findViewById(R.id.txt_moamele);
final TextView txt_ezdevaj = (TextView) findViewById(R.id.txt_ezdevaj);
final TextView txt_natije = (TextView) findViewById(R.id.txt_natije);
final TextView txt_main_aye = (TextView) findViewById(R.id.txt_main_aye);
final TextView txt_translate = (TextView) findViewById(R.id.txt_translate);
Button btnAgain=(Button) findViewById(R.id.btnAgain);
Cursor cursor = G.DB.rawQuery("SELECT * FROM Sheet1", null);
while (cursor.moveToNext()) {
Estekhare estekhare = new Estekhare();
estekhare.natije = cursor.getString(cursor.getColumnIndex("natije"));
estekhare.koli = cursor.getString(cursor.getColumnIndex("koli"));
estekhare.ezdevaj = cursor.getString(cursor.getColumnIndex("ezdevaj"));
estekhare.moamele = cursor.getString(cursor.getColumnIndex("moamele"));
estekhare.soore = cursor.getString(cursor.getColumnIndex("soore"));
estekhare.aye = cursor.getString(cursor.getColumnIndex("aye"));
estekhare.safhe = cursor.getString(cursor.getColumnIndex("safhe"));
estekhare.main_translate = cursor.getString(cursor.getColumnIndex("main_translate"));
estekhareHa.add(estekhare);
}
cursor.close();
Random rand = new Random();
int n = rand.nextInt(estekhareHa.size());
Estekhare estekhare = estekhareHa.get(n);
txt_soore.setText(estekhare.soore);
txt_aye.setText(estekhare.aye);
txt_safhe.setText(estekhare.safhe);
txt_koli.setText(estekhare.koli);
txt_moamele.setText(estekhare.moamele);
txt_ezdevaj.setText(estekhare.ezdevaj);
txt_natije.setText(estekhare.natije);
txt_main_aye.setText(estekhare.main_aye);
txt_translate.setText(estekhare.main_translate);
Estekhare Class
public class Estekhare {
public String natije;
public String koli;
public String ezdevaj;
public String moamele;
public String soore;
public String aye;
public String safhe;
public String main_aye;
public String main_translate;
}
G Class
public class G extends Application{
public static SQLiteDatabase DB;
public static Context context;
public static final String DIR_SDCARD=Environment.getExternalStorageDirectory().getAbsolutePath();
public static String DIR_DATABASE;
private final String dbName = "natije_estekhare.sqlite";
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
DIR_DATABASE= DIR_SDCARD +"/Android/data/"+ context.getPackageName()+ "/database/";
new File(DIR_DATABASE).mkdirs();
prepareDB();
}
public boolean prepareDB() {
try {
String state = Environment.getExternalStorageState();
InputStream is = G.context.getAssets().open(dbName);
if (state.equals(Environment.MEDIA_MOUNTED)) {
File DB_PATH = new File(DIR_DATABASE + "/" + dbName);
logger("SD MOUNTED");
if (DB_PATH.exists()) {
logger("DB exist");
DB = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null);
return true;
}
else {
logger("DB NOT exist");
if (copy(new FileOutputStream(DB_PATH), is)) {
logger("Copy Success");
DB = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null);
return true;
}
else {
logger("Copy Faild");
return false;
}
}
}
else {
logger("SD NOT MOUNTED");
DIR_DATABASE = getFilesDir().toString();
File dbFile = new File(getFilesDir().toString() + "/" + dbName);
if (dbFile.exists()) {
logger("DB exist");
DB = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
return true;
}
else {
logger("DB NOT exist");
FileOutputStream os = openFileOutput(dbName, context.MODE_PRIVATE);
if (copy(os, is)) {
logger("Copy Success");
DB = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
return true;
}
else {
logger("Copy Faild");
return false;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean copy(OutputStream os, InputStream is) {
try {
int readed = 0;
byte[] buffer = new byte[8 * 1024];
while ((readed = is.read(buffer)) > 0) {
os.write(buffer, 0, readed);
}
try {
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
os.flush();
}
catch (Exception e) {
e.printStackTrace();
}
try {
os.close();
}
catch (Exception e) {
e.printStackTrace();
}
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void logger(String Message){
Log.i("LOG", Message);
}
}
When I Run this program, it crashes. How to solve the problem?
java.lang.RuntimeException: Unable to start activity ComponentInfo{amir.badiei.app.estekhareapp/amir.badiei.app.estekhareapp.Main2_Activity}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.at amir.badiei.app.estekhareapp.Main2_Activity.onCreate(Main2_Activity.java:47).

If a column doesn't exist, then cursor.getColumnIndex will return -1.
I'd start checking to make sure your Sheet1 table has all of the columns you are trying to access and that they are indeed named exactly the way you are specifying in your code. Otherwise when you try to get the data from the cursor for a column of -1, you'll get the IllegalStateException.

Related

How to convert SQLite database in android studio and then share it as csv file

Im making an app in which the users inserts values into a table (SQLite DB) and I want to make a share button which will share the the table as an excel file (.csv).
The following is a rudimentary example. That will write a very basic CSV file based upon a query that concatenates the columns with a , between the columns.
The table has 3 columns named :-
_id
_name
_email
The query used is effectively SELECT _id||','||_name||','||_email FROM test1;, although the SQLiteDatabase query method is used to build the SQL.
The method getCSVRows of the DBHelper class returns a Cursor based upon the above (i.e. a single column, the CSV, that can be accessed via offset 0).
Each time the App is run two rows are added, via the addTest1Row method.
The App has a button that when clicked invokes the crtCSV method that basically :-
gets the column names as a CSV (really this method should be used to drive the getCSVRows method, as there is the potential to have the column names in the wrong place) and writes the line with these first.
retrieves the Cursor with the data as a CSV string and writes a line.
The output file is located in the mycsvfiles directory of the Downloads directory (note only the most basic of checks are done, so this may not work on some devices).
The file name will be unique as it is suffixed with the current timestamp.
This screenshot shows 3 such files (a taken from Android Studio's device Explorer) :-
This shows it opened in Android Studio :-
And lastly in Excel :-
Here's the code:-
First, as Permission is required the relevant section of the Manifest AndroidManifest.xml
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
If the App is to be used for any device that uses an API greater than 22 then permission has to be requested. As such there is a class for this namely ExternalStoragePermissions.java for handling this request :-
class ExternalStoragePermissions {
public int API_VERSION = Build.VERSION.SDK_INT;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public ExternalStoragePermissions() {}
// Note call this method
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
invoked from Main.Activity
The DatabaseHelper (i.e. Subclass of SQLiteOpenHelper, as is often used) is DBHelper.java :-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_TEST1 = "test1";
public static final String COL_TEST1_ID = BaseColumns._ID;
public static final String COL_TEST1_NAME = "_name";
public static final String COL_TEST1_EMAIL = "_email";
private static final String crtTest1SQL = "CREATE TABLE IF NOT EXISTS " +
TB_TEST1 +
"(" +
COL_TEST1_ID + " INTEGER PRIMARY KEY," +
COL_TEST1_NAME + " TEXT," +
COL_TEST1_EMAIL + " TEXT" +
")";
SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(crtTest1SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long addTest1Row(String name, String email) {
ContentValues cv = new ContentValues();
cv.put(COL_TEST1_NAME,name);
cv.put(COL_TEST1_EMAIL,email);
return mDB.insert(TB_TEST1,null,cv);
}
public Cursor getCSVRows(String table) {
Cursor rv;
String[] columns;
switch (table) {
case TB_TEST1:
columns = new String[]{COL_TEST1_ID + "||','||" + COL_TEST1_NAME + "||','||" + COL_TEST1_EMAIL};
break;
default:
return null;
}
return mDB.query(table,columns,null,null,null,null,null);
}
public String getColumnsAsCSV(String table) {
StringBuilder sb = new StringBuilder("");
if (ifTableExists(table)) {
Cursor csr = mDB.rawQuery("PRAGMA table_info(" +
table +
")",null);
boolean after_first_row = false;
int rowsdone = 0;
while (csr.moveToNext()) {
if (after_first_row) {
sb.append(",");
} else {
after_first_row = true;
}
sb.append(csr.getString(csr.getColumnIndex("name")));
}
}
return sb.toString();
}
private boolean ifTableExists(String table) {
String whereclause = "name=?";
String[] whereargs = new String[]{table};
Cursor csr = mDB.query("sqlite_master",null,whereclause,whereargs,null,null,null);
int rowcount = csr.getCount();
csr.close();
return rowcount > 0;
}
}
Last is the Activity MainActivity.java
public class MainActivity extends AppCompatActivity {
Button mConvert;
DBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Need to have permission to External Storage
if(Build.VERSION.SDK_INT >= 23) {
ExternalStoragePermissions.verifyStoragePermissions(this);
}
mConvert = this.findViewById(R.id.convert_table);
mConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
crtCSV(DBHelper.TB_TEST1 + String.valueOf(System.currentTimeMillis()),DBHelper.TB_TEST1);
}
});
mDBHlpr = new DBHelper(this);
mDBHlpr.addTest1Row("Fred","Fred#email.com");
mDBHlpr.addTest1Row("Mary","mary#email.com");
}
private int crtCSV(String filename, String table) {
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return -1;
}
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"mycsvfiles");
String directory = dir.getPath();
if (!dir.exists()) {
dir.mkdirs();
}
File f = new File(directory,filename);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return -2;
}
f.delete();
FileOutputStream fo;
try {
fo = new FileOutputStream(f);
} catch (IOException e) {
e.printStackTrace();
return -3;
}
Cursor csr = mDBHlpr.getCSVRows(table);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fo));
try {
bw.write(mDBHlpr.getColumnsAsCSV(table));
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
try {
fo.close();
} catch (IOException e1) {
e1.printStackTrace();
f.delete();
return -4;
}
f.delete();
return -5;
}
while (csr.moveToNext()) {
String line = csr.getString(0);
try {
bw.write(line);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
try {
fo.close();
} catch (IOException e1) {
e1.printStackTrace();
f.delete();
return -6;
}
f.delete();
return -7;
}
}
csr.close();
try {
bw.close();
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
return -8;
}
return 0;
}
}
The easiest way, use CSVWriter like this:
implementation 'com.opencsv:opencsv:3.7'
And in MainActivity
try {
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase db = myDb.getWritableDatabase();
Cursor curCSV = db.rawQuery("select * from " + "your_database_table", null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
String[] arrayStr = {curCSV.getString(0), curCSV.getString(1),
curCSV.getString(2), curCSV.getString(3),
curCSV.getString(4), curCSV.getString(5)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
} catch (IOException e) {
e.printStackTrace();
}
where curCSV.getString() detect the column title, so start from 0 to number of your table column.

How to Add a custom Font to this TextView?

I'm trying to add a font to a textView. I have the following code-snippet, but I'm not sure how to adapt it to my code below. Can someone help me?
Code snippet I want to integrate into my program:
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Xcelsion.ttf"); // getActivity().getAssets()
TextView myTextView = (TextView)findViewById(R.id.text_view);
myTextView.setTypeface(myTypeface); //
Program I want to add the font to:
public class ListRingtonesAdapter extends ArrayAdapter<SongInfo> {
private ArrayList<SongInfo> items;
private Context context;
private ArrayList<ViewHolder> listHolder = new ArrayList<ListRingtonesAdapter.ViewHolder>();
private int curPosition = 0;
private RingtonesSharedPreferences pref;
private boolean inRingtones;
static final String TAG = "LOG";
private static final int DEFAULT_RINGTONE = 1;
private static final int ASSIGN_TO_CONTACT = 2;
private static final int DEFAULT_NOTIFICATION = 3;
private static final int DEFAULT_ALARM = 4;
private static final int DELETE_RINGTONE = 5;
public static final String ALARM_PATH = "/media/audio/alarms/";
public static final String ALARM_TYPE = "Alarm";
public static final String NOTIFICATION_PATH = "/media/audio/notifications/";
public static final String NOTIFICATION_TYPE = "Notification";
public static final String RINGTONE_PATH = "/media/audio/ringtones/";
public static final String RINGTONE_TYPE = "Ringtone";
public ListRingtonesAdapter(Context context, int viewResourceId,
ArrayList<SongInfo> objects, boolean inRingtones) {
super(context, viewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.items = objects;
this.pref = new RingtonesSharedPreferences(context);
this.inRingtones = inRingtones;
if(Main.mp.isPlaying()){
Main.mp.stop();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ActionItem defRingtone = new ActionItem(DEFAULT_RINGTONE,
"Default Ringtone", context.getResources().getDrawable(
R.drawable.icon_ringtone));
ActionItem assign = new ActionItem(ASSIGN_TO_CONTACT,
"Contact Ringtone", context.getResources().getDrawable(
R.drawable.icon_contact));
ActionItem defNotifi = new ActionItem(DEFAULT_NOTIFICATION,
"Default Notification", context.getResources().getDrawable(
R.drawable.icon_notify));
ActionItem defAlarm = new ActionItem(DEFAULT_ALARM, "Default Alarm",
context.getResources().getDrawable(R.drawable.icon_alarm));
final QuickAction mQuickAction = new QuickAction(context);
mQuickAction.addActionItem(defRingtone);
mQuickAction.addActionItem(assign);
mQuickAction.addActionItem(defNotifi);
mQuickAction.addActionItem(defAlarm);
// setup the action item click listener
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction quickAction, int pos,
int actionId) {
switch (actionId) {
case DEFAULT_RINGTONE:
setDefaultRingtone(items.get(curPosition));
Toast.makeText(context,
"Ringtone set successfully",
Toast.LENGTH_LONG).show();
break;
case ASSIGN_TO_CONTACT:
Intent intent = new Intent(context,
SelectContactActivity.class);
intent.putExtra("position", curPosition);
context.startActivity(intent);
break;
case DEFAULT_ALARM:
setDefaultAlarm(items.get(curPosition));
Toast.makeText(context,
"Alarm set successfully",
Toast.LENGTH_LONG).show();
break;
case DEFAULT_NOTIFICATION:
setDefaultNotice(items.get(curPosition));
Toast.makeText(context,
"Notification set successfully",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
// setup on dismiss listener, set the icon back to normal
mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
}
});
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
view.setTag(holder);
} else {
view = convertView;
// holder = (ViewHolder) view.getTag();
}
final SongInfo item = items.get(position);
if (item != null) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.txtName.setText(item.getName())
;
if (item.isFavorite()) {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite);
} else {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite_off);
}
if (!item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
} else {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
}
holder.btnPlayPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
for(int i = 0; i < items.size(); i++){
if(items.get(i) != item)
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
if (item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
item.setPlaying(false);
items.get(position).setPlaying(false);
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
} else {
curPosition = position;
playAudio(context, item.getAudioResource());
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
item.setPlaying(true);
items.get(position).setPlaying(true);
}
for (ViewHolder object : listHolder) {
if (object != holder) {
object.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
}
}
});
holder.btnFavorite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (item.isFavorite()) {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite_off);
item.setFavorite(false);
pref.setString(item.getFileName(), false);
if (!inRingtones) {
Intent broadcast = new Intent();
broadcast.setAction("REMOVE_SONG");
context.sendBroadcast(broadcast);
}
} else {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite);
item.setFavorite(true);
pref.setString(item.getFileName(), true);
}
}
});
listHolder.add(holder);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mQuickAction.show(v);
curPosition = position;
}
});
}
return view;
}
private Object getAssets() {
// TODO Auto-generated method stub
return null;
}
private TextView findViewById(int txtsongname)
{
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
private TextView txtName;
private ImageView btnFavorite;
private ImageView btnPlayPause;
}
private void playAudio(Context context, int id) {
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
Main.mp = MediaPlayer.create(context, id);
Main.mp.setOnCompletionListener(playCompletionListener);
Main.mp.start();
onRingtonePlay.onPlay();
}
private OnCompletionListener playCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
for(int i = 0; i < items.size(); i++){
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause
.setBackgroundResource(R.drawable.icon_play);
}
}
};
private void setRingtone(SongInfo info, boolean ringtone, boolean alarm,
boolean music, boolean notification) {
File dir = null;
String what = null;
if (ringtone) {
what = "Ringtones";
}else if(alarm){
what = "alarms";
}else if(notification){
what = "notifications";
}else{
what = "Ringtones";
}
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
String[] projection = new String[] { MediaStore.MediaColumns.DATA,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor c = context.getContentResolver().query(uri,projection,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()+ "\"", null, null);
String strRingtone = null, strAlarm = null, strNotifi = null, strMusic = null;
while (c.moveToNext()) {
strRingtone = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE));
strAlarm = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_ALARM));
strNotifi = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION));
strMusic = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
}
if (ringtone) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (notification) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (alarm) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (music) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
if (ringtone) {
values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtone);
} else if (notification) {
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, notification);
} else if (alarm) {
values.put(MediaStore.Audio.Media.IS_ALARM, alarm);
} else if (music) {
values.put(MediaStore.Audio.Media.IS_MUSIC, music);
}
context.getContentResolver().delete(uri,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath() + "\"", null);
Uri newUri = context.getContentResolver().insert(uri, values);
int type = RingtoneManager.TYPE_ALL;
if (ringtone)
type = RingtoneManager.TYPE_RINGTONE;
if (alarm)
type = RingtoneManager.TYPE_ALARM;
if (notification)
type = RingtoneManager.TYPE_NOTIFICATION;
RingtoneManager.setActualDefaultRingtoneUri(context, type, newUri);
}
private void setDefaultRingtone(SongInfo info) {
File dir = null;
String what = "Ringtones";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_RINGTONE
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
}
private void setDefaultAlarm(SongInfo info) {
File dir = null;
String what = "alarms";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_ALARM
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_ALARM);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_ALARM, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}
}
private void setDefaultNotice(SongInfo info) {
File dir = null;
String what = "notifications";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}
}
private void deleteRingtone(SongInfo info) {
File dir = null;
if (Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
Log.d(TAG, "dir:"+dir.getPath());
File file = new File(dir, info.getFileName());
Log.d(TAG, "file name:"+info.getFileName());
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file
.getAbsolutePath());
context.getContentResolver().delete(
uri,
MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()
+ "\"", null);
if (file.exists()) {
file.delete();
}
}
OnRingtonePlay onRingtonePlay;
/**
* #param onRingtonePlay the onRingtonePlay to set
*/
public void setOnRingtonePlay(OnRingtonePlay onRingtonePlay) {
this.onRingtonePlay = onRingtonePlay;
}
interface OnRingtonePlay{
public void onPlay();
}
}
/* Set Font Method */
public static void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Xcelsion.ttf"));
}
} catch (Exception ignored) {
}
}
/* And use this method as below */
overrideFonts(context, myTextView);
Put typeface coding in getView(final int position, View convertView, ViewGroup parent) method in this part of your code
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
Typeface myTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/Xcelsion.ttf");
holder.txtName.setTypeface(myTypeface);
view.setTag(holder);
} else {
view = convertView;
// holder = (ViewHolder) view.getTag();
}

Android Close() was never explicitly called on database

I keep getting the error message Close() was never explicitly called on database. From what I've read I'm not closing the database once the activity is destroyed, but I don't know how to implement it:
Database Helper:
public class ResultsDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "results.db";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_NAME = "results";
public static final String _ID = BaseColumns._ID;
public static final String SAVED_NAME = "name";
public static final String COLUMN_NAME_CREATE_DATE = "date";
public static final String RIGHT_EAR = "right_ear";
public static final String LEFT_EAR = "left_ear";
public ResultsDatabase(Context context) {
// calls the super constructor, requesting the default cursor factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ SAVED_NAME + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ RIGHT_EAR + " BLOB,"
+ LEFT_EAR + " BLOB"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
}
I call this helper in my Tabbed Results Activity which displays the data in two different fragments as follows:
public class TabbedResultsActivity extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private final static String TAG = "HearingTest";
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
GraphView graphView = new GraphView(this);
graphView.setPoints(rightAnswerList);
float leftAverage = calculateAverage(rightAnswerList);
graphView.setAverage(leftAverage);
graphView.setPoints(leftAnswerList);
float rightAverage = calculateAverage(leftAnswerList);
graphView.setAverage(rightAverage);
setResults(leftAnswerList, rightAnswerList);
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Log.d(TAG, "The results were " + results);
Bundle leftbundle = new Bundle();
leftbundle.putString("results", results);
leftbundle.putParcelableArrayList("graph", leftAnswerList);
leftbundle.putFloat("average", leftAverage);
Bundle rightbundle = new Bundle();
rightbundle.putString("results", results);
rightbundle.putParcelableArrayList("graph", rightAnswerList);
rightbundle.putFloat("average", rightAverage);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
LeftEarResults.class, leftbundle);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Right_ear)),
RightEarResults.class, rightbundle);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
}
private StringBuilder setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
String resultCaption;
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the_hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
Log.d(TAG, "The results were " + resultsText);
return resultsText;
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}
My quesiton is how and where should I close the connection?
Thanks
Just alter your storeResults method as follows
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase(); // opens the database connection
try {
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
catch(Exception e) {
e.printStackTrace();
// furher error handling
}
finally {
db.close(); // closes the database every time after access
}
}

Android: Downloaded Images not showing in ListView

I used an AsyncTask to download Images from a URL and I wanted to display those images in a listview using a custom adapter. Everything else is downloading correctly, but the images just won't show in my listview. I tried different links, different methods (setImageDrawable & setImageBitmap) and nothing will work. Hopefully you guys can help me, I will post the relevant code parts.
`private int getEventsLength(String eventsUnformated) {
int count = 0;
int startPos = 0;
String find = "event {";
while (eventsUnformated.indexOf(find, startPos) != -1) {
startPos = eventsUnformated.indexOf(find, startPos) + find.length();
count++;
}
return count;
}
private Event[] getEvents(String eventsUnformated) {
ArrayList<Event> eventList = new ArrayList<Event>();
int startPos = 0;
int eventLength = getEventsLength(eventsUnformated);
for (int i = 0; i < eventLength; i++) {
ArrayList<String> weirdList = new ArrayList<String>();
while (weirdList.size() < 6) {
startPos = eventsUnformated.indexOf(':', startPos) + 1;
weirdList.add(eventsUnformated.substring(startPos, eventsUnformated.indexOf('\n', startPos)).trim());
}
Date eventDate = null;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
eventDate = dateFormat.parse(weirdList.get(2));
}
catch (ParseException ex) { }
try {
new DownloadImageTask().execute(new URL(weirdList.get(4)));
}
catch (MalformedURLException ex) { }
eventList.add(new Event(weirdList.get(0), weirdList.get(1), eventDate, eventImage, weirdList.get(3)));
}
return eventList.toArray(new Event[eventList.size()]);
}
private void populateEventListView() {
ArrayAdapter<Event> adapter = new EventListAdapter();
eventListView = (ListView) findViewById(R.id.listView2);
eventListView.setAdapter(adapter);
}
private class DownloadTask extends AsyncTask<Void, Void, Void> {
String downloadedEvents = "", downloadedChapters = "";
#Override
protected Void doInBackground(Void... params) {
try {
URL eventsUrl = new URL("myUrl/events.txt");
URL chaptersUrl = new URL("myUrl/chapters.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(eventsUrl.openStream()));
String temp = "";
String news = "";
while((temp = reader.readLine()) != null) {
news += temp + "\n";
}
reader.close();
downloadedEvents = news;
news = "";
temp = "";
reader = new BufferedReader(new InputStreamReader(chaptersUrl.openStream()));
while((temp = reader.readLine()) != null) {
news += temp + "\n";
}
reader.close();
downloadedChapters = news;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ViewFlipper newsFlipper = (ViewFlipper) findViewById(R.id.flipperNews);
Event[] Events = getEvents(downloadedEvents);
Chapter[] Chapters = getChapters(downloadedChapters);
TextView[] Labels = new TextView[Events.length];
for (int i = 0; i < Events.length; i++) {
eventList.add(Events[i]);
Labels[i] = makeNews(Events[i].getEventName());
newsFlipper.addView(Labels[i]);
}
for (int i = 0; i < Chapters.length; i++) {
chapterList.add(Chapters[i]);
}
super.onPostExecute(result);
}
}
private class EventListAdapter extends ArrayAdapter<Event> {
public EventListAdapter() {
super(MainActivity.this, R.layout.listview_event, eventList);
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View myView = convertView;
if (myView == null)
myView = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
Event currentEvent = eventList.get(pos);
TextView eventName = (TextView) myView.findViewById(R.id.lblEventName);
eventName.setText(currentEvent.getEventName());
TextView eventHost = (TextView) myView.findViewById(R.id.lblHostName);
eventHost.setText(currentEvent.getHostChapter());
TextView eventDate = (TextView) myView.findViewById(R.id.lblEventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy kk:mm");
eventDate.setText(dateFormat.format(currentEvent.getEventDate()));
TextView eventLocation = (TextView) myView.findViewById(R.id.lblEventLocation);
eventLocation.setText(currentEvent.getEventLocation());
ImageView badge = (ImageView) myView.findViewById(R.id.imgEvent);
badge.setImageDrawable(currentEvent.getEventImage());
return myView;
}
}
private class DownloadImageTask extends AsyncTask<URL,Void, Void> {
#Override
protected Void doInBackground(URL... imageUrls) {
try {
eventImage = Drawable.createFromStream(imageUrls[0].openConnection().getInputStream(), imageUrls[0].toString());
chapterImage = BitmapFactory.decodeStream(imageUrls[0].openStream());
}
catch (MalformedURLException ex) { }
catch (IOException ioException) { }
return null;
}
}`
Change your DownloadImageTask to:
private class DownloadImageTask extends AsyncTask<ImageView,Void, Bitmap> {
private ImageView imageView;
#Override
protected Void doInBackground(ImageView imv) {
URL imageURL = (URL) imv.getTag();
imageView = imv;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)(imageURL.getContent()));
} catch (MalformedURLException e) {
// Invalid URL
} catch (IOException e) {
//Problem with connecting internet, or resource is not available
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap b){
imageView.setImageBitmap(bitmap);
}
}
And in your Adapter:
badge.setImageDrawable(placeHolderImage);
badge.setTag(currentEvent.getImageURL);
new DownloadImageTask().execute(badge);
And of course you have to add getImageURL to your Event class.

android dropbox authentication and upload in different activities

I am trying to upload a file from dropbox in another activity from where i autenticate to dropbox. I have this RegisterActivity.java where the user registers and then later when the registration is completed the webbrowser comes up and the user has to allow the dropbox authentication.
later in my app on another activity the user is going to upload a video to dropbox. the upload is made by ASyncTask and works well. The problem is now that i dont want to reauthenticate again. How do i fix that? Is it on the same session or do i start a new session? Now Iam trying to use the sam mDBApi form RegisterAcitivity but i think that is wrong. The keys are stored in the storeKeys() method and saves them in SharedPreferences.
Thank you very much in advance
Here is my RegisterActivity in pastebin which works. http://pastebin.com/K06JUWXv
Here is the activity that where i call my ASyncTask UploadFile:
public class ShowVideo extends Activity{
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private DropboxAPI<AndroidAuthSession> mDBApi = RegisterActivity.mDBApi;
private String[] storedKeys = getKeys();
UploadFile upload;
public static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
Button dbButton = (Button) findViewById(R.id.dropboxButton);
dbButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(v.getId() == R.id.dropboxButton){
if (mDBApi.getSession().isLinked() == true){
Log.d("ShowVideo", "TRUE");
}
if (mDBApi.getSession().isLinked() == false){
Log.d("ShowVideo", "FALSE");
}
}
}
});
yesButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
}
}
});
noButton.setOnClickListener(new OnClickListener() {
public void onClick(View w) {
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.e("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
});
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
//AndroidAuthSession session = new AndroidAuthSession(new AppKeyPair(ret[0], ret[1]), AccessType.APP_FOLDER);
//mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
}
Here is my ASyncTask if you would take a look at that. Shouldn't be needed.
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private String SAVE_PATH;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dContext = context.getApplicationContext();
dDBApi = mDBApi;
SAVE_PATH = path;
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(SAVE_PATH);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), null);
}
catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
}
}
}
return null;
}
}

Categories

Resources