Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Eclipse连接到Android中的web浏览器_Android_Eclipse - Fatal编程技术网

使用Eclipse连接到Android中的web浏览器

使用Eclipse连接到Android中的web浏览器,android,eclipse,Android,Eclipse,我正在使用Eclipse创建一个Android应用程序,用户在其中输入彩票号码。然后,该应用程序使用Jsoup从国家彩票网站解析html彩票号码,从最新的现场抽奖中检索彩票号码。然后,用户按下检查按钮,然后打开一个新活动,显示用户号码和彩票抽奖号码之间的匹配情况,以检查用户是否中了彩票。在这一点上,我想有一个按钮,允许用户打开彩票网页,使他们能够检查他们的奖金,如果他们匹配他们的号码。但是,我在打开浏览器时遇到困难。用户输入号码并点击“检查”按钮后,程序崩溃,因此他们甚至无法将自己的号码与彩票号

我正在使用
Eclipse
创建一个Android应用程序,用户在其中输入彩票号码。然后,该应用程序使用Jsoup从国家彩票网站解析html彩票号码,从最新的现场抽奖中检索彩票号码。然后,用户按下检查按钮,然后打开一个新活动,显示用户号码和彩票抽奖号码之间的匹配情况,以检查用户是否中了彩票。在这一点上,我想有一个按钮,允许用户打开彩票网页,使他们能够检查他们的奖金,如果他们匹配他们的号码。但是,我在打开浏览器时遇到困难。用户输入号码并点击“检查”按钮后,程序崩溃,因此他们甚至无法将自己的号码与彩票号码进行比较。我收到的错误是,由于存在空指针异常,我无法启动活动
DisplayNumbersActivity
。有人能帮我确定我的代码有什么问题,或者我如何解决它吗?提前谢谢!我在下面列出了主要活动和
displayNumber
活动代码

public class DisplayNumbersActivity extends Activity {

private EditText urlText;
private Button checkWeb;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_numbers);
    // Show the Up button in the action bar.
    setupActionBar();

    //get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    //create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(20);
    textView.setTextColor(Color.RED);
    textView.setText(message);

    //set the text view as the activity layout
    setContentView(textView);

    urlText = (EditText) findViewById(R.id.url_field);
    checkWeb = (Button) findViewById(R.id.checkWeb);

    //set up event handlers
    checkWeb.setOnClickListener (new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            openBrowser();
        }//onClick

    });//setOnClickListener

    urlText.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_ENTER) { 
                openBrowser();
                return true;
            }
            return false;
        }//onKey

    });//setOnKeyListener

}//onCreate

//open a browser on the URL specified in the text box
private void openBrowser() {
    Uri uri = Uri.parse(urlText.getText().toString());
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}//openBrowser




/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
}//setUpActionBar


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}//onOptionsItemSelected

 }//class




public class MainActivity extends Activity {

private final static String NATIONAL_LOTTERY_DRAW_URL = "http://www.national-lottery.co.uk/player/p/drawHistory.do";
public final static String EXTRA_MESSAGE = ".com.example.lottochecker.MESSAGE";

boolean bonus = false;
boolean jackpot = false;
int lottCount = 0;
Button check;
Integer [] numbers;
int bonusBall;
String userInput = "";
final int MAX = 49;
boolean validType = false;
int userGuess;

private LotteryDraw lotteryDraw;

@Override
//when the activity is created, call the layout class
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     

}//onCreate

@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;
}//onCreateOptionsMenu

//called when the user clicks the send button
public void checkNumbers(View view) {
    //set up an array of text boxes for the user to put in their numbers
    EditText[] text_fields = new EditText[6];
    //set up an array of string variables for holding user input
    String[] str_nums = new String[6];
    //set up an array to hold integer values having been converted from the user input as a String 
    int[] int_nums = new int[6];
    //populate the array of text boxes with user input
    text_fields[0] = (EditText) findViewById(R.id.enter_numbers);
    text_fields[1] = (EditText) findViewById(R.id.enter_numbers2);
    text_fields[2] = (EditText) findViewById(R.id.enter_numbers3);
    text_fields[3] = (EditText) findViewById(R.id.enter_numbers4);
    text_fields[4] = (EditText) findViewById(R.id.enter_numbers5);
    text_fields[5] = (EditText) findViewById(R.id.enter_numbers6);

    for(int i=0; i<6; i++)
    {
        str_nums[i] = text_fields[i].getText().toString();

        // if the text box is empty, print error and stop processing.
        // if not empty convert string to int and store in array
        if(str_nums[i].equals(""))
        {
            Toast.makeText(MainActivity.this, "Please enter valid number in text box "+(i+1), Toast.LENGTH_LONG).show();
            return;
        }
        else
        {
            int_nums[i] = Integer.parseInt(str_nums[i]);
        }
    }

    // check validity of numbers entered
    for(int i=0; i<6; i++)
    {

        // check numbers are in range
        if (int_nums[i] < 1 || int_nums[i] > MAX)
        {

            Toast.makeText(MainActivity.this, "Number " + int_nums[i] + " in text box " + (i+1) + " is out of range. Please enter a number between 1 and 49", Toast.LENGTH_LONG).show();
            return;
        }

        // check for duplicates
        for(int j=0; j<6; j++)
        {
            if(i != j)
            {
                if (int_nums[i] == int_nums[j])
                {
                    Toast.makeText(MainActivity.this, "The number " + int_nums[i] + " is dublicated in text boxes " + (i+1) + " and " + (j+1) + ". Duplicates can not be accepted", Toast.LENGTH_LONG).show();
                    return;
                }
            }

        }
    }

    // numbers entered are valid    
    int matches = 0;
    boolean bonus_match = false;

    final int[] LOTTONUMBERS  = lotteryDraw.getNumbers();

    // check the 6 lotto numbers
    for(int lotto_num = 0; lotto_num < 6; lotto_num++)
    {
        for(int user_num = 0; user_num < 6; user_num++)
        {
            if(LOTTONUMBERS[lotto_num] == int_nums[user_num])
            {
                matches++;
                break;
            }
        }
    }

    // check the bonus ball
    for(int user_num = 0; user_num < 6; user_num++)
    {
        if(lotteryDraw.getBonusBall() == int_nums[user_num])
        {
            bonus_match = true;
            break;
        }
    }
    //inform the user of the results
    String output = "The lotto numbers are:\n";
    for(int i=0; i<6; i++)
    {
        output = output + LOTTONUMBERS[i] + " ";
    }

    output = output + " bonus: " + lotteryDraw.getBonusBall(); 

    output = output + "\n\nYour numbers are:\n";

    for(int i=0; i<6; i++)
    {
        output = output + str_nums[i] + " ";
    }

    output = output + "\n\nYou have matched "+ matches + " numbers ";

    if(bonus_match)
    {
        output = output + "and the bonus";
    }

    if(matches == 6)
    {
        output = output + "\n\nCONGRATULATIONS - YOU HAVE WON THE JACKPOT";
    }
    else if (matches >= 3)
    {
        output = output + "\n\nCONGRATULATIONS - you have won a prize";
    }
    else
    {
        output = output + "\n\nBad Luck - not enough matches to win";
    }
    //display the lottery results to the new activity  
    Intent intent = new Intent(this, DisplayNumbersActivity.class);
    intent.putExtra(EXTRA_MESSAGE, output);
    startActivity(intent);      



}//method

public void getLotteryDrawFromWebsite(View view) {
    ConnectivityManager connMgr = (ConnectivityManager) 
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        new DownloadWebpageTask().execute(NATIONAL_LOTTERY_DRAW_URL);
    } else {
        //TODO: add error info
    }
}

private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        lotteryDraw = extractLotteryDraw(result);
        TextView tv = (TextView) findViewById(R.id.textView1);
        tv.setText(lotteryDraw.toString());
        //when the lottery draw has been received enable the check button for the user to check numbers
        Button checkNumbers = (Button)findViewById(R.id.check);
        checkNumbers.setEnabled(true);
        //Log.d("DownloadWebpageTask", lotteryDraw.toString());
    }
}

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 100000 characters of the retrieved
    // web page content.
    int len = 200000;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setRequestProperty( "User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4" );

        // Starts the query
        conn.connect();
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}

private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");        
    char[] buffer = new char[len];
    reader.read(buffer);
    return (new String(buffer)).trim();
}

private LotteryDraw extractLotteryDraw(String html) {

    Log.d("extractLotteryDraw",html);

    LotteryDraw lotteryDraw = new LotteryDraw();

    Document doc = Jsoup.parse(html);

    Elements elements = doc.getElementsByClass("drawhistory");
    //System.out.println(elements.toString());
    Element table = elements.first();
    Element tbody = table.getElementsByTag("tbody").first();
    Element firstLottoRow = tbody.getElementsByClass("lottorow").first();

    Element dateElement = firstLottoRow.child(0);
    System.out.println(dateElement.text());

    Element gameElement = firstLottoRow.child(1);
    System.out.println(gameElement.text());

    Element noElement = firstLottoRow.child(2);
    System.out.println(noElement.text());
    String[] split = noElement.text().split(" - ");

    int[] numbers = new int[split.length];

    int i = 0;
    for (String strNo : split) {
        numbers[i] = Integer.valueOf(strNo);
        i++;
    }

    lotteryDraw.setNumbers(numbers);
    Log.v("DEBUG", "the value of numbers is " + numbers);
    Element bonusElement = firstLottoRow.child(3);
    Integer bonusBall = Integer.valueOf(bonusElement.text());

    lotteryDraw.setBonusBall(bonusBall);
    Log.v("DEBUG", "the value of numbers is " + numbers);
    return lotteryDraw;

}//extractLotteryDraw  
}//class
公共类DisplayNumbersActivity扩展活动{
私人编辑文本;
私人按钮检查网站;
@SuppressLint(“新API”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u display\u Number);
//在操作栏中显示“向上”按钮。
setupActionBar();
//从意图中获得信息
Intent=getIntent();
字符串消息=intent.getStringExtra(MainActivity.EXTRA_消息);
//创建文本视图
TextView TextView=新的TextView(此);
textView.setTextSize(20);
textView.setTextColor(Color.RED);
textView.setText(消息);
//将文本视图设置为活动布局
setContentView(文本视图);
urlText=(EditText)findViewById(R.id.url\u字段);
checkWeb=(按钮)findviewbyd(R.id.checkWeb);
//设置事件处理程序
checkWeb.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
openBrowser();
}//onClick
});//setOnClickListener
setOnKeyListener(新的OnKeyListener(){
@凌驾
公共布尔onKey(视图、int keyCode、KeyEvent事件){
//TODO自动生成的方法存根
如果(keyCode==KeyEvent.keyCode_输入){
openBrowser();
返回true;
}
返回false;
}//安基
});//setOnKeyListener
}//一次创建
//在文本框中指定的URL上打开浏览器
私有void openBrowser(){
Uri=Uri.parse(urlText.getText().toString());
意图=新意图(Intent.ACTION\u视图,uri);
星触觉(意向);
}//开放浏览器
/**
*如果API可用,请设置{@link android.app.ActionBar}。
*/
@TargetApi(构建版本代码蜂窝)
私有void setupActionBar(){
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.HONEYCOMB){
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}//设置操作栏
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例android.R.id.home:
//此ID表示“主页”或“向上”按钮
//活动中,将显示向上按钮。使用NavUtils允许用户
//在应用程序结构中向上导航一级。对于
//更多详细信息,请参见Android Design上的导航模式:
//
// http://developer.android.com/design/patterns/navigation.html#up-对背
//
NavUtils.navigateUpFromSameTask(本);
返回true;
}
返回super.onOptionsItemSelected(项目);
}//OnOptions项目已选定
}//阶级
公共类MainActivity扩展了活动{
私有最终静态字符串国家彩票抽奖URL=”http://www.national-lottery.co.uk/player/p/drawHistory.do";
公共最终静态字符串EXTRA_MESSAGE=“.com.example.lottochecker.MESSAGE”;
布尔加值=假;
布尔jackpot=false;
int-lottCount=0;
按钮检查;
整数[]个数;
int骨球;
字符串userInput=“”;
最终int MAX=49;
布尔值validType=false;
int-userGuess;
私人彩票抽签抽签;
@凌驾
//创建活动时,调用布局类
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}//一次创建
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}//OnCreateOptions菜单
//用户单击发送按钮时调用
公共作废支票号码(查看){
//设置一组文本框供用户输入数字
EditText[]文本\字段=新的EditText[6];
//设置用于保存用户输入的字符串变量数组
字符串[]str_nums=新字符串[6];
//设置一个数组以保存已从用户输入转换为字符串的整数值
int[]int_nums=新的int[6];
//使用用户输入填充文本框数组
文本字段[0]=(EditText)findViewById(R.id.输入文本编号);
文本字段[1]=(EditText)findViewById(R.id.输入\u编号2);
文本字段[2]=(EditText)findViewById(R.id.输入\u编号3);
文本字段[3]=(EditText)findViewById(R.id.输入\u编号4);
文本字段[4]=(EditText)findViewById(R.id.输入\u编号5);
文本字段[5]=(EditText)findViewById(R.id.输入\u编号6);

对于(inti=0;i在您的AndroidManifest.xml内部应用程序标记中添加活动引用

<activity android:name=".DisplayNumbersActivity"/>