App Engine datastore to Android listview - java

I have set up a basic entity class in my App Engine backend.
`#Entity`
`public class Club {`
`#Id`
`private int id;`
`private String clubName;`
`public Club() {`
`}`
`public int getId() {`
`return id;`
`}`
`public void setId(int id){
this.id =id;
}`
`public String getClubName() {
return clubName;
}`
`public void setClubName(String clubName) {
this.clubName = clubName;
}
}`
I have generated the cloud endpoint class and generated the cloud endpoint library.
I want to be able to populate the clubName from the datastore into a listview in android but not sure how to do this.
I'm trying to follow this https://developers.google.com/appengine/docs/java/endpoints/consume_android but so far I am unable to understand what to do. I'm new to this and would be greatful if anyone lead me in the right direction please.

You can use the below steps to achieve your objective:
1, As mentioned in the google doc on consuming cloud endpoints in android, ready your app by adding the required libraries and make API calls and then on getting data from your backend, you can store that data into a SQL database. You can do this step in the onpostexecute method of your asynch task
protected void onPostExecute(ScoreCollection scores) {
// Do something with the result. maybe the store the data to sqlite database
}
}
To know how to store data in SQLITe database please refer http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
http://www.vogella.com/articles/AndroidSQLite/article.html
2, Now query data from your SQLITE db into a cursor and then use a simplecursoradapter to display the data from cursor on a listview in your layout or activity screen
An approximate piece of code will have steps like below:
yourcursor = yourdatabase.query; //this is the cursor returned from querying your db
adapter = new SimpleCursorAdapter(this.getActivity(), R.layout.onerowinalistview, yourcursor, FROM, TO,0); // this connects the columns of your DB mentioned in FROM array to the elements in a row of your list as mentioned in TO array
ListView yourlistview = (ListView) view.findViewById(R.id.yourlistview);//this is the listview element in your screen layout
yourlistview.setAdapter(adapter); // setting the adapter to the listview
Hope this helps

Related

Migrate from android paging library 2 to paging 3

I am building chat app where i am using Room,ViewModel,PagedListAdapter and it's works perfectly but now i want to upgrade my app to Paging Library 3 which caused real pain. I tried to follow official guide of Android but still not able to migrate from lib 2 to version 3 of paging and most of the tutorial are in kotlin when i am using Java in my project.
I start from changing PagedListAdapter to PagingDataAdapter which cause error at main activity
Chat_ViewModel viewModel = new ViewModelProvider(this).get(Chat_ViewModel.class);
viewModel.chatList.observe(getViewLifecycleOwner(), new Observer<PagedList<ChatEntity_TableColums>>() {
#Override
public void onChanged(PagedList<ChatEntity_TableColums> chatEntity_tableColums) {
Log.d(TAG, "onChanged: Chat Entity = " + chatEntity_tableColums.size());
adapter.submitList(chatEntity_tableColums); // cannot resolve Submitlist
}
});
Then i also tried to upgrade Viewmodel by changing public final LiveData<PagedList<ChatEntity_TableColums>> chatList; to LiveData<PagingData<ChatEntity_TableColums>> chatList; then it cause error in it's constructor,where i cannot find replacement.
public class Chat_ViewModel extends ViewModel {
private static final String TAG = "Chat View Model";
public final LiveData<PagedList<ChatEntity_TableColums>> chatList;
public Chat_ViewModel() {
chatList = new LivePagedListBuilder<>(
ChatRoomDatabase.getInstance(MyApplication.getmContext(),1).chatDAO().getPaginationChat(String.valueOf(Session.getOtherUserID())),20).build();
}
}
This is a query from where i am retrieving the data. I am using default DataSource.Factory to get data from Room
#Query("SELECT * FROM Chat WHERE RECEIVER_USER_ID = :UserID ORDER BY ID DESC") DataSource.Factory<Integer, ChatEntity_TableColums> getPaginationChat(String UserID);
Please guide me bit to update my project into paging library 3 with Java

ListView onClick to get Firebase data

I managed to get data from the Firebase Database and show it in an alphabetical order in my ListView.
Now I want to show the value from my database, if I click on an item in the ListView. As an example in my database it says "BB" as a name and the value is "Bye, bye".
So after an onClick event in the ListView a Toast message should show the value. How can I do this?
HereĀ“s my database:
To show the value after you click on an item:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final String selectedFromList = (String) list.getItemAtPosition(position);
ref.orderByChild(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String retrievedValue=dataSnapshot.child(selectedFromList).getValue().toString();
Toast.makeText(activity_name.this, "Value: "+retrievedValue, Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Assuming you have a listview with the following:
Afk
MFG
After clicking on an item, get the item at that postion and use it in a query orderByChild and retrieve it's value.
The sample code 'Peter Haddad' provided in his answer basically works fine... IF you design your database in a better way I did back then.
If you use his code, you get the value of the database entry (so the text on the right side in the console database, but I wanted to get the left one.
I recommend using a structure like in the Firebase Docs about Structuring.
It could look something like this:
Here are two posts about searching and querying those kind of databases:
How to do a simple search in string in Firebase database?
Query based on multiple where clauses in Firebase
If you anyways want to do it in the way I tried, it`s possible:
In the sample code from 'Peter Haddad' simply replace dataSnapshot.child(selectedFromList).getValue().toString() with dataSnapshot.child(selectedFromList).getKey().toString().
The key represents the text on the left side of the console database structure.

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.

how to retrieve info from datastore using google app engine and display it in a list view on an android app using java?

I am trying to make an android app that retrieves info from google app engine datastore and display it as a listview in the android app..can anyone help me out with some code or explain what exactly needs to be done for this purpose? i have already made modifications on the server side to store data on the datastore..what i dont know is how to get that data onto the android app..i am using eclipse indigo and language is java
EDIT : I am putting my code that i am using to retrieve a set of strings from datastore and put it in a list view...the code is gonna look all haywire but i request you to bear with me and explain how exactly to write it..presently the application is force-closing whenever i get to the page where this list of retrieved strings is supposed to be displayed...
public class Display extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] title;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaylayout);
MyRequestFactory factory = (MyRequestFactory)Util.getRequestFactory(Display.this,MyRequestFactory.class);
FebfourthRequest febfourthRequest = factory.febfourthRequest();
final List<TrialDBProxy> list= new ArrayList<TrialDBProxy>();
febfourthRequest.queryTrialDBs().fire(new Receiver<List<TrialDBProxy>>()
{
#Override
public void onSuccess(List<TrialDBProxy> arg0) {
// TODO Auto-generated method stub
list.addAll(arg0);
}
});
for(int i=0;i<list.size();i++)
{
title[i] = list.get(i).getMessage();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++)
{
rd = new RowData(i,title[i]);
data.add(rd);
}
int[] to = new int[] { R.id.text1, R.id.text2 };
#SuppressWarnings("deprecation")
Cursor mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
ListAdapter adapter = new SimpleCursorAdapter(this,R.layout.displaylayout,mCursor,title,to);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
private class RowData
{
protected int mId;
protected String mTitle;
RowData(int id,String title)
{
mId=id;
mTitle = title;
}
#Override
public String toString()
{
return mId+" "+mTitle;
}
} '
NOTE : TrialDB is the file that contains all my fields that i want to store on the datastore.
displaylayout is the xml file where i have created a listview.
i am guessing the main part where i have to put code for displaying stuff is in the onCreate() method.
PLEASE HELP !
This is already a very good starting point for learning both Google App Engine and Android Development.
I may write the steps to follow:
Write a Google App Engine application which reads data from datastore and gives as JSON. You can use GAE web framework, or maybe Django. After doing that, you will have a url which gives you your data in your browser.
Write a hello world application for Android. This step gives you an opportunity to understand and setup Android development environment.
Write an Android app which uses a listview with static data.
Extend your Android app with calling a single simple url from web, then print it on your screen.
Extend your application via calling your Google App Engine application url inside your app. Now you have your datastore data in your app.
Populate your listview with your data.

Inserting EditText & Spinner data to SQLite?

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.

Categories