Looper.prepare Error on Device Not on Android Emulator - android

I trying to Make One App in which I will be Using CSV to restore to Sqlite Database .
This Code is working Fine on Android Emulator But Not Working On Device.
Please Help I am stuck very badly from last 3 days I am unable to figured out and tried many solution from Google but none of them are working.
public class MainActivity extends ListActivity {
TextView lbl;
DBController controller;
Button btnimport;
ListView lv;
final Context context = this;
ListAdapter adapter;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
controller = new DBController(this);
lbl = (TextView) findViewById(R.id.txtresulttext);
btnimport = (Button) findViewById(R.id.btnupload);
lv = getListView();
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
fileintent.setType("text/csv");
try {
startActivityForResult(Intent.createChooser(fileintent,"Open CSv"),requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity can handle picking a file. Showing alternatives.");
}
}
});
myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"a", "b", "c"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
setListAdapter(adapter);
lbl.setText("");
}
}
/** you were wrong here
* R.id.txtjournalname, R.id.txtjournalissn, R.id.txtjournalif});
in v.xml its
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "tbljournal";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
buffer.readLine();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 4); // defining 3 columns with null or blank field //values acceptance
//Id, Company,Name,Price
String spinnerdata = str[0].toString();
String uniqueid = str[1].toString();
String melting = str[2].toString();
String weight = str[3].toString();
Log.e("data", spinnerdata);
contentValues.put("spinnerdata", spinnerdata);
contentValues.put("uniqueid", uniqueid);
contentValues.put("melting", melting);
contentValues.put("weight", weight);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
}catch (SQLException e)
{
Log.e("Error",e.getMessage().toString());
}
catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
// db.endTransaction();
}
} else {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
// db.endTransaction();
}
}
myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"a", "b", "c"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
setListAdapter(adapter);
lbl.setText("Data Imported");
}
}
}
Below are LogCat
03-15 16:54:27.577 2559-2611/? E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
03-15 16:54:36.185 2559-2620/com.example.arnav.androidcsv.demo E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
03-15 16:54:46.556 2559-2763/com.example.arnav.androidcsv.demo E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
Once I select CSV file from file Manager Nothing Happening it get Stuck .

Related

Take Picture From Camera And Show it to the ImageView Android

before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview

Adding TextView dynamically under the relativeLayout

enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_download_packages, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}

ListView, cursors and null sets

I will go straight to the point. I have 1 class where I have 6 buttons. Each button saves to an SQLiteDatabase some parameters and then it launches an Activity.
The new Activity takes the parameters and queries the database to pull data accordingly. When the activity launches I clear the parameters in order to save them again if I press another or the same button.
If 1 table(which is linked to the button) is empty it returns the message I want. The problem is that if 1 is empty then all the tables return the message even if they have data!!
My 1st class
public class HRecords extends Activity {
SQLiteDatabase myDB=null;
Button tes,con,al,me,pr,va;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.records);
tes=(Button) findViewById(R.id.testbut);
con=(Button) findViewById(R.id.condbut);
al=(Button) findViewById(R.id.albut);
me=(Button) findViewById(R.id.medbut);
pr=(Button) findViewById(R.id.procbut);
va=(Button) findViewById(R.id.vacbut);
Database openHelper = new Database(this);//create new Database to take advantage of the SQLiteOpenHelper class
myDB = openHelper.getWritableDatabase(); // or getWritableDatabase();
myDB=SQLiteDatabase.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READWRITE);//set myDB to aeglea
doclicks();
}
private void doclicks(){
tes.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Tests");
values.put("tazle","user_test");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
con.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medical Conditions");
values.put("tazle","user_cond");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
al.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Allergies");
values.put("tazle","user_all");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
me.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medication");
values.put("tazle","user_med");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
pr.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medical Procedures");
values.put("tazle","user_proc");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
va.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Vaccinations");
values.put("tazle","user_vacc");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
}
}
The second class which as you can see it pulls data from the SQLite database(you can also see the message for empty results "Nothing Added here. Go to the site to add more.")
public class Record extends Activity{
SQLiteDatabase myDB=null;
TextView title=null;
Cursor cur,cur2=null;
ListView list=null;
private ArrayAdapter<String> listAdapter ;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.record);
title = (TextView) findViewById(R.id.recordTitle);
list = (ListView) findViewById(R.id.listView1);
Database openHelper = new Database(this);
myDB = openHelper.getReadableDatabase();
myDB=SQLiteDatabase.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READONLY);
Database db = new Database(getApplicationContext());
cur = fetchOption("SELECT * FROM history_go");
title.setText(cur.getString(cur.getColumnIndex("ton")));
ArrayList<String> itemlist = new ArrayList<String>();
String[] names=null;
//do query
cur2=fetchOption("SELECT * FROM "+cur.getString(cur.getColumnIndex("tazle")));
//check for results
if (cur2.getCount()==0) {
names = new String[] { "Nothing Added here. Go to the site to add more."};
}else{
names = new String[] {cur2.getString(cur2.getColumnIndex("name"))};
}
//add the array as list to the ArrayList
itemlist.addAll( Arrays.asList(names) );
listAdapter = new ArrayAdapter<String>(this, R.layout.item, itemlist);
//if results add the rest
if(cur2.getCount()!=0){
for(int i=0;i<(cur2.getCount()-1);i++){
cur2.moveToNext();
listAdapter.add(cur2.getString(cur2.getColumnIndex("name")));
}
}
// Set the ArrayAdapter as the ListView's adapter.
list.setAdapter(listAdapter);
//remove the navigation history
db.resetHistoryNavigation();
cur.close();
cur2.close();
}
public Cursor fetchOption(String query) throws SQLException {
Cursor mCursor = myDB.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
EDIT
Also, I forgot to mention that if I set the verification conditions as cur2 == null the application crushes because the cursor goes out of bounds(the for loop fires)
I found what was wrong. The empty set was triggering the catch exception and nothing else was received afterwards. So every table was null.
I had to implement multiple try/catch
private void doclicks(){
hr.setOnClickListener(new View.OnClickListener() {
private Database db = new Database(getApplicationContext());
JSONArray allergy,condition,medication,procedure,test,vaccine;
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("uid", cursor.getString(cursor.getColumnIndex("uid"))));
JSONObject response = null;
try {
CustomHttpTask asdf = new CustomHttpTask();
response = asdf.execute("http://192.168.1.4/aeglea/android/history.php", postParameters).get();
if(response.getString("success").equals("1")){
//get JSON Arrays
try{test = response.getJSONArray("test");}catch(Exception e){}
try{allergy = response.getJSONArray("allergy");}catch(Exception e){}
try{condition = response.getJSONArray("condition");}catch(Exception e){}
try{medication = response.getJSONArray("medication");}catch(Exception e){}
try{procedure = response.getJSONArray("procedure");}catch(Exception e){}
try{vaccine = response.getJSONArray("vaccine");}catch(Exception e){}
}
}catch (Exception e) {
Log.e("HHHERPT","YO MAMAA "+e);
}
//temp JSONOnject
JSONObject buffer=null;
//reset older values
db.resetHistory();
//Store values
try{
for(int i=0;i<allergy.length();i++){
buffer=allergy.getJSONObject(i);
db.addRecords("allergy",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
1,
"",
(float) 0.1,
1,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<condition.length();i++){
buffer=condition.getJSONObject(i);
db.addRecords("condition",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")) ,
"",(float) 0.1,
Integer.parseInt(buffer.getString("current")),
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<medication.length();i++){
buffer=medication.getJSONObject(i);
db.addRecords("medication",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
1,
"",
(float) 0.1,
Integer.parseInt(buffer.getString("current")),
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<procedure.length();i++){
buffer=procedure.getJSONObject(i);
db.addRecords("procedure",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
buffer.getString("comments"),
(float) 0.1,
0,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<vaccine.length();i++){
buffer=vaccine.getJSONObject(i);
db.addRecords("vaccine",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
"",
(float) 0.1,
0,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<test.length();i++){
buffer=test.getJSONObject(i);
db.addRecords("test",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
buffer.getString("comments"),
(float) Float.parseFloat(buffer.getString("value")),
1,
1);
}
}catch(Exception e){
}
//create new intent
Intent records = new Intent(getApplicationContext(), HRecords.class);
// Close all views before launching logged
records.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(records);
// Close Login Screen
onPause();
}
});
}

save state of changed database in android application

I am working on an android app, in which the first page is a homepage. On clicking on any item on the homepage, the user can view details in that item. The details are taken from an sqlite database and can be accepted or rejected in the app by the user. On accept or reject by the user, the detail gets deleted from the list of details. But, on clicking back button from the details page, when the user reaches the homepage again, there occurs this problem that when the user clicks on the same item again, it shows all the details without saving state.
E.g. if my item1 has 10 details within it..i view all the 10 details in the details page..then accept 2..so total remain 8..but when i click back and reach the homepage and again click on item1, it shows all 10 again...and does not record the change which occured when 2 were accepted.
How can this be solved?
This is the code that we are working on:
package com.sql.nigel;
import java.util.ArrayList;
public class listActivity extends ListActivity implements
android.view.View.OnClickListener,OnItemClickListener{
private ArrayList<listActivity2> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
private SQLiteDatabase database;
private MySQLiteHelper dbHelper=new MySQLiteHelper(this);
private String[] leave_Col = {"Requester","LeaveType","No_of_Days","FromDate","ToDate"};
private String[] Cart_Col = {"CartNo","Date","Description","TotalValue","TotalTax","BudgetValue","UniqueNo"};
private String[] Time_Col = {"Name","Date","Project","Client","Tasks","FromDate","ToDate"};
private String[] Travel_Col = {"Requester","Purpose","Location","Cost","Date","Description","FromDate","ToDate","Hotel","Taxi","AdditionalExp"};
private String[] Invoice_Col = {"InvoiceNo","VendorName","Date","InvoiceValue","Date","VendorNo","PostingDate","FiscalYear","Pln_Group"};
private String[] Purchase_Col = {"PONo","Date","Vendor","OrderValue","PurchasingOrg","ApprovedVendor","Requester","Notes","RelatedInfo","QualityScore"};
String table_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listactivity);
database = dbHelper.getWritableDatabase();
table_name=this.getIntent().getExtras().getString("activity");
Button backButton = (Button)findViewById(R.id.back);
backButton.setOnClickListener(this);
Button selectButton = (Button)findViewById(R.id.select);
selectButton.setOnClickListener(this);
/* ImageView rightarrow = (ImageView)findViewById(R.id.rightarrow);
rightarrow.setOnClickListener(this);*/
m_orders = new ArrayList<listActivity2>();
this.m_adapter = new OrderAdapter(this, R.layout.listactivity2, m_orders);
setListAdapter(this.m_adapter);
ListView listView=(ListView)findViewById(android.R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(table_name.compareTo("LeaveRequest")==0){
Intent intent = new Intent(listActivity.this, leavedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("Time")==0){
Intent intent = new Intent(listActivity.this, timedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("ShoppingCart")==0){
Intent intent = new Intent(listActivity.this, cartdetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("Invoice")==0){
Intent intent = new Intent(listActivity.this, invoicedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("PurchaseOrder")==0){
Intent intent = new Intent(listActivity.this, purchasedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("Travel")==0){
Intent intent = new Intent(listActivity.this, traveldetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}
}
});
viewOrders = new Runnable(){
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
}
private Runnable returnRes = new Runnable() {
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
m_orders = new ArrayList<listActivity2>();
if(table_name.compareTo("LeaveRequest")==0){display_Leave();
}else if(table_name.compareTo("Time")==0){display_Time();
}else if(table_name.compareTo("ShoppingCart")==0){display_Cart();
}else if(table_name.compareTo("Invoice")==0){display_Invoice();
}else if(table_name.compareTo("PurchaseOrder")==0){display_Purchase();
}else if(table_name.compareTo("Travel")==0){display_Travel();
}
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
database.close();
}
public void display_Leave(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Leave Request");
Cursor c_L = database.query("LeaveRequest",leave_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2(""+c_L.getString(2)+" days");
o1.setOrdertext3(""+c_L.getString(1)+" ");
o1.setOrdertext4(""+c_L.getString(3)+" to "+c_L.getString(4));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Time(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Time Booking");
Cursor c_L = database.query("Time",Time_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2(""+c_L.getString(3));
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(1));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Cart(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Shopping Cart");
Cursor c_L = database.query("ShoppingCart",Cart_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2("");
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(1));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Invoice(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Invoice Approval");
Cursor c_L = database.query("Invoice",Invoice_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(1));
o1.setOrdertext2("");
o1.setOrdertext3(""+c_L.getString(0)+" ");
o1.setOrdertext4(""+c_L.getString(2));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Purchase(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Purchase Order");
Cursor c_L = database.query("PurchaseOrder",Purchase_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2(""+c_L.getString(3));
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(1));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Travel(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Travel Approval");
Cursor c_L = database.query("Travel",Travel_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(1));
o1.setOrdertext2(""+c_L.getString(3));
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(4));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
private class OrderAdapter extends ArrayAdapter<listActivity2> {
private ArrayList<listActivity2> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<listActivity2> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listactivity2, null);
}
listActivity2 o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.textList1);
TextView t2 = (TextView) v.findViewById(R.id.textList2);
TextView t3 = (TextView) v.findViewById(R.id.textList3);
TextView t4 = (TextView) v.findViewById(R.id.textList4);
if (t1 != null) {
t1.setText(o.getOrdertext1());
}
if(t2 != null){
t2.setText(o.getOrdertext2());
}
if(t3 != null){
t3.setText(o.getOrdertext3());
}
if(t4 != null){
t4.setText(o.getOrdertext4());
}
}
return v;
}
}
public void onClick(View v) {
switch(v.getId())
{
case R.id.back:
Intent backIntent = new Intent(listActivity.this, SqlTwoActivity.class);
startActivity(backIntent);
break;
case R.id.select:
Intent selectIntent = new Intent(listActivity.this, checkappear.class);
selectIntent.putExtra("checkappear", table_name);
startActivity(selectIntent);
break;
/*
case R.id.rightarrow:
Intent rightarrow = new Intent(listActivity.this, listActivity.class);
startActivity(rightarrow);
break;*/
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Hard to find database calls in your code. Some general guidelines:
First you need to encapsulate all calls to the Database in separate threads.
Always close your cursors and DB connection after you're finished.
Best would be to use AsyncTask. Check out some tutorials for using SQLite with AsyncTask - it will handle the separate Thread automatically for you.
Second - read about the Activity Stack, so that what #Peter tells you makes sense.

android delete item from list [duplicate]

This question already has answers here:
Android expandable list need help to delete item
(2 answers)
Closed 8 years ago.
public class DeleteActivity extends ExpandableListActivity {
private RingtoneAdapter expListAdapter;
int myProgress = 0;
List<String> items = new ArrayList<String>();
final Context myApp = this;
// private static final String DIRECTORY = "/system/media/audio/ringtones/";
private static final String DIRECTORY = "/sdcard/download/";
private MediaPlayer mp = new MediaPlayer();
List<String> Ringtones = new ArrayList<String>();
ArrayAdapter<String> adapter;
TextView tv, empty;
ExpandableListView exlv1;
// ListView lv1;
Boolean hasErrors = false;
int currentPosition = 0;
private static final String LOG_TAG = "MobiIntheMorning";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
refreshList();
Toast.makeText(this, "hello this is delete called", Toast.LENGTH_LONG).show();
Ringtones.remove(DIRECTORY+Ringtones.get(1));//THIS DOSE NOT GIVING ANY AFFECT
refreshList();
Intent i = new Intent(DeleteActivity.this, FindFilesByType.class);
startActivity(i);
}
public void refreshList() {
File ringtones_directory = new File(DIRECTORY);
if (!ringtones_directory.exists()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Directory Not Found");
ad.setMessage("Sorry! The ringtones directory doesn't exist.");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
}
if ( !ringtones_directory.canRead()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! You don't have permission to list the files in that folder");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
} else {
Ringtones = FindFiles(false);
if (Ringtones.size() < 1) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! No ringtones exists in " + DIRECTORY
+ ".");
ad.setPositiveButton("OK", null);
ad.show();
Log.e(LOG_TAG, "No ringtones were found.");
hasErrors = true;
}
}
try {
if ( !hasErrors) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
DeleteActivity.this, android.R.layout.test_list_item,
Ringtones);
ArrayList<String> GrouppList = new ArrayList<String>();
GrouppList.addAll(Ringtones);
ArrayList<ArrayList<Color>> colors = new ArrayList<ArrayList<Color>>();
for (int i = 0; i <= Ringtones.size(); i++) {
ArrayList<Color> color = new ArrayList<Color>();
color = new ArrayList<Color>();
color.add(new Color("", "", true));
colors.add(color);
}
expListAdapter = new RingtoneAdapter(this, GrouppList, colors);
Toast.makeText(this, GlobalVariable.getstrEmail(),
Toast.LENGTH_LONG).show();
Ringtones.remove(0);
// setListAdapter(expListAdapter);
exlv1 = (ExpandableListView) findViewById(R.id.expandableListView1);
this.exlv1.setAdapter(this.expListAdapter);
}
this.exlv1.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
Toast.makeText(DeleteActivity.this, "hello" + arg0,
Toast.LENGTH_LONG).show();
GlobalVariable.SetcurrentPosition(arg0);
GlobalVariable.SetstrEmail(DIRECTORY + Ringtones.get(arg0));
}
});
} catch (Exception e) {
Toast.makeText(this, "Error " + e.toString(), Toast.LENGTH_LONG)
.show();
Log.i(LOG_TAG, e.toString());
}
}
private List<String> FindFiles(Boolean fullPath) {
final List<String> tFileList = new ArrayList<String>();
Resources resources = getResources();
// array of valid audio file extensions
String[] audioTypes = resources.getStringArray(R.array.audio);
FilenameFilter[] filter = new FilenameFilter[audioTypes.length];
int i = 0;
for (final String type : audioTypes) {
filter[i] = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("." + type);
}
};
i++;
}
FileUtils fileUtils = new FileUtils();
File[] allMatchingFiles = fileUtils.listFilesAsArray(
new File(DIRECTORY), filter, -1);
for (File f : allMatchingFiles) {
if (fullPath) {
tFileList.add(f.getAbsolutePath());
} else {
tFileList.add(f.getName());
}
}
return tFileList;
} // find fil
#SuppressWarnings("unchecked")
public List<String> loadArray(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
List<String> read_field = (List<String>) in.readObject();
in.close();
return read_field;
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
public Collection<File> listFiles(File directory, FilenameFilter[] filter,
int recurse) {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
for (FilenameFilter filefilter : filter) {
if (filter == null
|| filefilter.accept(directory, entry.getName())) {
files.add(entry);
Log.v(LOG_TAG, "Added: " + entry.getName());
}
}
if ((recurse <= -1) || (recurse > 0 && entry.isDirectory()))
files.addAll(listFiles(entry, filter, recurse - 1));
}
}
return files;
}
public class FileUtils {
public void saveArray(String filename, List<String> output_field) {
try {
FileOutputStream fos = new FileOutputStream(filename);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(output_field);
out.flush();
out.close();
} catch (IOException e) {
e.getStackTrace();
}
}
public File[] listFilesAsArray(File directory, FilenameFilter[] filter,
int recurse) {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
}
}
I've done some code that code fetches .mp3 files from the sdcard and displays it to me
now i am trying to delete selected item from it using
Ringtones.remove(DIRECTORY+Ringtones.get(1));
that is it should delete my first item from the list but it doesn't works for me
what is wrong i ma doing into this?
I am not able to find any silly mistakes I made here; Ringtones.remove("test.mp3"); and Ringtones.remove(1.mp3); both I've also tried.
Why are you doing
DIRECTORY + Ringtones.get(1)
Ringtones is a List so you want to be doing something like
Ringtones.remove(1);
or
Ringtones.remove(aRintoneString)
what you effectively doing here is getting the first element and adding a other string which gives you a NEW third string that doesn't exist in Ringtones
Hi Call notifyDataSetChanged() on your Adapter after removing the item from the List.
It will refresh your List and you will get updated items in your list.

Categories

Resources