我们可以在android中的多个活动中访问连接对象吗?

时间:2014-01-02 12:51:43

标签: java android sql-server-2005

我创建了一个程序,其中创建了与SQL Server的连接。现在我想在下一个查询的另一个活动中访问该对象我可以这样做吗。

如果是,那么请告诉我如何?

这是我的MainActivity:

  void connectionToSql()
  {
    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
        url ="jdbc:jtds:sqlserver://192.168.1.15;instanceName=MSSQLSERVER;DatabaseName="+DBName+";integratedSecurity=true;user="+UserName+";password="+Password;

        Timer myTimer = new Timer();
        myTimer.schedule(new TimerTask() {          
            @Override
            public void run() {

                //Just a function for driverManager.getConnection.. nothing else
                asdf();
            }
        }, 10000);

        Toast.makeText(getBaseContext(), "Connected to server", Toast.LENGTH_SHORT).show();
    } catch (InstantiationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
void asdf()
{
  try {
    conn =DriverManager.getConnection(url);
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  selectitem();
}

void selectitem()
{
    try {
        statement = conn.createStatement();
        resultSet = statement.executeQuery("SELECT * FROM lalit_db;");

        while(resultSet.next()){
            Log.w(s2, resultSet.getString(3));
            }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.w("It is the error", "............");
    }

    b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                b1.setBackgroundColor(c.TRANSPARENT);
                b1.setTextColor(c.RED);

                Intent i = new Intent(MainActivity.this,menus.class);
                startActivity(i);

            }
        });
}

现在我想访问Connection conn menus.java的对象in another activity

这是我的 menus.java

public class menus extends Activity{

ListView list;
ArrayAdapter<String> adapter = null;

Connection xyz;
Statement st;
ResultSet rs;

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

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

  ////////////////Here i am trying to copy the object of conn in new object xyz
    xyz = MainActivity.conn;

    Toast.makeText(getBaseContext(), "In Menus.......", Toast.LENGTH_SHORT).show();

    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); 
                      getValues();
}

void getValues()
{
    try {
        st = xyz.createStatement();
        rs = st.executeQuery("SELECT name from lalit_db where category='.Net'");

        while(rs.next())
        {
            Log.w("Here is the result..", rs.getString(1));
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}       
}

但它给出了错误:

01-02 12:49:31.489: W/dalvikvm(9917): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
01-02 12:49:31.558: E/AndroidRuntime(9917): FATAL EXCEPTION: main
01-02 12:49:31.558: E/AndroidRuntime(9917): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.z/com.example.z.menus}: java.lang.NullPointerException
01-02 12:49:31.558: E/AndroidRuntime(9917):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-02 12:49:31.558: E/AndroidRuntime(9917):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-02 12:49:31.558: E/AndroidRuntime(9917):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-02 12:49:31.558: E/AndroidRuntime(9917):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)

我该怎么办?

1 个答案:

答案 0 :(得分:0)

在MainActivity中将conn设为静态变量。

class MainActivity
{
static object conn;

}

只是访问该对象将返回null。静态对象只在整个应用程序的生命周期中存在。

根据要求编辑:

private class MyNetworkTask extends AsyncTask<Void, Void, Void> {
     protected Boolean doInBackground()  {

        try {
        st = xyz.createStatement();
        rs = st.executeQuery("SELECT name from lalit_db where category='.Net'");

        while(rs.next())
        {
            Log.w("Here is the result..", rs.getString(1));
        }


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

     protected void onProgressUpdate(Integer... progress) {
        
     }

     protected void onPostExecute(Long result) {
          Log.w(“Process completed”);
     }
 }

new MyNetworkTask()。execute();