Display data from mysql into ListView in Android - java

I am currently fetching data from mysql database and displaying successfully in the TextView like this:
private void showJSON(String response){
String child_name="";
//String address="";
//String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
child_name = collegeData.getString(config.KEY_NAME);
//address = collegeData.getString(config.KEY_ADDRESS);
//vc = collegeData.getString(config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Children Name:\t" + child_name);
now, rather into the TextView, I want to display it in the ListView. So How to proceed in this way as i am new to android development.

In order to populate a ListView in Android you first need to create an Adapter object where you'll define the layout of each item and the behavior of the list.
Basically what you'll have to do is:
Create an ArrayList of the objects you want to display
Create an Adapter for your list view (passing the previously created list as parameter at creation)
Set the adapter to your ListView object.
You may follow this guide for the complete details: http://www.vogella.com/tutorials/AndroidListView/article.html

Related

How to add jsonObject to an existing JSON file in the "raw" folder Android Studio? (Java)

Im trying to add jsonObject to an existing JSON file in "raw" folder.
Every time the button pressed it should add to the JSON file two new variables from the plainText input. I cant figure out how to do that because I cant properly get the path of the "raw" folder.
the code that I wrote without the "adding to JSON" part
public void submit(View view) {
EditText editAmount;
EditText editReason;
Log.d("Smth", "Submit!");
editAmount = (EditText)findViewById(R.id.editAmount);
editReason = (EditText)findViewById(R.id.editReason);
String amount = editAmount.getText().toString();
String date = "18.02.2023";
String reason = editReason.getText().toString();
Log.d("Smth", amount);
Log.d("Smth", reason);
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("amount", amount);
jsonObject.put("reason", reason);
jsonObject.put("date", "18.02.2023");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
I have tried a lot of other solutions on StackOverFlow, but all of them give me errors.
I hope you will help me with this problem of editing JSON file) Thank you

can't retrieve the data from sqlite db

i have created a method to retrieve all favorites from database, but its not getting any data.
i have added a Log.e to check the count of data, and its come as below:
I/SQLiteAssetHelper: successfully opened database FoodDB.db
fav: []: : is count
so please advice me where is the mistake exactly, and how i could call the method from the activity to get all data.
getAllFavorites method
public List<Favorites> getAllFavorites (String foodId) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"FoodId", "Name", "Image", "Description", "Components",
"MenuId", "UserName"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor c = qb.query(db, sqlSelect, "FoodId=?", new String[]{foodId}, null, null, null);
final List<Favorites> result = new ArrayList<>();
if (c.moveToFirst()) {
do {
result.add(new Favorites(
c.getString(c.getColumnIndex("FoodId")),
c.getString(c.getColumnIndex("Name")),
c.getString(c.getColumnIndex("Image")),
c.getString(c.getColumnIndex("Description")),
c.getString(c.getColumnIndex("Components")),
c.getString(c.getColumnIndex("MenuId")),
c.getString(c.getColumnIndex("UserName"))
));
} while (c.moveToNext());
}
db.close();
return result;
}
activity_favorites.JAVA
public class FavoritesActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FavoritesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
recyclerView = findViewById(R.id.recycler_favorites);
recyclerView.setHasFixedSize(true);
LinearLayoutManager myLayoutManager = new LinearLayoutManager(this);
myLayoutManager.setReverseLayout(true);
myLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(myLayoutManager);
loadFavorites();
}
private void loadFavorites() {
adapter = new FavoritesAdapter(this, new Database(this).getAllFavorites("FoodId"));
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "check is it working?", Toast.LENGTH_SHORT).show();
Log.e("fav: "+new Database(this).getAllFavorites("FoodId"), ": is count");
}
}
Considering that the debugging confirms that you have data in the database and that you can access it and that it appears that you are following the correct steps for utilising a RecyclerView, then in all likelihood the issues are with the FavoritesAdapter.
As a quick way of showing this the following steps and code should show a list but using an ArrayAdapter along with a ListView and a stock layout.
Add a ListView to your layout.activity_favorites.xml, giving it an id of listview (make sure that it will be visible).
add 4 lines as class variables (i.e. after FavoritesAdapter) :-
ListView mListView;
List mFavoritesList;
ArrayAdapter mAdapter;
Database mDBHlpr;
add the following lines to set mListView according to the id of the listview added at 1 (after setContentView(R.layout.activity_favorites);) :-
mListView = this.findViewById(R.id.listview);
mDBHlpr = new Database(this);
mFavoritesList = mDBHlpr.getAllFavorites("doesn't matter as not used as yet");
mAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,mFavoritesList);
mListView.setAdapter(mAdapter);
Note this assumes that the getAllFavorites uses Cursor c = qb.query(db, sqlSelect, null, null, null, null, null);
4 Run the App and hopefully you'll get something along the lines of :-
Note mjt.usingrecyclerviews.Favorites is the package/class name. i.e. it's listing the rows BUT because the default of the ArrayAdapter is to use the toString method and none is defined in the Favorites class it uses the default. So package class and then the identifier for the respective object.
This screen print was after running the code/App twice each adding 3 rows to the Favoorites table, hence the 6 rows in the ListView.
Adding the following method to the Favorites class :-
public String toString() {
return "Id=" + String.valueOf(this.foodid) + " Name=" + this.name + " etc.....";
}
results in :-
So now, a 3rd run and there are 3 sets of the same 3 people (as expected)
What to do next.
As previously said the issue is very likely with your adapter. As such I'd suggest marking this as answered, (i.e. you can now retrieve data from the database or least least know that it's there) and then ask another question, this time providing code for the adapter.
download "sqlite expert personal" and copy your db file to "sqlite expert personal". You can view your table and values inside and also write down the same query that you are writing in your app and be sure if its working properly or not.

Intent values (json array) to Listview

Is it possible to put Intent values from one Activity to a ListView in another Activity?
Here are the values from Activity1 that I wanted to put to the ListView in Activity2:
try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");
fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);
if(json!=null)
{
Intent i = new
Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra(u.username(), u.getUsername());
i.putExtra("password",Password);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}
}catch(Exception e)
{
e.printStackTrace();
}
You can put intent values from one activity to a listview in another activity.
From another activity, you can use getIntent().getExtras().getString("key...");. But this can be only one line.
For sending array, you should see Sending arrays with Intent.putExtra.
For sending arraylist, Passing ArrayList through Intent.
I hope this may help you.
Yes, you can. I can see that you want to pass all the values of your user object to another activity using intent. You can pass the individual values like you are doing above OR You can pass the user object directly as -
i.putExtra("MyClass", u); //u is the user object here
You can get back your user object in the target activity as -
getIntent().getSerializableExtra("MyClass"); //Make sure that your user model class implements serializable
If it is a listview of users, you can add this user object to your array of users. This is the array that you must have set to your adapter in target activity. Now you can call -
adapter.notifyDataSetChanged();
This will make the new changes in your listview. Thanks.

How to get Data from a Firebase Database and populate them in a ListView

{
"chat_room" : {
"-Kp_ldAz7_g3W4riNkJY" : {
"message" : "Hello!",
"uname" : "Praveen"
}
}
}
this is my Firebase DB jSON file for a single chat message, i tried the following method i created called "appendChat()" to populate the database on a ListView.
but for some reason the ListView only shows the last message sent
private void appendChat(DataSnapshot dataSnapshot) {
final ArrayList<String> chatListArr = new ArrayList<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
chatListArr.add((String) ((DataSnapshot) i.next()).getValue());
chatListArr.add((String) ((DataSnapshot) i.next()).getValue());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_2,android.R.id.text1, chatListArr);
chatList.setAdapter(arrayAdapter);
}
My ListView has a String for the username and a sub string for the message, how do i change the code to retrieve database values and populate in a ListView as
username:
message
The problem is that you are creating a brand new ArrayAdapter each time a message is received. This effectively deletes all of the previous messages. I suggest that you create the ArrayAdapter once in onCreate(). Then you can just add data to the ArrayList and call notifyDataSetChanged() on the adapter.

How to make ListView to refresh after every 5 sec when data come from a server

I have ListView which have data . Data come from server and I want the ListView to update after every 5 sec. How to do this? I am new to android development. Please help me. Here is my code...
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String data = c.getString(TAG_DATA);
final String dataaaa = rcdata.getText().toString().trim();
HashMap<String, String> user_data = new HashMap<String, String>();
user_data.put(TAG_DATA, data);
personList.add(user_data);
}
ListAdapter adapter = new SimpleAdapter(
DataSendActivity.this, personList, R.layout.layout_chat,
new String[]{TAG_DATA},
new int[]{R.id.data}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
Use a Handler and its postDelayed method to invalidate the list's adapter as follows:
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 5000 );
}
}, 5000 );
You must only update UI in the main (UI) thread.
you can see this question and comment How to refresh/Update Serialize Java Object in sharedPreferences. the user want the same. however it is good to use loader with service for that kind of problem calling asyncTask within minute is not good. also theres is a sample project you can check this https://github.com/Michenux/YourAppIdea also available in playstore which check for data changes from server.

Categories

Resources