2012-10-26 49 views
0

這是我的代碼。getExtras()返回null

在我的主要.java文件中。

public void showQuiz (View view){ 
     Username = (EditText) findViewById(R.id.Username); 
     String userId = Username.getText().toString(); 
     String deviceId = Secure.getString(this.getContentResolver(), 
       Secure.ANDROID_ID); 
     //this intent is used to open other activity wich contains another webView 
     Intent intent = new Intent(this, Quiz.class); 

     Bundle bun = new Bundle(); 
     bun.putString("userid",userId); 
     bun.putString("deviceid", deviceId); 

     intent.putExtras(bun); 
     startActivity(intent); 
    } 

這是什麼在活動的java文件。

package com.earn.egpt; 

import android.app.Activity; 
import android.os.Bundle; 
import android.webkit.WebView; 

public class Quiz extends Activity { 
    private static final String url = "http://www.m.s-w-family.com/?subid="; 
    private static final String url2 = "&deid="; 

    @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_quiz); 
      Bundle extras=getIntent().getExtras(); 
      String userId=extras.getString("userId"); 
      String deviceId=extras.getString("deviceId"); 
     WebView webview; 
     webview = (WebView) findViewById(R.id.webView1); 
     webview.getSettings().setJavaScriptEnabled(true); 
     webview.loadUrl(url+userId+url2+deviceId); 
     } 
    } 

由於某些原因它將字符串作爲null傳遞,但我不知道爲什麼。我對這種編程非常陌生,所以我甚至不知道該去哪裏。我已經查看了類似於我的其他問題,並嘗試瞭解決這些問題,但值仍然爲空。

回答

2

您正在使用額外的Bundle。直接把臨時演員到意圖,而不是:

intent.putExtra("userid", userId); 
intent.putExtra("deviceid", deviceId); 

startActivity(intent); 

現在你getString()方法將返回在測驗想要什麼。

+0

我得到這個錯誤'該方法putString(字符串,字符串)是不明確的類型意圖' – kira423

+0

哦,達爾,我改變了我的代碼適當的方法。謝謝! – Sam

+0

不幸的是,它們仍然返回NULL – kira423

5

觀察變量的大小寫。你插入「userid」並檢索「userId」。

+0

非常感謝,我現在感覺很傻! – kira423

+0

不錯,趕上蒂姆,我錯過了。 (upvote)@ kira423考慮對id使用「public static final String」引用,而不是手寫Strings,以防止將來出現這種錯誤。 – Sam