I've taken a look at most of the questions discussing this but can't seem to find anything that fixes my problem. I have a Custom Array adapter passing data to a list and i need the list to refresh once I've deleted an item, I understand that notifyDataSetChanged() should be my solution but have yet to make it work
sorry for my messy code
but i'm still learning :)
any help would be appreciated, thanx :)
My Adapter:
public class CustomBasketAdapter extends ArrayAdapter<String>
{
private String TAG ="Vik";
public String stringEmail= "";
public String stringStore= "";
private String product = "";
private String quantity = "";
private String store = "";
//String[] stringEmail={"stefan.grobler#gmail.com"};
private final Activity context;
private final String[] storename;
private final String[] itemprice;
private final String[] itemname;
private final String[] productquantity;
private final String[] basketlinetotal;
//public CustomListAdapter(Activity context, String[] itemname,String[] itemprice, Integer[] imgid) {
public CustomBasketAdapter(Activity context, String[] storename,String[] itemprice, String[] productquantity, String[] itemname, String[] basketlinetotal ) {
super(context, R.layout.viewbasket_layout, storename);
// TODO Auto-generated constructor stub
this.context=context;
this.storename=storename;
this.itemprice=itemprice;
this.itemname=itemname;
this.productquantity=productquantity;
this.basketlinetotal=basketlinetotal;
Intent intent = ((Activity) context).getIntent();
if (null != intent)
{
stringEmail = intent.getStringExtra("EmailAddress");
stringStore = intent.getStringExtra("StoreDescription");
}
Toast toast = Toast.makeText(getContext(),stringEmail, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 10);
//toast.show();
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.viewbasket_layout, null,true);
final TextView txtstore = (TextView) rowView.findViewById(R.id.txtstorename);
final TextView txtproduct = (TextView) rowView.findViewById(R.id.txtproduct);
final TextView txtquantity = (TextView) rowView.findViewById(R.id.txtquantity);
TextView txtprice = (TextView) rowView.findViewById(R.id.txtprice);
TextView txttotal = (TextView) rowView.findViewById(R.id.txttotal);
Button btnclear = (Button) rowView.findViewById(R.id.btnclearitem);
txtstore.setText(storename[position]);
txtproduct.setText(itemname[position]);
txtquantity.setText(productquantity[position]);
txtprice.setText(itemprice[position]);
txttotal.setText(basketlinetotal[position]);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
product = txtproduct.getText().toString();
quantity = txtquantity.getText().toString();
store = txtstore.getText().toString();
DeleteFromBasket();
Toast toast = Toast.makeText(getContext(),"Item Cleared", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 10);
toast.show();
notifyDataSetChanged();
}
/*your onclick code*/
});
return rowView;
};
public void ChannelToService()
{
String SOAP_ACTION = "http://tempuri.org/ITHubServ/DeleteFromBasket";
String METHOD_NAME = "DeleteFromBasket";
String NAMESPACE = "http://tempuri.org/";
String URL = "http://www.buh34nart.co.za/THubServ.svc?wsdl";
String OrderLine = "";
try{
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
String basketline = stringEmail + "|" + store + "|" + product.replace("|", "") + "|" + quantity;
//OrderLine = OrderLine.substring(0,OrderLine.length() -1);
Request.addProperty("Line", basketline);
//Request.addProperty("UserPassword", txtPass.getText().toString());
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport= new HttpTransportSE(URL);
Object Response = null;
transport.call(SOAP_ACTION, soapEnvelope);
Response = soapEnvelope.getResponse();
// data = Response.toString().split("[\\x7C]");
//Log.i(TAG, "Result Order: " + Response);
//if(Response.toString().equals("1"))
//{
// runOnUiThread(new Runnable() {
// public void run() {
//Toast toast = Toast.makeText(LoginPage.this,"Incorrect Username/Password" +
//" Login Failed", Toast.LENGTH_LONG);
//toast.setGravity(Gravity.CENTER, 0, 10);
//toast.show();
//Not Registered or psw wrong or email wrong (forgot password)
// }
// });
//}
//else
//{
// if(Response.toString().equals("9"))
// {
// startActivity(new Intent("com.ctc.android.widget.TechnicalError"));
// // Probleem met system Technical
// }
// else
// {
//btnloginclick();
// }
// }
}
catch(Exception Ex) {}
}
public void DeleteFromBasket()
{
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
ProgressDialog progDailog = new ProgressDialog(getContext());
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
ChannelToService();
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
CustomBasketAdapter.this.clear();
CustomBasketAdapter.this.addAll();
CustomBasketAdapter.this.notifyDataSetChanged();
progDailog.dismiss();
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
super.onPreExecute();
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
}
I think that your problem in that you aren't deleting the item in the string array. You should change
CustomBasketAdapter.this.clear();
CustomBasketAdapter.this.addAll();
CustomBasketAdapter.this.notifyDataSetChanged();
By
CustomBasketAdapter.this.remove(item);
CustomBasketAdapter.this.notifyDataSetChanged();
Nevermind I found the solution
what i've done is called the method that builds the list
from within the custom adapter
if(context instanceof ViewBasket){
((ViewBasket)context).GetBasketProducts();
}
because deleting the item only changed the data on the database which passes me the information i needed to request the information again
Related
My app has an itinerary function, the part where you create a new itinerary involves selecting from 2 spinners which drop down to present different options. The data coming from MQsql database and the JSON response is correct for both sets. Currently i have been able to get either one set of the data to load in the correct spinner (being which either just transport info or attraction info but not both), or i have been able to get both sets of data to load but both are displayed in the same 2 spinners. I need them to be separated into there allocated spinners but need help doing this as i dont undertand what im doing wrong.
createItinerary class:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
LayoutInflater myInflator;
View myView;
DBManager db;
myAdapter adapter;
String NAME;
String LOCATION;
String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
TextView TextTime;
String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
new GetTransport().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, 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.go_home){
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
/*
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Entities.remove(position);
finalEntities.remove(position);
loadAttractions();
}
});*/
return myView;
}
}
}
Thank you to anyone who can help me with this.
i want to set the background color of listview using java...
Below is the code in which i want to set the background color of list view.
value in the name,address,varificationtype comes from server.
now i want to set the background color of listview to RED.
I already defined
public class GetLead extends ListActivity implements OnClickListener{
private ProgressDialog pDialog;
// URL to get contacts JSON
// private static String url = "104.25.125.70/verification/getCaf";
// JSON Node names
private static final String TAG_ID = "cid";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
// private static final String TAG_CONTACTS = "contacts";
//
String priority="high";
private static final String TAG_ADDRESS = "address";
private static final String TAG_STATUS = "status";
private static final String TAG_VARTYPE = "verification";
private long backPressedTime = 0;
GlobalClass gclass;
// contacts JSONArray
JSONArray contacts = null;
Button refresh, logout;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_getjson);
// startService(new Intent(this, LocationBackgroundService.class));
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// getting values from selected ListItem
String custid = ((TextView) view.findViewById(R.id.custId))
.getText().toString();
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.address))
.getText().toString();
String verType = ((TextView) view.findViewById(R.id.verificationType))
.getText().toString();
// Starting single contact activity
if(verType.equals("reside")){
Intent in = new Intent(getApplicationContext(),
resideVarStatusUpdate.class);
in.putExtra(TAG_ID, custid);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
}
else if(verType.equals("reside1")){
Intent in = new Intent(getApplicationContext(),
reside1VarStatusUpdate.class);
in.putExtra(TAG_ID, custid);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
}
}
});
// Calling async task to get json
new GetContacts().execute();
refresh = ((Button) findViewById(R.id.refresh));
refresh.setOnClickListener(this);
logout = ((Button) findViewById(R.id.logout));
logout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == refresh){
new GetContacts().execute();
}
else if (v == logout){
this.finish();
}
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(GetLead.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String jsonStr = null;
// get user data from session
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("id",globalVariable.getId()));
// email
try {
jsonStr = SimpleHttpClient
.executeHttpPost(
"http://"+constantVar.ip+"/verification/getCaf",
postParameters);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String status = c.getString(TAG_STATUS);
String varType = c.getString(TAG_VARTYPE);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_ADDRESS, address);
contact.put(TAG_STATUS, status);
contact.put(TAG_VARTYPE, varType);
contact.put("priority", priority);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId,
R.id.name, R.id.address, R.id.verificationType});
if (priority.equals("high")) {
setListAdapter(adapter);
LinearLayout listLayout = (LinearLayout)findViewById(R.id.list_layout);
listLayout.setBackgroundColor(Color.GREEN);
}
}
}
How can I do this only using Java here?
Update your code in onPostExecute()
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(GetLead.this, contactList, R.layout.list_item, new String[]{TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_VARTYPE, priority}, new int[]{R.id.custId,
R.id.name, R.id.address, R.id.verificationType});
if (priority.equals("high")) {
GetLead.this.runOnUiThread(new Runnable() {
#Override
public void run() {
setListAdapter(adapter);
getListView().setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
});
}
}
You should do this in your adapter, override getView like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_event_row_view, parent, false);
convertView.setBackgroundColor(Color.RED);
Now you can set the color of each entry as you wish.
Actually you have to set the layout background color used in xml to set color accordingly.
if (priority.equals("high")) {
LinearLayout listLayout = listItem.findViewByid(R.id.list_layout);
listLayout.setBackground(R.color.Red)
setListAdapter(adapter);
}
I am trying to create a shopping cart app and everything was going great but now i am stuck for last three day did search lot in stackoverflow but could not get a answer.I am populating listview from server and there is two buttons in each row plus(for adding quantity) and minus for (decrements it). This is the screen where i am adding quantity to cart.
I am trying to insert row to sqlite database upon clicking either of two buttons and i have achieved this and i am show these data in next activity inside a listview. Here my problem starts when i insert data it shows it properly but during updation it is showing strange behavior. If i click on first three rows the insertion and updation working fine but if i scroll down and click on any item then instead of updating each time its inserting.. I know this question is quite big and lengthy but i could not find a good way to summarize it sorry.. Please help me thanks ..
This is the screen which i am getting as output.
Here is my ListView class.
public class MyFragment extends Fragment implements View.OnClickListener{
int mCurrentPage;
private ListView listView;
RecyclerView recyclerView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private List<FeedItem> productsInCart = new ArrayList<FeedItem>();
private RelativeLayout content;
private SharedPreferences preference;
TextView badge,prices;
int totalCount=0,newCount = 0;
int lastCount;
int totalPrice;
SQLiteDatabase dataBase;
public static final String TOTAL_COUNT = "count";
DBHelper mHelper;
boolean isUpdate;
String userId,price,pname,position;
private Button checkOut;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
recyclerView= (RecyclerView) v.findViewById(R.id.my_recycler_view);
content = (RelativeLayout)v.findViewById(R.id.content);
badge = (TextView)v.findViewById(R.id.all_comments);
checkOut = (Button)v.findViewById(R.id.checkOut);
prices = (TextView)v.findViewById(R.id.price);
feedItems = new ArrayList<FeedItem>();
new JSONAsyncTask()
.execute("http://api.androidhive.info/feed/feed.json");
listAdapter = new FeedListAdapter(getActivity(), feedItems);
recyclerView.setAdapter(listAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
listAdapter.setOnAddNum(this);
listAdapter.setOnSubNum(this);
mHelper=new DBHelper(getActivity());
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),CheckOutFooter.class);
startActivity(i);
getActivity().overridePendingTransition
(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
}
});
checkOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (userId != null){
Intent i = new Intent(getActivity(),CheckOut.class);
startActivity(i);
}
else{
Toast.makeText(getActivity(), "Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
// TODO Auto-generated method stub
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("feed");
for (int i = 0; i < jarray.length(); i++) {
JSONObject feedObj = jarray.getJSONObject(i);
// Actors actor = new Actors();
FeedItem item = new FeedItem();
item.setObservation(feedObj.optString("name"));
item.setSummary(feedObj.optString("timeStamp"));
item.setName(feedObj.optString("name"));
feedItems.add(item);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false){
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else{
listAdapter.notifyDataSetChanged();
}
pDialog.dismiss();
}
}
#Override
public void onClick(View view) {
Object tag = (Integer) view.getTag();
switch (view.getId()){
case R.id.btnAddToCart1:
// FeedItem item = feedItems.get(tag);
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
String pName = feedItems.get(position).getName();
String product_name = feedItems.get(position).getName();
num++;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
Toast.makeText(getActivity(),
product_name+ " is added to cart!", Toast.LENGTH_SHORT).show();
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("PNAME",product_name).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
break;
case R.id.btnAddToCart5:
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
if (num>0) {
num--;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
else{
num= 0;
dataBase.delete(
DBHelper.TABLE_NAME,
DBHelper.KEY_ID + "="
+ (position+1), null);
listAdapter.notifyDataSetChanged();
}
}
break;
}
}
public void onResume(){
super.onResume();
}
private void updateData() {
preference =
getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
userId = preference.getString("QUANTITY", null);
price = preference.getString("PRICE", null);
pname = preference.getString("PNAME", null);
position = preference.getString("POSITION", null);
int counts = Integer.parseInt(position);
if(userId == null){
badge.setText("0");
}
else{
checkOut.setEnabled(true);
badge.setText(String.valueOf(userId));
dataBase = mHelper.getReadableDatabase();
/*Cursor curs = dataBase.rawQuery("SELECT SUM(price) FROM cart", null);
if(curs.moveToFirst())
{
int total = curs.getInt(0);
System.out.println("Total Sum of Price : "+total);
prices.setText(String.valueOf(total)+" Rs/-");
}
*/
Cursor cur = null;
String query = "SELECT * FROM " + DBHelper.TABLE_NAME +
" WHERE " +DBHelper.KEY_ID+"=?;" ;
cur = dataBase.rawQuery(query,new String[] {String.valueOf(counts+1)});
if((cur != null) && (cur.getCount() > 0)){
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.update(DBHelper.TABLE_NAME, cv, DBHelper.KEY_ID+" = '" +
String.valueOf(counts+1) + "'", null);
cur.close();
}
else{
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.insert(DBHelper.TABLE_NAME, null, cv);
cur.close();
}
}
}
}
My checkout page where i am showing data from sqlite.
public class CheckOut extends AppCompatActivity{
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> product_Name = new ArrayList<String>();
private ArrayList<String> product_Quantity = new ArrayList<String>();
private ArrayList<String> product_Price = new ArrayList<String>();
private ArrayList<Integer> quantityList = new ArrayList<Integer>();
private ArrayList<Integer> amountList = new ArrayList<Integer>();
ListView recyclerView;
TextView quantity;
TextView amount;
Button pay;
DBHelper mHelper;
SQLiteDatabase dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkout);
recyclerView= (ListView) findViewById(R.id.my_recycler_view);
amount = (TextView) findViewById(R.id.amount);
quantity = (TextView) findViewById(R.id.quantity);
pay = (Button) findViewById(R.id.pay);
mHelper = new DBHelper(this);
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DBHelper.TABLE_NAME, null);
int sum = 0;
int qty = 0;
userId.clear();
product_Name.clear();
product_Quantity.clear();
quantityList.clear();
amountList.clear();
product_Price.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_ID)));
product_Name.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PNAME)));
product_Quantity.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_COUNT)));
product_Price.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PRICE)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(CheckOut.this,userId, product_Name, product_Price,product_Quantity);
recyclerView.setAdapter(disadpt);
mCursor.close();
quantityList = convertInteger(product_Quantity);
amountList = converAmountInteger(product_Price);
for (int i : quantityList){
qty = qty+i;
}
for (int s : amountList){
sum = sum +s;
}
amount.setText(String.valueOf(sum));
quantity.setText(String.valueOf(qty));
disadpt.notifyDataSetChanged();
}
private ArrayList<Integer> converAmountInteger(
ArrayList<String> product_Price2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String amount : product_Price2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(amount));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + amount + " can not be an integer");
}
}
return result;
}
private ArrayList<Integer> convertInteger(
ArrayList<String> product_Quantity2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String quantity : product_Quantity2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(quantity));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + quantity + " can not be an integer");
}
}
return result;
}
Database class:
public class DBHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="user.db";
public static final String TABLE_NAME="cart";
public static final String KEY_COUNT="cartItem";
public static final String KEY_PNAME="product_name";
public static final String KEY_ID="id";
public static final String KEY_PRICE="price";
public static final String KEY_CREATED_AT="created_at";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_COUNT+" INTEGER,"
+KEY_PNAME+" TEXT,"+KEY_PRICE+" INTEGER,"+ KEY_CREATED_AT
+ " DATETIME" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
UPDATE :
There was a little mistake i changed the column name instead of i created a unique key and its working fine..
I tried to add textwatcher with filter class but it do not work plz help. I get the json array through the server using the url. the search(filter) doesnt work well.
public class CallDetails extends Activity {
SessionManager session;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
private List<Drivers> driverlist = null;
ListView listview;
ImageButton btback;
DriverAdapter dadapter;
String uid;
String name;
String email;
String odtyp;
static String oid;
Drivers driver;
private EditText editTextFilter;
private static String OUTBOX_URL ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calldetails);
Intent i = getIntent();
oid =i.getStringExtra("orderId");
odtyp =i.getStringExtra("ordertype");
OUTBOX_URL ="http://www.gdrive.com/api/calldetails.php?id="+oid;
//managing session...
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_EMAIL);
uid = user.get(SessionManager.KEY_UID);
btback =(ImageButton)findViewById(R.id.btnBack);
btback.setVisibility(View.INVISIBLE);
// Locate the EditText in listview_main.xml
editTextFilter = (EditText)findViewById(R.id.editTextFilter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editTextFilter.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3){ /* to do*/ }
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*to do*/ }
});
//populating view with data...
//driverList = new ArrayList<Drivers>();
new JSONAsyncTask().execute(OUTBOX_URL);
listview = (ListView)findViewById(R.id.drlist);
dadapter = new DriverAdapter(CallDetails.this, R.layout.list_item, driverList);
listview.setItemsCanFocus(false);
listview.setAdapter(dadapter);
//populating list ends
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), driverList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
public void back(View v){
Intent back = new Intent(getApplicationContext(), SafetyDrive.class);
startActivity(back);
finish();
}
private class DriverAdapter extends ArrayAdapter<Drivers> {
Context context;
int Resource;
LayoutInflater inflater;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
public DriverAdapter(Context context, int layoutResourceId,ArrayList<Drivers> drs) {
super(context, layoutResourceId, drs);
//inflater = ((Activity) context).getLayoutInflater();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = layoutResourceId;
driverList = drs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("in ", "view start");
View item = convertView;
DriverWrapper DriverWrapper = null;
if (item == null) {
DriverWrapper = new DriverWrapper();
item = inflater.inflate(Resource, null);
DriverWrapper.ename = (TextView) item.findViewById(R.id.textName);
DriverWrapper.ephone = (TextView) item.findViewById(R.id.textPhone);
DriverWrapper.mkcall = (ImageButton) item.findViewById(R.id.btnphone);
item.setTag(DriverWrapper);
} else {
DriverWrapper = (DriverWrapper) item.getTag();
}
Drivers driver = driverList.get(position);
DriverWrapper.ename.setText("Name: " + driver.getName());
DriverWrapper.ephone.setText("Phone: " + driver.getPhone());
final String dp = driver.getPhone().trim();
DriverWrapper.mkcall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//making call..
//Log.e("no is", dp);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +dp));
//callIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(callIntent);
//finish();
}
});
return item;
}
class DriverWrapper {
TextView ename;
TextView ephone;
ImageButton mkcall;
//ImageButton msg;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(driverList);
} else {
for (Drivers driver : driverList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
}
class JSONAsyncTask extends AsyncTask {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CallDetails.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//Log.d("in at-", "asynctask");
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("drivers");
if(jarray.length()!=0){
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Drivers driver = new Drivers();
driver.setPhone(object.getString("phone"));
driver.setName(object.getString("emp_name"));
driverList.add(driver);
}
}else{
driver = new Drivers();
driver.setPhone(" ");
driver.setName(" No Driver Place yet");
driverList.add(driver);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
btback.setVisibility(View.VISIBLE);
dadapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class Drivers {
private String name;
private String phone;
public Drivers() {
}
public Drivers(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
actually it wont filter because youve cleared the driverList and then in the else statement you loop to driverList which is already empty. the only thing you can do is create a backup list for the driversList and then use the backup list to get all data for filtering to the driverList.
Example Here:
// here is the backuplist
ArrayList<Drivers> backupList = new ArrayList<Drivers>();
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// actually its easy to just clear the backup list
// but due to reasons where users press backspace you have to load backup list only once
if(backupList.isEmpty()) {
backupList.addAll(driverList);
}
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(backupList);
} else {
for (Drivers driver : backupList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
Hope it helps :)
I have a TimePicker which I'd like to use to determine a length of time a user can stay connected. Lets say the time now is 10:00 if the user selects 11:00 - I'd like the source code below to determine that there are 60 minutes between the current time - and the time selected and set that to a string/long (minutes) which I then have displayed as a textview.
I've coded everything as I thought it should be - however the textview never seems to update with minutes value. Everytime I attempt to view the data - I get a value of 0 not matter what the timepicker is set to.
Anyone have any suggestions? I'm stumped at the moment and I'm not sure what else to try.
ADDEDITDEVICE.JAVA (where the timepicker and minutes determination takes place)
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Date date = new Date();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
date.setMinutes(tp.getCurrentMinute());
date.setHours(tp.getCurrentHour());
Long.toString(minutes);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
}
long minutes = ((new Date()).getTime() - date.getTime()) / (1000 * 60);
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
}
}
VIEW COUNTRY.JAVA (where the minutes data set by the timepicker should be visible)
public class ViewCountry extends NfcBeamWriterActivity {
private static final String TAG = ViewCountry.class.getName();
protected Message message;
NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
private TextView ssidTv;
private TextView combined;
private TextView minutes;
//String timetest = "300";
// String a="\"";
// String b="\"";
// String message1 = a + ssidTv.getText().toString() +"," +
// capTv.getText().toString()+b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("name", true);
editor.putBoolean("cap", true);
editor.putBoolean("code", true);
editor.putBoolean("time", true);
editor.putBoolean("ssid",true);
editor.putBoolean("minutes",true);
editor.putBoolean("timetest",true);
editor.commit();
setDetecting(true);
startPushing();
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (TextView) findViewById(R.id.timeEdit);
codeTv = (TextView) findViewById(R.id.codeText);
ssidTv = (TextView) findViewById(R.id.wifiSSID);
minutes = (TextView) findViewById(R.id.Minutes);
}
#Override
protected void onResume() {
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params) {
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
result.moveToFirst();
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int timeIndex = result.getColumnIndex("time");
int ssidIndex = result.getColumnIndex("ssid");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
timeTv.setText(result.getString(timeIndex));
codeTv.setText(result.getString(codeIndex));
ssidTv.setText(result.getString(ssidIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editItem:
Intent addEditContact = new Intent(this, AddEditDevice.class);
// addEditContact.putExtra(CountryList.ROW_ID, rowID);
// addEditContact.putExtra("name", nameTv.getText());
// addEditContact.putExtra("cap", capTv.getText());
// addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.user1SettingsSave:
Intent Tap = new Intent(this, Tap.class);
startActivity(Tap);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact() {
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector dbConnector = new DatabaseConnector(
ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(Long... params) {
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":" + timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
minutes,
Long.toString(minutes),
ssidTextView.getText().toString());
You have that code to add a contact, BUT in your database conector you have:
public void insertContact(String name,
String cap,
String code,
String time,
long minutes,
String ssid,
String string){
I think that don't match, so this is why don't insert correctly.
BTW i can't comment at the moment because i need 50 reputation.
Regards
USE CREATE TABLE IF NOT EXISTS T/N then your problem wil be solved.
otherwise it will override the current table at the same time all the data will be lost.