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.
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'm working with nfc tags that when I scan a nfc tag, tag content stored in string and match the string with listview contents if the string matches with listview contents then the background of the listview item color changes to green.
I already wrote the code to get tag content in to a string I have listview in which there are some contents if the tag content matches with the content in the Listview it turns the background listview item color into green, the problem we got is that Even though a single compartment is being scanned multiple items are turning green but when clicking on done button only the scannned compartment is being registered Its just happening when we scroll
Here is the code :
public class Main15Activity extends AppCompatActivity {
ListView l1;
TextView t1;
Button b1;
String tagcontent,rname;
Context ctx = this;
Databaseop mydb;
ArrayAdapter<String> listAdapter;
private NfcAdapter nfcAdapter;
ArrayList<String> theList,arrayList;
int flag=0;
Databaseop dp;
int counter;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main15);
l1 = (ListView) findViewById(R.id.listview3);
b1 = (Button) findViewById(R.id.button14);
//b2 = (Button) findViewById(R.id.button30);
t1 = (TextView) findViewById(R.id.textView2);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this,
"NFC NOT supported on this devices!",
Toast.LENGTH_LONG).show();
finish();
} else if (!nfcAdapter.isEnabled()) {
Toast.makeText(this,
"NFC NOT Enabled!",
Toast.LENGTH_LONG).show();
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
finish();
}
mydb = new Databaseop(Main15Activity.this);
final String rname = getIntent().getStringExtra("rname");
t1.setText(rname);
dp = new Databaseop(ctx);
mydb = new Databaseop(Main15Activity.this);
Cursor data = mydb.getListContents(dp, rname);
if (data.getCount() == 0) {
Toast tos=Toast.makeText(Main15Activity.this, "There are no contents in this list!", Toast.LENGTH_LONG);
tos.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
LinearLayout toastLayout = (LinearLayout) tos.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(20);
tos.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
tos.show();;
} else {
while (data.moveToNext()) {
String theListcon = data.getString(0);
Intent intent=getIntent();
//String user=intent.getStringExtra("name");
final String rid=intent.getStringExtra("rid");
final String[] contents = convertStringToArray(theListcon);
for (int j = 0; j <= contents.length - 1; j++) {
String cmp=contents[j];
dp = new Databaseop(ctx);
dp.reports2(dp,rid,cmp);
}
//arrayList=new ArrayList<>(Arrays.asList(contents));
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contents){
public View getView(int position , View convertView, ViewGroup parent){
View view=super.getView(position, convertView, parent);
TextView textView=(TextView)view.findViewById(android.R.id.text1);
textView.setTextColor(Color.WHITE);
textView.setTypeface(null, Typeface.BOLD);
//textView.setBackgroundColor(Color.RED);
String content=getItem(position);
if(content.equals(tagcontent))
{
// int dkgrn=006400;
textView.setBackgroundColor(getResources().getColor(R.color.DARKGREEN));
Databaseop dp = new Databaseop(ctx);
dp.repoupdt(dp,tagcontent,rid);
Toast tos1= Toast.makeText(Main15Activity.this,tagcontent+" is Visited",Toast.LENGTH_SHORT);
tos1.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
LinearLayout toastLayout = (LinearLayout) tos1.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(20);
tos1.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
tos1.show();
}
//Toast.makeText(Main15Activity.this, "Location not on route", Toast.LENGTH_SHORT).show();
return view;
}
};
l1.setAdapter(listAdapter);
}
}
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=getIntent();
String rid=intent.getStringExtra("rid");
Cursor data1 = dp.getstatcnt(Integer.parseInt(rid));
data1.moveToNext();
final int theListcon = Integer.parseInt(data1.getString(0));
final int j= l1.getAdapter().getCount();
dp.updatereport(dp,rid,theListcon,j);
dp.updateendtime(dp,rid);
new AlertDialog.Builder(Main15Activity.this).setTitle("Warning")
.setMessage("Viseted "+theListcon+" out of "+j+ " Compartments \n Are you sure you want to end rounds?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Main15Activity.this, ""+theListcon+"/"+j,
Toast.LENGTH_LONG).show();
Intent i=new Intent(Main15Activity.this,MainActivity.class);
startActivity(i);
}
}).setNegativeButton("No", null).show();
}
});
}
public static String strSeparator = ", ";
public static String[] convertStringToArray(String str) {
String[] arr = str.split(strSeparator);
return arr;
}
#Override
protected void onNewIntent(Intent intent) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag == null) {Toast.makeText(this,"no ndef message",Toast.LENGTH_SHORT).show();
} else {
Parcelable[] parcelables=intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(parcelables!=null && parcelables.length>0){
readTextFromTag((NdefMessage)parcelables[0]);
}else{Toast.makeText(this,"no ndef message",Toast.LENGTH_SHORT).show();}
}
super.onNewIntent(intent);
}
private void readTextFromTag(NdefMessage ndefMessage) {
NdefRecord[] ndefRecords=ndefMessage.getRecords();
if(ndefRecords!=null&&ndefRecords.length>0){
NdefRecord ndefRecord=ndefRecords[0];
String tagcontent=gettextfromNdefrecord(ndefRecord);
}else {
Toast.makeText(this,"no ndef message",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
Intent intent = new Intent(this, Main15Activity.class);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
super.onResume();
}
#Override
protected void onPause() {
nfcAdapter.disableForegroundDispatch(this);
super.onPause();
}
public String gettextfromNdefrecord(NdefRecord ndefRecord) {
try {
byte[] payload = ndefRecord.getPayload();
String textencoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
int languageSize = payload[0] & 0063;
tagcontent = new String(payload, languageSize+1, payload.length - languageSize-1 , textencoding);
listAdapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
Log.e("gettextfromndefrecord", e.getMessage(), e);
}
return tagcontent;
}
#Override
public void onBackPressed() {
// Simply Do noting!
Toast toast=Toast.makeText(Main15Activity.this,"you cannot go back from here",Toast.LENGTH_LONG);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toastTV.setTextSize(20);
toast.show();
}
}
You have to check for other case too
You're setting the background color for a condition and you should set another color for the latter condition.
if(content.equals(tagcontent)){
textView.setBackgroundColor(getResources().getColor(R.color.DARKGREEN));
}
else{
textView.setBackgroundColor(getResources().getColor(R.color.WHITE));
}
I have a listView in Activity A as shown below.
When the first list is clicked, it should display 3 on editText. But it displays 5 which was actually getting from the last list.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new
AdapterView.OnItemClickListener() { // when list is pressed, intent to B
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
mClickedPosition = position;
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) { // receive from B
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
// m_listItems.clear();
if (mClickedPosition == -1) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // receive from C
}
Use you ArrayList to extract String at position of ListView like..
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
mClickedPosition = position;
String result = m_listItems.get(position); //add this
result = result.substring(2);
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("result", result); // your intent stuff
}
}
});
I'm having a listview that shows my model items that I filled with the contentprovider (inbox). Now when I'm in my broadcastreceiver and I get an update I would like to let the listview know that he must update his List off models and show it.
I've seen that you can do this with notifyChanged but I can't find a good example.
Can someone help me out on this?
EDIT:
SMSBroadcastReceiver:
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (messages.length < 0) {
return;
}
SmsMessage sms = messages[0];
String body = "";
String sender = sms.getOriginatingAddress().toString();
Long time_rcv = sms.getTimestampMillis();
try {
if (messages.length == 1 || sms.isReplace()) {
body = sms.getDisplayMessageBody();
} else {
StringBuilder bodyText = new StringBuilder();
for (int i = 0; i < messages.length; i++) {
bodyText.append(messages[i].getMessageBody());
}
body = bodyText.toString();
}
} catch (Exception e) {
}
ContentValues smsValues = new ContentValues();
smsValues.put("address", sender);
smsValues.put("body", body);
smsValues.put("date_sent", time_rcv);
context.getContentResolver().insert(BlacklistConstants.smsInboxUri, smsValues);
From here I want to the let my fragment know that there is a new sms added.
Thats the .insert gives me back.
This is the fragment this function fills my smsList that contains my models.
private void fetchBox(Conversations smsConversation, String thread_id, Uri threadUri) {
//Cursor smsInThreads = getActivity().getContentResolver().query(threadUri, null, "thread_id = ?", new String[]{thread_id}, null);
CursorLoader cursorLoader = new CursorLoader(getActivity(), threadUri,
null, // the columns to retrieve (all)
"thread_id = ?", // the selection criteria (none)
new String[]{thread_id}, // the selection args (none)
null // the sort order (default)
);
Cursor smsInThreads = cursorLoader.loadInBackground();
if (smsInThreads.moveToFirst()) {
smsConversation.setNumber(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("address")));
for (int x = 0; x < smsInThreads.getCount(); x++) {
smsObjects msg = new smsObjects();
msg.setBody(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("body")));
msg.setNumber(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("address")));
msg.setId(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("_id")));
msg.setTimeStampReceived(smsInThreads.getString(smsInThreads.getColumnIndexOrThrow("date_sent")));
smsConversation.addTextMessage(msg);
smsInThreads.moveToNext();
}
}
//smsList.add(smsConversation);
smsInThreads.close();
}
And finally this is my custom adapter:
public class ListAdapter extends ArrayAdapter<Conversations> {
private String TAG = ListAdapter.class.getName();
private final Context context;
private final List<Conversations> smsList;
public ListAdapter(Context context, List<Conversations> smsList) {
super(context, R.layout.sms_inbox, smsList);
this.context = context;
this.smsList = smsList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.sms_inbox, parent, false);
holder = new ViewHolder();
holder.senderNumber = (TextView) convertView.findViewById(R.id.smsNumberText);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.senderNumber.setText(smsList.get(position).getNumber());
return convertView;
}
private static class ViewHolder
{
public TextView senderNumber;
}
#Override
public int getCount() {
return smsList != null ? smsList.size() : 0;
}
}
Now I don't know how to easy let the fragment know that there is a new insert and that the listview needs to update his model and show it.
I did this in the past like this:
Uri newSms = context.getContentResolver().insert(BlacklistConstants.smsInboxUri, smsValues);
Log.d(TAG,newSms.toString());
Intent smsReceiveIntent = new Intent(BlacklistConstants.smsFilter);
smsReceiveIntent.putExtra("newSMS",newSms);
context.sendBroadcast(smsReceiveIntent);
And then on my fragment I listened to that intent and added it to the smsList and then did notifyDataChanged. But I think there is a better way not?
I solved this by starting an intent in the onreceive and then in the main listen to that intent and update the list.
In the onreceive:
Intent smsReceiveIntent = new Intent(BlacklistConstants.smsFilter);
smsReceiveIntent.putExtra("newSMS",newSms.toString());
context.sendBroadcast(smsReceiveIntent);
and in the activity where you can update the listview:
// Sets up the smsreceiver broadcastreceiver
private void setupSmsReceiver() {
smsReceiver = new BroadcastReceiver() {
public void onReceive(Context context, final Intent intent) {
Log.d(TAG, "onReceive smsReceiver");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "runOnUiThread");
String uri = intent.getStringExtra("newSMS");
addToList(uri);
smsAdapter.notifyDataSetChanged();
}
});
}
}
};
getActivity().registerReceiver(smsReceiver, new IntentFilter(BlacklistConstants.smsFilter));
}
What I do is to use a ContentObserver in the class that hosts the list, like this
(NOTE: this code goes inside a fragment)
private static final int REFRESH_PAGES = 1;
private static final int CHANGE_CURRENT_SET = 2;
private myCustomObserver mContentObserver;
//utility function to set de observer
// register a un content observer to know that the content has changed
private void registerContentObserver(int myId) {
Log.v(DEBUG_TAG, "registerContentObserver, myId=" + myId);
if (mContentObserver != null) {
getActivity().getContentResolver().unregisterContentObserver(
mContentObserver);
}
mContentObserver = new MyCustomObserver (mHandler);
getActivity().getContentResolver().registerContentObserver(
yourUri, true,
mContentObserver);
}
...... this is the content observer
class MyCustomObserver extends ContentObserver {
public MyCustomObserver(Handler handler) {
super(handler);
Log.v(DEBUG_TAG, "MyCustomObserver");
}
#Override
public void onChange(boolean selfChange) {
Log.i(DEBUG_TAG, "onChange, selfChange==" + selfChange);
super.onChange(selfChange);
Message msg = mHandler.obtainMessage(REFRESH_PAGES);
mHandler.sendMessage(msg);
};
#SuppressLint("NewApi")
#Override
public void onChange(boolean selfChange, Uri uri) {
Log.v(DEBUG_TAG, "onChange, selfChange==" + selfChange + ", uri=="
+ uri.toString());
final Message msg = mHandler.obtainMessage(REFRESH_PAGES);
mHandler.sendMessage(msg);
super.onChange(selfChange, uri);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
}
I also need a handler :
public Handler mHandler = new Handler() {
#Override
public void handleMessage(android.os.Message msg) {
Log.v(DEBUG_TAG, "mHandler");
if (isAdded()) {//IMPORTANT if you are in a fragment
switch (msg.what) {
case REFRESH_PAGES:
getLoaderManager().getLoader(0).forceLoad();
break;
case CHANGE_CURRENT_SET:
firstTime = true;
doYourStaff();
break;
}
}
};
};
in the Content Provider you need something like :
getContext().getContentResolver()
.notifyChange(yourUri, null);
e voilĂ ...
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();
}
});
}