0

を使用してAndroidアプリケーションを作成していますEclipseユーザーが宝くじ番号を入力する場所。次に、アプリは、Jsoup を使用して最新のライブ抽選から宝くじ番号を取得し、National Lottery Web サイトから HTML 宝くじ番号を解析します。次に、ユーザーがチェック ボタンを押すと、新しいアクティビティが開き、ユーザーの番号と宝くじの抽選番号の一致が表示され、ユーザーが宝くじに当選したかどうかが確認されます。この時点で、ユーザーが宝くじの Web ページを開いて、番号が一致した場合に賞品を確認できるようにするボタンが必要です。ただし、ブラウザを開くのに苦労しています。ユーザーが自分の番号を入力してチェック ボタンを押した後、プログラムがクラッシュするため、自分の番号と宝くじの番号を比較する段階にさえ達していません。アクティビティを開始できないというエラーが表示されますDisplayNumbersActivityヌルポインタ例外があるからです。私のコードの問題が何か、またはそれを解決する方法を特定するのを手伝ってくれる人はいますか? 前もって感謝します!主なアクティビティとDisplayNumbersアクティビティ コードを以下に示します。

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
4

1 に答える 1

0

アプリケーションタグ内のAndroidManifest.xmlにアクティビティ参照を追加します

<activity android:name=".DisplayNumbersActivity"/>
于 2013-09-16T12:32:09.577 に答える