从另一个类获取Service类的值

时间:2013-11-19 17:45:34

标签: android service android-activity

我正在创建一个项目,我从服务器获取数据并通过表视图显示它。以下是主要活动类

的代码
package com.example.e_quates;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

//import com.websmithing.broadcasttest.BroadcastService;

//import com.websmithing.broadcasttest.BroadcastService;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import java.sql.SQLException;

public class MainActivity extends Activity {
    List<String> strs = new ArrayList<String>();
    ResultSet rs=null;
    TableLayout tl;
    TableRow[] tr;
    TextView[] tv;
    private Intent intent;
    private static final String TAG = "E-Quates";
    int count=1;
    public static DB db = new DB(<connection string>);
    String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{    
            strs=db.sqlexec(query);
            db.closeConnection();
            Log.e("connected ","success");
            System.out.println("connection sucess");
            tl=(TableLayout)findViewById(R.id.table);
            Log.e("first row","created");
            tr=new TableRow[strs.size()/7];
            tv=new TextView[strs.size()];
            //int i=0;
            for(int i=0,j=-1;i<strs.size();i++)
            {
                Log.e("index "+i,"value is "+strs.get(i));
                if(i%7==0)
                {
                    j++;
                    Log.e("inside if","value "+i);
                    tr[j]=new TableRow(this);
                    tr[j].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                }
                tv[i] = new TextView(this);
                tv[i].setText(strs.get(i));
                tv[i].setId(i);
                tv[i].setBackgroundResource(R.drawable.row_shape);
                tr[j].addView(tv[i]);
            }
            for(int i=0,j=-1;i<strs.size()/7;i++)
            {
                tl.addView(tr[i]);
                Log.e("adding row",""+i);
            }
                //Thread.sleep(5000);
            }
        catch(Exception E)
        {
            System.out.println(E.toString());
        }
        intent = new Intent(this, BroadcastService.class);
    }

    public void onResume() {
        super.onResume();       
        startService(intent);
        Log.e("service","called");
        registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        stopService(intent);        
    }   

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("in the","receiver");
            updateUI(intent);       
        }
    };

    private void updateUI(Intent intent) {

        strs.clear();
        //String dummy = null;
        Log.e("inside ","UI update");
        //db.sqlexec(query);
        try
        {
        strs = intent.getStringArrayListExtra("TAG");
        //application_main apm=((application_main) getApplicationContext());
        for(int i=0;i<strs.size();i++)
        {
            Log.e("inside for","loo[");
            tv[i].setText(strs.get(i));
        }
        }
        catch(Exception e)
        {
            Log.e("exception occured in intent value",e.toString());
        }
        //Log.e("value is ",dummy.toString());
            //Thread.sleep(5000);
        }    
}

这是我的DB类

package com.example.e_quates;
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 java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
//import android.widget.*;

class DB extends Activity
{
    List<String> strs = new ArrayList<String>();
    ResultSet rs=null;
    Connection conn=null;
    private Intent intent;
    @SuppressLint("NewApi")
    String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
    public DB(String db_connect_string,String db_userid,String db_password) {
        System.out.println("inside DB");
        Log.e("inside DB","");
        try
        {
            StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Log.e("Inside first","try block");
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
            Log.e("Connection sucessfull","");
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    public List<String> sqlexec(String sql)
    {
        try
        {
            Statement stmt = null;
            strs.clear();
            try {
                stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                Log.e("##########################################################################3","result in rs");
                while (rs.next()) {
                    strs.add(rs.getString("SymbolName"));
                    strs.add(rs.getString("LTP"));
                    strs.add(rs.getString("Net_change"));
                    strs.add(rs.getString("Bid_vol"));
                    strs.add(rs.getString("Ask"));
                    strs.add(rs.getString("Ask_vol"));
                    strs.add(rs.getString("High_Index"));
                    Log.e("symbolname",rs.getString("SymbolName"));
                }
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        catch(Exception e)
        {
            Log.e("error:",e.toString());
        }
        Log.e("return ","to main");
        int size=strs.size();
        Log.e("array size in DB",""+size);

        //Log.e("set string",String.valueOf(apm.getState()));
        Log.e("application ","initialized");
        return strs;
    }

    public void closeConnection()
    {
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

};

这是服务类

package com.example.e_quates;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class BroadcastService extends Service {
    List<String> strs_array1 = new ArrayList<String>();
    private static final String TAG = "E-Quates";
    public static final String BROADCAST_ACTION = "com.example.e_quates";
    private final Handler handler = new Handler();
    Intent intent;
    String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
    int counter = 0;
    DB db1=new DB(<connection string>);
    //String dummy;
    @Override
    public void onCreate() {
        super.onCreate();
        //db1.forService();
        intent = new Intent(BROADCAST_ACTION);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 3000); // 3 second

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            DisplayLoggingInfo();
            handler.postDelayed(this, 3000); // 3 seconds
        }
    };  

    private void DisplayLoggingInfo() {

        Log.d(TAG, "entered DisplayLoggingInfo");
            strs_array1=db1.sqlexec(query);
            intent.putStringArrayListExtra(TAG, (ArrayList<String>)strs_array1);
            sendBroadcast(intent);
            Log.e("Broadcast","done");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {       
        handler.removeCallbacks(sendUpdatesToUI);       
        super.onDestroy();
    }
}  

问题是,当我从主活动类调用DB类的sqlexec()函数时,它返回正确的值但是我正在调用它的服务类,它不返回SQL输出。我已经尝试了在服务类中调用sqlexec()函数的所有可能组合,但是同样的问题正在发生。 函数db.sqlexec(query)没有返回任何值..  我已经提到了link寻求帮助:

1 个答案:

答案 0 :(得分:0)

不要在Service构造函数中进行任何初始化。 Android使用自己的机制构建Android组件(Activity, Service, BroadcastReceiver, ContentProvider)。将所有初始化代码从构造函数移动到onCreate()方法。

编辑:澄清我的指示

我指的是这段代码:

List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);

这些变量将在构造函数中初始化(即使您没有显式创建构造函数,也会为您创建一个)。常量不是问题,但这些可能会导致问题:

private final Handler handler = new Handler();
DB db1=new DB(<connection string>);

您需要在Handler中创建onCreate()。我不知道您的DB班级正在做什么,但您可能也希望在onCreate()中创建该实例。

编辑2

我现在看到DB课程的代码。你不能这样做!您的DB课程延长了Activity。您无法像这样创建此类的实例:

DB db1=new DB(<connection string>);

Android组件(Activity, Service, BroadcastReceiver, ContentProvider)由Android框架使用自己的机制创建。

为什么您的DB课程会延长Activity?它不需要。