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();
}
});
}
Related
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 .
I take input in an edittext, that is in a popup window. On dismiss of that popup, the string in edittext should be updated in db at required postion.
Popup Window code:
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popl,(ViewGroup)findViewById(R.id.pop));
final PopupWindow pw = new PopupWindow(layout, 700 * (metrics.widthPixels/1080) , 300 * (metrics.heightPixels/1080) , true);
int coord[]= new int[2];
v.getLocationOnScreen(coord);
pw.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getApplicationContext(), android.R.color.transparent)));
pw.setOutsideTouchable(true);
pw.showAtLocation(v, Gravity.NO_GRAVITY, coord[0] + 50 ,coord[1]+100);
Button del = (Button) layout.findViewById(R.id.del);
Button viewImage = (Button) layout.findViewById(R.id.view);
final EditText notes = (EditText) layout.findViewById(R.id.note);
notes.setText(data[6]);
notedata = data[6];
del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = dBcontract.getWritableDatabase();
if ((thisimageuri!=null)&&(thisimageuri.toString().charAt(0)!='a'))
deleteimage(thisimageuri);
Log.d("delete operaiton",String.valueOf(db.delete(eventDBcontract.ListofItem.tableName,eventDBcontract.ListofItem.columnID+" = "+data[4],null)));
recreate(); //add option to delete files as well
}
});
viewImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (thisimageuri!=null)
{
Intent intent = new Intent(getApplicationContext(),showPic.class);
intent.putExtra("photo uri",thisimageuri);
notedata = notes.getText().toString();
pw.dismiss();
startActivity(intent);
}
}
});
pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
notedata = notes.getText().toString();
Log.d("popop window", "onDismiss: " + notedata);
interact.savenote(data[4],notedata);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Method to save in database:
public void savenote(String id , String note)
{
ContentValues values = new ContentValues();
SQLiteDatabase db = dBcontract.getWritableDatabase();
values.put(eventDBcontract.ListofItem.columnnotes,note);
db.update(eventDBcontract.ListofItem.tableName,values,"id=?",new String[]{id});
Log.d("Interact","add note complete " + note);
}
The code works correctly,i.e note is saved correctly in db, when i click on view image but not when I click outside of popup to dismiss it.
Log:
04-14 00:12:24.569 9517-9517/lcukerd.com.stufflist D/popop window: onDismiss: Yu
04-14 00:12:24.569 9517-9517/lcukerd.com.stufflist D/Interact: add note complete Yu
Help me spot the issue. This is eating my brain.
EDIT 1:
data[4] is the id of entry in db to be updated.
data[6] is the old value of "note" as saved in db.
TextView desc,details,responsibility,status,txtdate;
EditText equipment_id;
DBController controller = new DBController(this,null,null,1);
ImageButton btnupdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_update_equiments);
equipment_id = (EditText)findViewById(R.id.txtequipmentid);
desc = (TextView)findViewById(R.id.txtdescription);
details = (TextView)findViewById(R.id.txtdetails);
status = (TextView)findViewById(R.id.txtstatus);
txtdate = (TextView)findViewById(R.id.txtdate);
responsibility = (TextView)findViewById(R.id.txtresponsibilitycenter);
btnupdate = (ImageButton)findViewById(R.id.btnupdate);
//desc.setVisibility(View.GONE);
//details.setVisibility(View.GONE);
// responsibility.setVisibility(View.GONE);
// btnupdate.setVisibility(View.GONE);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
txtdate.setText(formattedDate);
//update data
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//String status = "1";
controller = new DBController(getApplicationContext(), null, null ,1);
SQLiteDatabase database = controller.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("description", desc.getText().toString());
data.put("details", details.getText().toString());
data.put("responsibility_center",responsibility.getText().toString());
data.put("status", status.getText().toString());
data.put("date_taken", txtdate.getText().toString());
database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
//database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
Toast.makeText(Search_Equipments.this, "Updated successfully", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(Search_Equipments.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//search equipment
public void searchEquipment(View view){
if (equipment_id.getText().toString().equals("")){
Toast.makeText(Search_Equipments.this,"Please Enter Equipement No.",Toast.LENGTH_LONG).show();
} else {
controller = new DBController(this, null, null , 1);
Equipment equipment = controller.getEquipment(equipment_id.getText().toString());
if (equipment != null){
desc.setText(String.valueOf(equipment.get_description()));
details.setText(String.valueOf(equipment.get_details()));
responsibility.setText(String.valueOf(equipment.get_responsibility()));
desc.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
responsibility.setVisibility(View.VISIBLE);
btnupdate.setVisibility(View.VISIBLE);
}else {
Toast.makeText(Search_Equipments.this,"Not Found",Toast.LENGTH_LONG).show();
}
}
}
can someone help my code. if passed the condition that data successfully updated but when i display the updated data from database data has not updated, can someone help me to fix this. . . . . . because i dont where is my error there. see my update code. thanks :)
You forgot to commit the transaction.
database.setTransactionSuccessful();
database.endTransaction();
I have been making ringtone application and I have a problem. I can play sounds in listitem and I can set ringtone but when I check from telephone settings, it doesn't play. Where is the problem, thanks.
public class AndroidListViewActivity extends ListActivity {
int [] sesdosya;
MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sesdosya= new int[] {R.raw.aramabeni,R.raw.azsonra,R.raw.baglama,R.raw.crank,R.raw.haha,R.raw.hippopchicken,R.raw.nokiaturkish,R.raw.nuri,
R.raw.policemix,R.raw.polistelsiz,R.raw.ramiz,R.raw.veryfunnybaby,R.raw.wahwah,R.raw.walawalabingbang,R.raw.windowsmusic};
// storing string resources into Array
String[] sesler = getResources().getStringArray(R.array.sesler);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, sesler));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent intent = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
intent.putExtra("position", position);
startActivity(intent);
}
private String getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
});
}
}
Other class; (Play and set ringtone)
public class SingleListItem extends Activity{
int [] sesdosya;
String[] sesisim;
MediaPlayer mediaPlayer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sesisim = new String[] {"aramabeni","azsonra","baglama","crank","haha","hippopchicken","nokiaturkish","nuri","policemix",
"polistelsiz","ramiz","veryfunnybaby","wahwah","walawalabingbang","windowsmusic"};
sesdosya= new int[] {R.raw.aramabeni,R.raw.azsonra,R.raw.baglama,R.raw.crank,R.raw.haha,R.raw.hippopchicken,R.raw.nokiaturkish,R.raw.nuri,
R.raw.policemix,R.raw.polistelsiz,R.raw.ramiz,R.raw.veryfunnybaby,R.raw.wahwah,R.raw.walawalabingbang,R.raw.windowsmusic};
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
mediaPlayer = MediaPlayer.create(this, sesdosya[position]);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
mediaPlayer.start();
//start the progress dialog
}
});
Button zil = (Button) findViewById(R.id.btnzilsesi);
zil.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
setRingtone(sesdosya[position]);
//start the progress dialog
}
});
}
#SuppressLint("SdCardPath")
public boolean setRingtone(int p){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(p);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path=Environment.getExternalStorageDirectory().getPath()+"/sdcard/media/audio/ringtones/";
String filename=sesisim+".mp3";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE,filename);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "test1");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION,false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
SingleListItem.this,
RingtoneManager.TYPE_RINGTONE,
newUri
);
return true;
}
}
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.