2

I am trying to fetch data from .sqlite and display it into the ListView !

For that implemented a GetterSetter class for getting and setting the data in the ArrayList by this method & i was successful in printing the values got from database to console :

public ArrayList<GS> getData() 
{
    try{
    Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
    gs = new ArrayList<GS>();
    while (c1.moveToNext())
    {
        GS q1 = new GS();

        q1.setId(c1.getString(0));
        q1.setA_id(c1.getString(1));
        q1.setA_name(c1.getString(2));
        q1.setAS_name(c1.getString(3));  //--I want this type of list to be in ListView--
        q1.setDesc_art(c1.getString(4));
        Log.v("id",q1.AS_name+"");
        gs.add(q1);
    }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return gs;
}

I call this method by :

ArrayList<GS> q = db.getData();

So what code should be implemented, to display it in ListView ?

*UPDATE * : activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >
</ListView>

</RelativeLayout>

customlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

DBAdapter.java

 public class DBAdapter extends SQLiteOpenHelper
 {
CustomAdapter adapter;
static String name = "law.sqlite";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;

@Override
public void onCreate(SQLiteDatabase db)
{
    // TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    // TODO Auto-generated method stub
} 

private DBAdapter(Context v) 
{
    super(v, name, null, 1);
    path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}

public boolean checkDatabase()
{
    SQLiteDatabase db = null;
    try 
    {
        db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) 
    {
        e.printStackTrace();
    }
    if (db == null) 
    {
        return false;
    } 
    else
    {
        db.close();
        return true;
    }
}

public static synchronized DBAdapter getDBAdapter(Context v)
{
    return (new DBAdapter(v));
}

public void createDatabase(Context v) 
{
    this.getReadableDatabase();
    try
    {
        InputStream myInput = v.getAssets().open(name);
        // Path to the just created empty db
    String outFileName = path +"/"+ name;
        // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) 
    {
        myOutput.write(buffer, 0, length);
    }
        // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

    /*  



        InputStream is = v.getAssets().open("quiz.sqlite");
        // System.out.println(is.available());
        System.out.println(new File(path + "/" + name).getAbsolutePath());
        FileOutputStream fos = new FileOutputStream(path + "/" + name);
        int num = 0;
        while ((num = is.read()) > 0) {
            fos.write((byte) num);
        }
        fos.close();
        is.close();*/
    } catch (IOException e) 
    {
        System.out.println(e);
    }
}

public void openDatabase() 
{
    try 
    {
        sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
                SQLiteDatabase.OPEN_READWRITE);
    } catch (Exception e) 
    {
        System.out.println(e);
    }
}

public ArrayList<GS> getData() 
{
    try{
    Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
    gs = new ArrayList<GS>();
    while (c1.moveToNext())
    {
        GS q1 = new GS();

        q1.setId(c1.getString(0));
        q1.setA_id(c1.getString(1));
        q1.setA_name(c1.getString(2));
        q1.setAS_name(c1.getString(3));
        q1.setDesc_art(c1.getString(4));
        Log.v("id",q1.AS_name+"");
        gs.add(q1);

    }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return gs;
}
}

MainActivity.java

public class MainActivity extends Activity {

ArrayList<GS> q = new ArrayList<GS>();
CustomAdapter adapter;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
       // Get ListView object from xml
     lv = (ListView) findViewById(R.id.listView1);

    DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
    if (!db.checkDatabase()) 
    {
        db.createDatabase(getApplicationContext());
    }
    db.openDatabase();

    q = db.getData();
    for(int i=0;i<q.size();i++)
    {
        Log.i("outside",""+q.get(i).getAS_name());
    }
    lv = (ListView) findViewById(R.id.listView1);
    lv.setAdapter(new CustomAdapter(MainActivity.this,q));
    lv.setAdapter(adapter);

}

class CustomAdapter extends ArrayAdapter<GS>
  {
       ArrayList<GS> list;
       LayoutInflater mInfalter;    
       public CustomAdapter(Context context, ArrayList<GS> list)
       {
          super(context,R.layout.customlayout,list);
          this.list= list;  
          mInfalter = LayoutInflater.from(context);
        for(int i=0;i<q.size();i++)
        {
            Log.i("................",""+list.get(i).getAS_name());
        }

       }
       @Override
        public View getView(int position, View convertView, ViewGroup parent) {
          ViewHolder holder;
          Log.i("..........","Hello in getView");
          if(convertView==null)
          {
               convertView = mInfalter.inflate(R.layout.customlayout,parent,false);
               holder = new ViewHolder();
               holder.tv1 = (TextView)convertView.findViewById(R.id.textView1); 
               convertView.setTag(holder); 
          }else{
                holder = (ViewHolder)convertView.getTag();
          } 

                holder.tv1.setText(list.get(position).getAS_name());
          return convertView;
    }

  }
 static class ViewHolder
    {
        TextView tv1;
    }  
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
Vivek Warde
  • 1,936
  • 8
  • 47
  • 77
  • 2
    Your question is all about how to setup a ListView? If so, here's the [Vogella tutorial](http://www.vogella.com/tutorials/AndroidListView/article.html) – gunar Jan 28 '14 at 17:03
  • 1
    You might want to look into implementing a CursorAdapter - or using a SimpleCursorAdapter instead. – Submersed Jan 28 '14 at 17:05
  • I have updated my Question & basically i cannot predict my mistake in setting up the listView ? – Vivek Warde Jan 28 '14 at 17:16

1 Answers1

1

You have

String[] values = new String[q.size()]; 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_list_item_1, android.R.id.text1, values);

But where do you populate items to values array. I don't see that in your code.

You can use Custom ListView with a Custom Adapter

 ArrayList<GS> q = db.getData();
 ListView lv = (ListView) findViewById(R.id.listView);
 lv.setAdapter(new CustomAdapter(MainActivity.this,q));

CustomAdapter

class CustomAdapter extends ArrayAdapter<GS>
  {
       ArrayList<GS> list;
       LayoutInfalter mInfalter;    
       public CustomAdapter(Context context, ArrayList<GS> list)
       {
          super(context,R.layout.customlayout,list);
          this.list= list  
          mInfalter = LayoutInfalter.from(context);
       }   
        public View getView(int position, View convertView, ViewGroup parent) {
          ViewHolder holder;
          if(convertView==null)
          {
               convertView = mInflater.inflate(R.layout.customlayout,parent,false);
               holder = new ViewHolder();
               holder.tv1 = (TextView)convertView.findViewById(R.id.textView1); 
               convertView.setTag(holder); 
          }else{
                holder = (ViewHolder)convertVire.getTag();
          } 

                holder.tv1.setText(list.get(postion).getAS_name());
          return convertVIew;
    }
    static class ViewHolder
    {
        TextView tv1;
    }    
  }

Have a TextView with id textview1 in customlayout.xml.

Or

Using SimpleCursorAdapter would be appropriate in this case.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • using your code line `lv.setAdapter(MainActivity.this,q);` gives me a error "The method setAdapter(ListAdapter) in the type ListView is not applicable for the arguments (MainActivity, ArrayList)" – Vivek Warde Jan 28 '14 at 17:46
  • instead i tried to use `lv.setAdapter(adapter);` but using this line Coustom adapter is not called ...:( – Vivek Warde Jan 28 '14 at 17:48
  • @VivekWarde sorry it shoudl be `lv.setAdapter(CustomAdapter(MainActivity.this,q));` – Raghunandan Jan 28 '14 at 17:48
  • error :The method CustomAdapter(MainActivity, ArrayList) is undefined for the type MainActivity – Vivek Warde Jan 28 '14 at 17:50
  • @VivekWarde another mistake missed the `new` keyword. this should be obvious. `lv.setAdapter(new CustomAdapter(MainActivity.this,q))`. – Raghunandan Jan 28 '14 at 17:51
  • OK thanks but this is only executing the constructor of CustomAdapter, not the getView() function , i tried this debugging – Vivek Warde Jan 28 '14 at 18:03
  • @VivekWarde it will AFAIK. i am sure about it. I guess you are not doing it right – Raghunandan Jan 28 '14 at 18:06
  • @VivekWarde post yout updated code along with customlayout.xml – Raghunandan Jan 28 '14 at 18:15
  • @VivekWarde see this `ArrayAdapter` should be ArrayAdapter. missing @Override annotation for `getView`. rest all is fine – Raghunandan Jan 29 '14 at 15:36
  • Ok, but after this the same problem perists that it is not executing the getView() function :( – Vivek Warde Jan 29 '14 at 15:55
  • can we use `lv.setAdapter(adapter);` in the code (perhaps in getData() method) – Vivek Warde Jan 29 '14 at 15:56
  • @VivekWarde how do you know it is not getting executed. log something like `Log.i("..........","Hello in getView");` and what you say just makes no sense at all. :(. I am saying it should work coz i have done this many times. If there is no log then there is no data in list – Raghunandan Jan 29 '14 at 15:56
  • @VivekWarde log something in getView and tell me if you see anything in logcat. if you see nothing there is no data in list – Raghunandan Jan 29 '14 at 16:01
  • Log in getData() method displays the value in logcat ! the control is never passed to getView() i also tried by debugging breakpoints – Vivek Warde Jan 29 '14 at 16:26
  • did you try loggin in `getView`?. If the control goes to adapter it will goto getView – Raghunandan Jan 29 '14 at 16:27
  • no `lv.setAdapter(new CustomAdapter(MainActivity.this,q));` invoke only the constructor, the control never goes into getView – Vivek Warde Jan 29 '14 at 16:29
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46355/discussion-between-raghunandan-and-vivekwarde) – Raghunandan Jan 29 '14 at 16:31
  • sir can u pls answer this question http://stackoverflow.com/questions/22451081/how-to-track-the-original-position-of-item-while-scrolling-in-a-long-custom-list – Vivek Warde Mar 19 '14 at 14:04