Inserting EditText & Spinner data to SQLite? - java

I'm trying to figure out how to capture data from a form using EditText & Spinner's and insert it into a SQLite database. I am able to write the hard coded attributes but when I try to use R.id.fieldName it throws an error due to being an Integer vice a String.
public class PetAdd extends Activity {
DBAdapter db = new DBAdapter(this);
private OnClickListener btnPetAddListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
db.open();
long id;
id = db.insertPet("name", "type", "breed", "sex", "notes");
/**id = db.insertPet(R.id.petName, R.id.SpinnerPetType, R.id.petBreed, R.id.SpinnerPetGender, R.id.EditTextPetAddOptions);*/
db.close();
}
};
I'm still trying to learn all this stuff and my brain is fried from looking at a plethora of online tutorials, examples and Google documentation. If anyone can show me how to do this or direct me to a barney style tutorial that breaks it down for me to understand what's going on, it'd be greatly appreciated.

R.id.fieldName is a numeric reference to the item in your Activity (provided it's part of your layout).
You'll need to call findViewById(R.id.fieldName) to get a refererene to it. You'll also need to cast it to the correct type of view (in your case EditText) and then call getText().toString() on the whole thing.
Putting it all together...
EditText myField = (EditText)findViewById(R.id.userName); //assuming you have a field named userName in your XML
String userNameValue = myField.getText().toString();
Oh, and welcome to Stack... don't forget to mark answers as correct and up-vote them when they're helpful.

If you use R.id.name you are in fact using internally generated int that Android uses. You need the raw data your spinner has.
I suggest you play with getItem and getItemId in your Spinner. If you are using a SimpleAdapter you can expect to get the ID of your item with getItemId.
The implementation of getItem is up to you. I usually use BaseAdapter or in the case of Spinners, ArrayAdapter, which has several convenient methods.
And with the EditText you need to call getText() to the EditText.

Related

The app back to previous page when I attempt to fetch data from another activity

I have 1 adapter file, contain following code:
//When user click detailBtn, it will pass the data to EventDetail page.
holder.detailBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(holder.detailBtn.getContext(), EventDetail.class);
intent.putExtra("eventName", datalist.get(position).getEventName());
intent.putExtra("eventDate", datalist.get(position).getEventDate());
intent.putExtra("eventVenue", datalist.get(position).getEventVenue());
intent.putExtra("eventDesc", datalist.get(position).getEventDesc());
intent.putExtra("eventRole", datalist.get(position).getEventRoles());
intent.putExtra("eventCreator", datalist.get(position).getEventCreator());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
holder.detailBtn.getContext().startActivity(intent);
}
});
The main problem occur here, following code is caused the problem::
So, when I try to access the field "eventRole" and put it in ArrayAdapter in EventDetail java file using following code:
String[] roles = (String[]) getIntent().getStringArrayExtra("eventRole");
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.option_item, roles);
The app jump back to previous page :(
Can anyone help me to look into why it return back to previous activity when I try to access it? I can't find any clue on the logcat it shows to me...
The "eventRole" array is stored as Map Structure in Firestore.
Are you sure that your getEventRoles() method return String[] ? As far as I understood, you have casted getIntent().getStringArrayExtra("eventRole"); to String[] even if getStringArrayExtra() is returning String[], Why ?
I think the problem is in your getEventRoles() method, it might not be returning String[] and you are trying to cast that incompatible type to String[] which is throwing ClassCastException.

Passing data using navigation component - How come I need a values for the constructor when the guide doesn't?

I am using this android guide for passing data between navigation destinations.
You can see in the code snippet below the guide doesn't need any values passed to the constructor, and it sets the values rather than passing them:
#Override
public void onClick(View view) {
EditText amountTv = (EditText) getView().findViewById(R.id.editTextAmount);
int amount = Integer.parseInt(amountTv.getText().toString());
ConfirmationAction action =
SpecifyAmountFragmentDirections.confirmationAction()
action.setAmount(amount)
Navigation.findNavController(view).navigate(action);
}
However, when I am trying to follow this, like the guide directs it insists I put pass elements which I want to only set:
Here is the parts relevant in the nav_graph.xml:
Destination:
Action:
I ask, because even only passing them as parameters or passing them as parameters and setting them as well the program claims it didn't receive one of the elements.
You can use this to pass data(i.e a Bundle) using Navigation Architecture Component
EditText amountTv = (EditText) getView().findViewById(R.id.editTextAmount);
int amount = Integer.parseInt(amountTv.getText().toString());
Bundle bundle = new Bundle();
bundle.putInt("AMOUNT",amount);
findNavController().navigate(R.id.IdOfTheFragemntYouAreTryingToNavigate, bundle, null, null)

Java/Android Arraylist giving addresses

I am trying to display a list in android using guidance from vogella's tutorial for sqlite in android :
this is part of my ProjectListDataSource class (This gets all data from the sqlite database):
public List<ProjectList> getAllProjects() {
List<ProjectList> projects = new ArrayList<ProjectList>();
Cursor cursor = database.query(ProjectListHelper.TABLE_PROJECT_LIST,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
projects.add(cursorToProjectList(cursor));
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return projects;
}
private ProjectList cursorToProjectList(Cursor cursor) {
ProjectList projList = new ProjectList();
projList.setId(cursor.getLong(0));
projList.setProjName(cursor.getString(1));
projList.setProjComment(cursor.getString(2));
projList.setProjDateTime(cursor.getString(3));
return projList;
}
And this is my activity class :
public class ProjectListActivity extends ListActivity implements
OnClickListener {
private static final String TAG = "ProjectListActivity";
private ProjectListDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_projectlist);
Log.d(TAG, "On Creat'd");
init();
}
private void init() {
// Getting data from database and adding to ListView
datasource = new ProjectListDataSource(this);
datasource.open();
List<ProjectList> values = datasource.getAllProjects();
ArrayAdapter<ProjectList> adapter = new ArrayAdapter<ProjectList>(this,
android.R.layout.simple_list_item_activated_1, values);
setListAdapter(adapter);
}
But on doing that I am getting unexpected result like this (see image) :
http://i.imgur.com/tQMooi8.png
But the database has records like this (see image):
http://i.imgur.com/HfY2azs.png
Can anyone please explain and give a solution as to why I cant get the list view to show the records as in the database...
Thanks,
Viney
Basic adapters, like ArrayAdapter or CursorAdapter, will map only one value to a single view. Here, a ProjectList object to a TextView with the id of android.R.id.simple_list_item_activated_1
You need a single layout(for a single view within the ListView) with multiple views to which you will map id, name, date, comment, etc. You need to extend one of the adapters. Preferably BaseAdapter or CursorAdapter.
There are several issues here, depending on what you want to display.
The reason you're seeing the object string reference in your list is because you're using a plain ArrayAdapter, which simply calls toString() on the objects in the array. If you override toString() in ProjectList, you can display what you want (though that's normally not the best way to solve this problem).
Another option which would allow you to keep using a plain ArrayAdapter would be to create an array of strings from the ProjectList objects of the data you want to display. A bit wasteful, but that's another option.
What you normally want to do is extend ArrayAdapter and override getView(). In getView() you assign the data you want to display in the view.
If you want to display all the data from your ProjectList objects in a single list item, you'll also need to create a custom layout to represent the row.

Getting listview ID name

I'm passing a listview in to an onselect but theres a couple of ways it's called from different listviews. So i'm trying to work out which listview is being clicked.
I thought I could do the following however the string thats returned is like com.myapp.tool/id/32423423c (type thing) instead of lvAssets.
Here is what I've got:
#Override
public void onNumberRowSelect(ListView listview, clsNameID stat) {
if(listview.getAdapter().toString().equals("lvGenericAssets")){
} else if(listview.getAdapter().toString().equals("lvAssets")){
} else {
Functions.ShowToolTip(getApplicationContext(),
listview.getAdapter().toString());
}
}
As Emil Adz said in first, you can get the id of your list by calling list.getId();
Then use String idList = getResources().getResourceEntryName(id); and you will be able to get the name of the id you have given to your list
Why wont you just use: list.getId(); if you defined it in the XML file then you should define there an id for you ListView.
If you are doing this from code then you can use the list.setId(); to first set it's id.
Another thing you can do is to add a Tag to your listView: list.setTag("list1");
and latter on distinct this listView using the Tag: list.getTag();

java android load items to listview from database?

Okay so i have a database, and i want it so you can favorite items.
Would i make it so you can save items then it will load it into a list view?
this is my load thing
//Calls the database, gets a list of names.
// if listofnames.size()==0 keep name, otherwise
// change name to first name.
ArrayList<String> nameList = new ArrayList<String>();
favList = db.getName();
if(favList.size()>0){
name.setText(favList.get(0));
But that just sets a text i want it to add items..
You may use ArrayAdapter or SimpleAdapter or BaseAdapter - through which you may bind dataSource (List<T>) to the ListView.
You can do this as follows
public class MyClass extends ListActivity{
public void onCreate(Bundle bundle){
//get the names from database
setListAdapter(new ArrayAdapter<E>(this,R.layout.xml_filename,your_list);
}
}
Remember in this case your xml file should be the TextView (I.e the items what list view should contain). You cannot pass an xml file with a ListView directly.
If you have still some problem, then post your code which can be solved.
You can follow the given link for more clarification.
http://developer.android.com/resources/tutorials/views/hello-listview.html

Categories