Lalit
Lalit

Reputation: 1703

Get Data from SQL Database and set it to ListView in Android

I want to get data from SQL Server and set it to list.

1. I already have data in my current Activity. _I printed it on Logcat_ .

2. Now I want to set that data to my list.

Basically I have taken a static list of data for the basic view, that I mention there

How to set that data to list ?

Here is my Code that will show content how i did code :

public class menus extends Activity {

ListView list;
ArrayAdapter<String> adapter = null;
Editor edit1;
SharedPreferences pref;
SharedPreferences.Editor editor;

int i = 0,count = 0;
String[] listOfMenus;
String listdetails;
Connection xyz;
Statement st;
ResultSet rs;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.select_item);

    list=(ListView)findViewById(R.id.menulistblank);

    editor = getPreferences(MODE_PRIVATE).edit();

     /////// This is my Static data that I stored in list.

    String[] values = new String[]{"Adroid Developer",".Net Developer","Java Developer","BA"};

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

         list.setAdapter(adapter); 

                // Object of connection for getting content.
         xyz = MainActivity.conn;

         MyNetworkTask myWebFetch = new MyNetworkTask();
         myWebFetch.execute();

         list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(getBaseContext(), "You click "+arg2, Toast.LENGTH_SHORT).show();
            }
        });
}

   //////// ASYNC TASK ////////

private class MyNetworkTask extends AsyncTask<Void, Void, Void> {

     protected void onProgressUpdate(Integer... progress) {
         Log.w("Process completed", "In XXXXXXXX");
     }

     protected void onPostExecute(Long result) {
          Log.w("Process completed", "aaaaaaaaaa");
     }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        Log.w("Process completed", "In doInBackground..");
        try {
            st = MainActivity.conn.createStatement();
            rs = st.executeQuery("SELECT * FROM lalit_db;");
            while(rs.next()){

                  // ***** It prints my required data  in Logcat
                Log.w(rs.getString(2), rs.getString(3));
                }

            Thread.sleep(5000);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
 }
}// Main Program Ends..

Please tell me what should i do to

set this data of logcat Log.w(rs.getString(2), rs.getString(3)); in List.

Upvotes: 0

Views: 7213

Answers (2)

Ycos3D
Ycos3D

Reputation: 1

if you want multicolumn ListView , try this :

public void fillList(ResultSet rs,ListView list_head,ListView list,int layout,int to[],String columns[],String titles[]) 
{       
    ArrayList<HashMap<String, String>> mylist, mylist_title;
    ListAdapter adapter_title, adapter;
    HashMap<String, String> map1, map2;

    mylist = new ArrayList<HashMap<String, String>>();
    mylist_title = new ArrayList<HashMap<String, String>>();

    /**********Display the headings************/
    map1 = new HashMap<String, String>();
    for (int i = 0; i < columns.length; i++)  
        map1.put(columns[i], titles[i]);
    mylist_title.add(map1);

    try 
    {
        adapter_title = new SimpleAdapter(context, mylist_title,layout,columns, to);
        list_head.setAdapter(adapter_title);
    } catch (Exception e) {
        Log.w("Error1","" + e.getMessage()); 
        e.printStackTrace();
    }

    /**********Display the contents************/





    try 
    {
    while(rs.next())
    {           
        map2 = new HashMap<String, String>();
        for (int i = 0; i < columns.length; i++)  
            map2.put(columns[i], rs.getObject(columns[i]).toString());
        mylist.add(map2);
    }
} catch (SQLException e1) 
{
    // TODO Auto-generated catch block
    Log.w("Error2","" + e1.getMessage()); 
    e1.printStackTrace();
}



    try 
    {
        adapter = new SimpleAdapter(context, mylist, layout,columns, to);
        list.setAdapter(adapter);
    } 
    catch (Exception e) 
    {
        Log.w("Error3","" + e.getMessage()); 
        e.printStackTrace();

    }

}

Upvotes: 0

Ketan Ahir
Ketan Ahir

Reputation: 6728

  1. add strings in values while fetching data

    st = MainActivity.conn.createStatement();
    rs = st.executeQuery("SELECT * FROM lalit_db;");
    values=new String[st.getFetchSize()]; //total number of rows
    int index=0;
    while(rs.next()){
      values[index]=rs.getString(2);
      index++;
     // ***** It prints my required data  in Logcat
     Log.w(rs.getString(2), rs.getString(3));
    }
    
  2. Display in onPostExecute()

    protected void onPostExecute(Void result) {
      Log.w("Process completed", "aaaaaaaaaa");
      adapter = new ArrayAdapter<String>(menus.this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
    
       list.setAdapter(adapter); 
    }
    

Edit

add @Override annotation to onPostExecute() method

@Override
protected void onPostExecute(Void result) {
      Log.w("Process completed", "aaaaaaaaaa");
 }

Upvotes: 1

Related Questions