Results 1 to 8 of 8
  1. #1
    boyfunky is offline Member
    Join Date
    Jun 2014
    Posts
    5
    Rep Power
    0

    Default Using ListView to Retrieve Data from Database

    am a newbie to Java programming and I am trying to use a ListView to access a database and retrieve its data.

    I have written the following code. What is wrong with my code?


    package com.example.firstapp;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;

    import android.support.v7.app.ActionBarActivity;
    import android.support.v7.app.ActionBar;
    import android.support.v4.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.GridView;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.os.Build;

    public class MainActivity extends ActionBarActivity {


    public static ArrayList<String> ArrayofName = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ListView listview = (ListView) findViewById(R.id.listview);

    String connString = "jdbc:jtds:sqlserver://DRLOVE/EDMS;instance=MSSQLSERVER;";
    String query = "select * from Employee";
    String driver = "net.sourceforge.jtds.jdbc.Driver";
    Connection conn = null;
    ResultSet reset = null;
    try{
    Class.forName(driver).newInstance();
    conn = DriverManager.getConnection(connString);
    if(!conn.isClosed()){
    //add appropriate logging here to track progress
    Statement stmt = conn.createStatement();
    reset = stmt.executeQuery(query);
    final ArrayList<String> list = new ArrayList<String>();
    while(reset.next()){

    ((Menu) listview).add(reset.getString(2));
    }
    reset.close();
    stmt.close();
    }
    }
    catch (SQLException e) {
    e.printStackTrace();
    } catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
    return true;
    }
    return super.onOptionsItemSelected(item);
    }

    /**
    * A placeholder fragment containing a simple view.
    */
    public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container,
    false);
    return rootView;
    }
    }


    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default Re: Using ListView to Retrieve Data from Database

    Quote Originally Posted by boyfunky View Post
    am a newbie to Java programming and I am trying to use a ListView to access a database and retrieve its data.

    I have written the following code. What is wrong with my code?
    You tell us.
    What is not working about the code you have supplied?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,585
    Rep Power
    25

    Default Re: Using ListView to Retrieve Data from Database

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE GOES HERE
    [/code]
    to get highlighting and preserve formatting.

    Are there error messages in the Logcat?
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    boyfunky is offline Member
    Join Date
    Jun 2014
    Posts
    5
    Rep Power
    0

    Default Re: Using ListView to Retrieve Data from Database

    Java Code:
    public class Dbconnect extends ListActivity {
    	
    	 static String names [] ;
    
    	 public static void main (String [] args)throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    			String connString = "jdbc:jtds:sqlserver://DRLOVE/EDMS;instance=MSSQLSERVER;";
    			String query = "select * from Employee";
    			String driver = "net.sourceforge.jtds.jdbc.Driver";
    			Connection conn = null;
    			ResultSet reset = null;
    			try{
    			Class.forName(driver).newInstance();
    			conn = DriverManager.getConnection(connString);
    			if(!conn.isClosed()){
    			//add appropriate logging here to track progress
    			Statement stmt = conn.createStatement();
    			reset = stmt.executeQuery(query);
    			
    			//names = reset.getArray(2);
    			//names = reset.toString()
    			int i = 0;
    			names = new String[reset.getMetaData().getColumnCount()];
    			while(reset.next()){
    			//System.out.println(reset.getString(2));
    				names[i] = reset.getString(2);
    				i++;
    			} 
    			reset.close();
    		    stmt.close();            
    		}
    			}
    		catch (SQLException e) {
    		    e.printStackTrace();
    		} catch (InstantiationException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}	
    		}
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    		setListAdapter(new ArrayAdapter<String>(Dbconnect.this, android.R.layout.simple_list_item_1, names));
    	}
    	}
    2nd Java Activity page
    Java Code:
    public class MainActivity extends ActionBarActivity {
    
    	@Override
    	protected void onCreate(Bundle RunBackground) {
    		// TODO Auto-generated method stub
    				super.onCreate(RunBackground);
    				setContentView(R.layout.background);
    				Thread timer = new Thread(){
    					public void run(){
    						try {
    							sleep(5000);
    						} catch (InterruptedException e){
    							e.printStackTrace();
    						}finally {
    							/* opens new activity and starts activity*/
    							Intent openStartingPoint = new Intent("com.example.graphmobile.DBCONNECT");
    							startActivity(openStartingPoint);
    							
    						}
    					}
    				};
    				timer.start();
    			}
    
    			@Override
    			protected void onPause() {
    				// TODO Auto-generated method stub
    						super.onPause();
    						finish();
    			}
    		}
    This program should load the MainActivity class, load d background then start d DbConnect activity. but I get an error when it switched to d DbConnect. This is the wrror i am getting

    07-04 05:29:40.856: E/AndroidRuntime(2034): FATAL EXCEPTION: main
    07-04 05:29:40.856: E/AndroidRuntime(2034): Process: com.example.graphmobile, PID: 2034
    07-04 05:29:40.856: E/AndroidRuntime(2034): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.graphmobile/com.example.graphmobile.Dbconnect}: java.lang.NullPointerException: storage == null
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:2195)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.ActivityThread.handleLaunchActivity(Ac tivityThread.java:2245)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.ActivityThread.access$800(ActivityThre ad.java:135)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.ActivityThread$H.handleMessage(Activit yThread.java:1196)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.os.Handler.dispatchMessage(Handler.java:10 2)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.os.Looper.loop(Looper.java:136)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.ActivityThread.main(ActivityThread.jav a:5017)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at java.lang.reflect.Method.invokeNative(Native Method)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at java.lang.reflect.Method.invoke(Method.java:515)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:779)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:595)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at dalvik.system.NativeStart.main(Native Method)
    07-04 05:29:40.856: E/AndroidRuntime(2034): Caused by: java.lang.NullPointerException: storage == null
    07-04 05:29:40.856: E/AndroidRuntime(2034): at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at java.util.Arrays.asList(Arrays.java:155)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.widget.ArrayAdapter.<init>(ArrayAdapter.ja va:128)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at com.example.graphmobile.Dbconnect.onCreate(Dbconne ct.java:62)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.Activity.performCreate(Activity.java:5 231)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.Instrumentation.callActivityOnCreate(I nstrumentation.java:1087)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:2159)
    07-04 05:29:40.856: E/AndroidRuntime(2034): ... 11 more

    What am I doing wrong? I want to read data from a database and put it as a ListView or ListItem.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,585
    Rep Power
    25

    Default Re: Using ListView to Retrieve Data from Database

    java.lang.NullPointerException: storage == null
    07-04 05:29:40.856: E/AndroidRuntime(2034): at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at java.util.Arrays.asList(Arrays.java:155)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at android.widget.ArrayAdapter.<init>(ArrayAdapter.ja va:128)
    07-04 05:29:40.856: E/AndroidRuntime(2034): at com.example.graphmobile.Dbconnect.onCreate(Dbconne ct.java:62)
    The red line is where the NPE happened in your code where it was creatting an ArrayAdapter.
    Look at line 62 and find what is null.

    BTW Android doesn't use a main() method.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    boyfunky is offline Member
    Join Date
    Jun 2014
    Posts
    5
    Rep Power
    0

    Default Re: Using ListView to Retrieve Data from Database

    Hi Norm,

    I re-wrote the entire code again. It runs without any errors bt doesnt display the ListView.
    Dbconnect.Java

    Java Code:
    package com.example.graphmobile;
    
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    
    
    public class Dbconnect extends ListActivity {
    	
    	//String[] names1;
    	private static int columnCount;
    	private static String [] names;
    	
    	public static int onConnect () throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    		//String[] names = new String[]; 
    		
    		String connString = "jdbc:jtds:sqlserver://DRLOVE/EDMS;instance=MSSQLSERVER;";
    			String query = "select * from Employee";
    			String driver = "net.sourceforge.jtds.jdbc.Driver";
    			Connection conn = null;
    			ResultSet reset = null;
    			Statement stmt = null;
    			try{
    			Class.forName(driver).newInstance();
    			conn = DriverManager.getConnection(connString);
    			if(!conn.isClosed()){
    			//add appropriate logging here to track progress
    			stmt = conn.createStatement();
    			reset = stmt.executeQuery(query);
    			
    			//names = reset.getArray(2);
    			//names = reset.toString()
    			//int i = 0;
    			 columnCount  = reset.getMetaData().getColumnCount();
    			} 
    			reset.close();
    		    stmt.close();            
    		}
    			
    		catch (SQLException e) {
    		    e.printStackTrace();
    		} catch (InstantiationException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}	
    			
    			
    			return columnCount;
    		}
    	
    	
    	public static String [] onConnectData () throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    		 names = new String[onConnect()]; 	
    		String connString = "jdbc:jtds:sqlserver://DRLOVE/EDMS;instance=MSSQLSERVER;";
    			String query = "select * from Employee";
    			String driver = "net.sourceforge.jtds.jdbc.Driver";
    			Connection conn = null;
    			ResultSet reset = null;
    			try{
    			Class.forName(driver).newInstance();
    			conn = DriverManager.getConnection(connString);
    			if(!conn.isClosed()){
    			//add appropriate logging here to track progress
    			Statement stmt = conn.createStatement();
    			reset = stmt.executeQuery(query);
    			
    			//names = reset.getArray(2);
    			//names = reset.toString()
    			int i = 0;
    			// names  = new String[reset.getMetaData().getColumnCount()];
    			while(reset.next()){
    			//System.out.println(reset.getString(2));
    				names[i] = reset.getString(2);
    				i++;
    			} 
    			reset.close();
    		    stmt.close();            
    		}
    			}
    		catch (SQLException e) {
    		    e.printStackTrace();
    		} catch (InstantiationException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}	
    			
    			return names;
    		}
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		
    		super.onCreate(savedInstanceState);
    			
    		try {
    			setListAdapter(new ArrayAdapter<String>(Dbconnect.this, android.R.layout.simple_list_item_1, onConnectData()));
    		} catch (InstantiationException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    	
    }
    The MainActivity.Java class remains the same. I do not now why it doesnt load any data into the listadapter.

    Any help is appreciated.
    Also, how can I debug or perform a step by step check?

    Thanks

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default Re: Using ListView to Retrieve Data from Database

    To debug it stick some logging in there and then look at Logcat.

    Did you check Logcat for errors?
    If your code threw an exception you'd only know about it via the logs.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    Join Date
    Jul 2014
    Posts
    2
    Rep Power
    0

    Default Re: Using ListView to Retrieve Data from Database

    Hope this code helps you.
    public class CheckData extends ListActivity {
    TextView selection;
    public int idToModify;
    DataManipulator dm;

    List<String[]> list = new ArrayList<String[]>();
    List<String[]> names2 =null ;
    String[] stg1;
    protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.check);
    dm = new DataManipulator(this);
    names2 = dm.selectAll();

    stg1=new String[names2.size()];

    int x=0;
    String stg;

    for (String[] name : names2) {
    stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];

    stg1[x]=stg;
    x++;
    }


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this,android.R.layout.simple_list_item_1,
    stg1);
    this.setListAdapter(adapter);
    selection=(TextView)findViewById(R.id.selection);

    }

    public void onListItemClick(ListView parent, View v, int position, long id) {
    selection.setText(stg1[position]);
    }


    }

    Please visit <url removed> For more Web Apps.
    Last edited by Tolls; 07-10-2014 at 09:06 AM. Reason: Remove url

Similar Threads

  1. Replies: 5
    Last Post: 05-23-2014, 10:07 AM
  2. how to retrieve data using <select> tag from database
    By shyamgsk in forum Java Servlet
    Replies: 6
    Last Post: 09-20-2013, 04:10 PM
  3. Replies: 0
    Last Post: 01-20-2012, 06:44 AM
  4. JSP code to connect, store and retrieve from database
    By HarryJade in forum New To Java
    Replies: 1
    Last Post: 12-26-2009, 03:45 AM
  5. retrieve file containg image from database
    By rajeshwari_ib in forum Advanced Java
    Replies: 5
    Last Post: 12-15-2009, 09:10 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •