Filling a listview from an online database

how to show data from sqlite database in listview in android
android listview from database example
how to retrieve data from database in listview in android
how to retrieve data from sqlite database in android and display in custom listview
custom listview using sqlite database in android
simple cursor adapter listview android
saving data with sqlite and adding it to a listview
how to display data in listview in android studio

Im new to programming and i have been trying to make this work for quite sometime but i havent been able to solve it, so, i want to transfer data(For now just names) from my online database to a listview and display it. I have already checked my php file and it works fine(It gives back the names i want), also the code seems to works fine until i reach the Baseadapter part.

Activity VerPostsUsuario

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.github.snowdream.android.widget.SmartImageView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONArray; 
import org.json.JSONException;   
import java.util.ArrayList;  
import cz.msebera.android.httpclient.Header;

public class VerPostsUsuario extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ver_posts_usuario);
    listView=(ListView)findViewById(R.id.listView);
    descargarImagen();


}

private ListView listView;

ArrayList nombreAnimal = new ArrayList();

private void descargarImagen(){
    nombreAnimal.clear();

    final ProgressDialog progressDialog = new ProgressDialog(VerPostsUsuario.this);
    progressDialog.setMessage("Cargando Datos");
    progressDialog.show();

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("mydomain+php", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            if(statusCode==200){
                progressDialog.dismiss();
                try {
                    JSONArray jsonArray = new JSONArray(new String(responseBody));
                    for (int i=0; 1<jsonArray.length();i++){
                        nombreAnimal.add(jsonArray.getJSONObject(i).getString("nombreAnimal"));

                    }
                    listView.setAdapter(new ImagenAdapter(getApplicationContext()));

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });

}

private class ImagenAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater layoutInflater;
    TextView tvnombreAnimal;


    public ImagenAdapter(Context applicationContext) {
        this.ctx=applicationContext;
        layoutInflater=(LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {

        ViewGroup viewGroup =(ViewGroup)layoutInflater.inflate(R.layout.activity_main_items, null);
       tvnombreAnimal = (TextView) viewGroup.findViewById(R.id.tvnombreAnimal1);

        tvnombreAnimal.setText(nombreAnimal.get(i).toString());







        return viewGroup;
    }

Activity VerPostsUsuario XML (ListView)

<ListView
        android:id="@+id/listView"
        android:layout_width="368dp"
        android:layout_height="492dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:background="#11000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Activity_main_items XML

<TextView
        android:id="@+id/tvnombreAnimal1"
        android:layout_width="177dp"
        android:layout_height="39dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="148dp"
        android:layout_marginStart="148dp"
        android:layout_marginTop="8dp"
        android:textColor="#000"
        android:textSize="24dp"

         />

Originally the tutorial also showed how to display images (Thats why there is an import "SmartImageView" and "Rect") so i deleted this part and tried to only do it with a text. Maybe i messed up somewhere but i cant find where, so if you could help me out in this one i would be very grateful.

Edit:

So i want to say thanks to all of the people who tried to help me out, it seems the Array had a few problems as did the Baseadapter. I will list them below for anyone who has a similar problem.

-Array:

Had a "1" instead of an "i" and had to replace

I was trying to get a field from the db called "nombreAnimal" when in reality in my php file i had assigned "nombreAnimal" to "Nombre" (nombreAnimal.add(jsonArray.getJSONObject(i).getString("Nombre"));)

I also found out that the best way to check if your Array has the Values you want(Or at least something) is to Check the Logcat of Android

-BaseAdapter:

I forgot to get the Size from my Array in the getCount (Array.size;)

I forgot in the getItem i needed to return the "position", "i" in my case, from my array "nombreAnimal" (Array.get(i);)

I forgot in the getItemdId to return "i" (i;)

I think there is something wrong with the array and how you handle the server response. This is how I made it work.

Seems like you are trying to get the value "nombreAnimal" instead of "Nombre". Try this:

try {
     JSONArray jsonArray = new JSONArray(new String(responseBody));
     for (int i = 0; i < jsonArray.length(); i++) {
          nombreAnimal.add(jsonArray.getJSONObject(i).getString("Nombre"));
     }
     listView.setAdapter(new ImagenAdapter(getApplicationContext()));
} catch (JSONException e) {
     e.printStackTrace();
}

Example of list working

I hope it helps you!

Populate Records in ListView - Android database SQLite , Populate Records in ListView - Android database SQLite (p4). For this This facilities is supported by SQLite library available in Android OS. Right click the  Find Free Database now. Visit & Look for More Results!

I am assuming that everything is correct except the implementation of the Adapter.

You are not overriding those methods properly, i let you the code to fix it.

Code in ImagenAdapter :

//You need  to return the size of the array, if you always are returning 0 the adapter dont
        //print any because they "think" the array is empty.
        @Override
        public int getCount() {
            return nombreAnimal.size();
        }

        //This method helps you to return the Item at specific index
        @Override
        public Object getItem(int i) {
            return nombreAnimal.get(i);
        }

I hope it helps you.

Populating a ListView with a CursorAdapter, When we want the data for the list to be sourced directly from a SQLite database query, we can use a CursorAdapter. The CursorAdapter fits in between a Cursor (​  The ListView control is a great way to display file system information and data from an XML file or database. The ListView control is typically used to display a graphical icon that represents the item, as well as the item text.

Review your BaseAdapter as below; you can find more information here

@Override
public int getCount() {
    return nombreAnimal.size();
}

@Override
public Object getItem(int position) {
    return nombreAnimal.get(position);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // inflate the layout for each list row
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.activity_main_items, null);
    }

    TextView tvnombreAnimal = (TextView) 
        convertView.findViewById(R.id.tvnombreAnimal1);
    tvnombreAnimal.setText(nombreAnimal.get(i).toString());

    // returns the view for the current row
    return convertView;
}

How to populate a listview with data from an SQLite database in , How do I populate a listview with data from an SQLite database in Android Studio​? Can I use SQLite as network database to fetch data online like Mysql and  Now that we know the basics of adding a ListItem to a ListView control in VB.net, lets move on to filling a ListView with data from a DataSet. The basic steps in this procedure are: Clear old contents from ListView. Add Columns to ListView to support the Dataset. Fill ListView with ListItems containing the data.

try that code:

public class VerPostsUsuario extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ver_posts_usuario);
    listView=(ListView)findViewById(R.id.listView);
    descargarImagen();


}

private ListView listView;

ArrayList nombreAnimal = new ArrayList();

private void descargarImagen(){
    nombreAnimal.clear();

final ProgressDialog progressDialog = new ProgressDialog(VerPostsUsuario.this);
progressDialog.setMessage("Cargando Datos");
progressDialog.show();

AsyncHttpClient client = new AsyncHttpClient();
client.get("mydomain+php", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        if(statusCode==200){
            progressDialog.dismiss();
            try {
                JSONArray jsonArray = new JSONArray(new String(responseBody));
                for (int i=0; 1<jsonArray.length();i++){
                    nombreAnimal.add(jsonArray.getJSONObject(i).getString("nombreAnimal"));

                }
                listView.setAdapter(new ImagenAdapter(getApplicationContext(), nombreAnimal));

            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

    }
});

}

private class ImagenAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater layoutInflater;
    TextView tvnombreAnimal;
    ArrayList list;
public ImagenAdapter(Context applicationContext, ArrayList list) {
    this.ctx=applicationContext;
    this.list = list;
    layoutInflater=(LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int i) {
    return list.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View convertView, ViewGroup parent) {

    ViewGroup viewGroup =(ViewGroup)layoutInflater.inflate(R.layout.activity_main_items, null);
   tvnombreAnimal = (TextView) viewGroup.findViewById(R.id.tvnombreAnimal1);

    tvnombreAnimal.setText(list.get(i).toString());







    return viewGroup;
}

I just added extra arraylist in your inner class.

How to take data from an SQLite data based in Android and , Worried that someone is tracking you online? Get NordVPN. How do I populate ExpandableListView using sqlite database? 6,629 Views · What data types  Populating ListView from Database using C# and VB.Net Inside the Form Load event, the records from the database are fetched into a DataTable. Then a loop is executed over the DataTable rows and one by one Item is added to the ListView.

Saving data with SQLite and adding it to a ListView, CodingWithMitch 21,291 views · 8:35. Android: Populating a ListView from the SQLite Database Duration: 19:06 Posted: May 13, 2016 Filling a ListView Dynamically from Any Data Sources. When I was developing different front-end data entry modules for data entry operators, I found that it is very common in different modules to fill a listview according to given query strings and I was designing a listview for each module from scratch.

A simple way to populate an Android ListView with a SQLite , Here's an example of how to populate an Android ListView , where I get the data for the ListView from a database Cursor : DatabaseHelper. The following code assumes you are already using ADODB code, and have a connection to the database. First, you must add a ListView control to your project. The ListView control is found in Microsoft Windows Common Controls 6.0 (SPx) (where x = your VB service pack number). To add these controls, click Project/Components from the VB IDE.

Using an ArrayAdapter with ListView · codepath/android_guides , Populating Data into ListView. Once the adapter is attached, items will automatically be populated into the ListView based on the contents of the  Im new to programming and i have been trying to make this work for quite sometime but i havent been able to solve it, so, i want to transfer data(For now just names) from my online database to a li

Comments
  • Please note that there is a small error in for (int i=0; 1<jsonArray.length();i++){, should be i<jsonArray.length(). Hope that helps!
  • Thanks you, i didnt notice, it doesnt work but its a step into the right direction into solving this
  • Yes! Now in the logs the values appear but it shows this error. Value [{"Nombre":"Carlos"},{"Nombre":"Juan"}] of type org.json.JSONArray cannot be converted to JSONObject. Idk what the "result" field would be in my case
  • Looking at other of your comments, I notice that you are trying to get the value "nombreAnimal", and I think you should put "Nombre". I will update my answer above so you can see how the code should be.
  • Thanks Man!!! It finally worked, you were right it was the field i put in the php file not from my database(The tutorial explained that in that field i should put the name of my db field). So thats why it didnt work! you helped me out a lot dude im very Thankful!
  • It still doesnt seem to work, do you think that with this the base adapter part should work correctly ?
  • Could ContraintLayout on the activity main items have something to do with it? In the tutorial a LinearLayout was used
  • You have to add this in the ImagenAdapter for sure. But maybe you have something else wrong in your code or xml layouts.
  • Ok, I will check my code again for errors and i will try to find out if the array even has something on it. Thank you for your help
  • This doesnt seem to work either, idk if the array might be the problem, how could i put the names into a normal textview to check if the data is there ?
  • can you print this line to be sure getting json data jsonArray.getJSONObject(i).getString("nombreAnimal") @ArchersTH177
  • Sorry for the ignorance but by that you mean displaying it on a textview or something where you can see the data?
  • Yes just print it in the debug console, use Log.v or System.out
  • So i used a string to store that line, then used log with tag:"TAG" and id:"id"+(The string i created) Then i started the debugger and searched for tag and it says this twice ViewPostImeInputStage ACTION_DOWN
  • Tried but nothing happened, there seem to be no errores on the code but for whatever reason it doesnt work. Do you know how to put the Array nombreAnimal data into a normal textview to check if there is actually any data on it ?