簡體   English   中英

Android應用程序在收到意圖包時崩潰了?

[英]Android app crashing on receiving intent bundle?

首先,我要說我是一個完整的新手,這是我的第一個項目,並且我已經嘗試過在各處搜索以回答我的問題。

我在android上設置了登錄屏幕。 一旦用戶單擊登錄按鈕並且登錄名/密碼正確(在PHP / SQL中已驗證),它將向下一個活動發送意圖/捆綁。

這是發送意圖/捆綁的代碼:

Intent intent = new Intent(this, Homepage.class);
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
Intent intent2 = new Intent(this, Homepage.class);
intent2.putExtra("username2", username2);
startActivity(intent);

這是用於接收下一個活動的意圖包的代碼:

   Intent intent2 = getIntent(); 
   String usernamefromlogin = intent2.getExtras().getString("username2");
   String url5 = url.concat(usernamefromlogin);
   TextView text = (TextView) findViewById(R.id.errorchecking);
   text.setText(url5);

我使用concat()將URL放在意圖包之前,因為該URL將用作對PHP文件的_GET命令(但我離題了)。 目前,我已將其設置為將文本放入TextView中,以便可以看到最終結果,但是在崩潰之前,應用程序崩潰了。

當我點擊登錄按鈕時,我的應用程序崩潰了。 這是我得到的Logcat:

11-30 20:06:39.449: E/AndroidRuntime(4578): FATAL EXCEPTION: main
11-30 20:06:39.449: E/AndroidRuntime(4578): Process: com.sencide, PID: 4578
11-30 20:06:39.449: E/AndroidRuntime(4578): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sencide/com.sencide.Homepage}: java.lang.NullPointerException
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.os.Handler.dispatchMessage(Handler.java:102)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.os.Looper.loop(Looper.java:137)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.ActivityThread.main(ActivityThread.java:4998)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at java.lang.reflect.Method.invokeNative(Native Method)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at java.lang.reflect.Method.invoke(Method.java:515)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at dalvik.system.NativeStart.main(Native Method)
11-30 20:06:39.449: E/AndroidRuntime(4578): Caused by: java.lang.NullPointerException
11-30 20:06:39.449: E/AndroidRuntime(4578):     at com.sencide.Homepage.onCreate(Homepage.java:46)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.Activity.performCreate(Activity.java:5243)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-30 20:06:39.449: E/AndroidRuntime(4578):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
11-30 20:06:39.449: E/AndroidRuntime(4578):     ... 11 more
11-30 20:06:42.569: I/Process(4578): Sending signal. PID: 4578 SIG: 9

這是我的整個代碼:

AndroidLogin.java

public class AndroidLogin extends Activity implements OnClickListener {


Button ok,back,exit;
TextView result;
String thisisausername;



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
   setContentView(R.layout.main);



    // Login button clicked
    ok = (Button)findViewById(R.id.btn_login);
    ok.setOnClickListener(this);


    result = (TextView)findViewById(R.id.tbl_result);



}









public void postLoginData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();

   // login.php returns true if username and password match in db 
    HttpPost httppost = new HttpPost("http://10.0.2.2/login.php");

    try {




        // Add user name and password
        EditText uname = (EditText)findViewById(R.id.txt_username);
        String username = uname.getText().toString();



        EditText pword = (EditText)findViewById(R.id.txt_password);
        String password = pword.getText().toString();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        Log.w("SENCIDE", "Execute HTTP Post Request");
        HttpResponse response = httpclient.execute(httppost);

        String str = inputStreamToString(response.getEntity().getContent()).toString();
        Log.w("SENCIDE", str);

        if(str.toString().equalsIgnoreCase("true"))
        {
            Log.w("SENCIDE", "TRUE");
            result.setText("Login Successful! Please Wait...");   
        }else
        {
            Log.w("SENCIDE", "FALSE");
            result.setText(str);                
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    // Read response until the end
    try {
        while ((line = rd.readLine()) != null) { 
            total.append(line); 
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Return full string
    return total;
}


public void RegisterButton(View view) {
    String url = "http://10.0.2.2/register.php";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);   
}




@Override
public void onClick(View view) {
            postLoginData();




            // turns the text in the textview "Tbl_result" into a text string called "tblresult"
            TextView tblresult = (TextView) findViewById(R.id.tbl_result);




    // If "tblresult" text string matches the string "Login Successful! Please Wait..." exactly, it will switch to next activity
            if (tblresult.getText().toString().equals("Login Successful! Please Wait...")) {
                  Intent intent = new Intent(this, Homepage.class);
                  EditText uname2 = (EditText)findViewById(R.id.txt_username);
                  String username2 = uname2.getText().toString();
                  intent.putExtra("username2", username2);
                  startActivity(intent);
               }    






}



}

Homepage.Java

public class Homepage extends Activity {






//URL to get JSON Arrays
public static String url = "http://x.x.x.x/SQL.php?username=123";



//JSON Node Names 
private static final String TAG_USER = "users";
private static final String TAG_ID = "uid";
private static final String TAG_NAME = "fullname";
private static final String TAG_DISPLAY = "displayname";
private static final String TAG_EMAIL = "email";
private static final String TAG_PW = "password";
private static final String TAG_CREATED = "created_at";
private static final String TAG_UPDATED = "updated_at";


JSONArray user = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


   //Get login name from EditText in login screen and concatenate it to PHP user-name for _GET 
   Intent intent2 = getIntent(); 
   String usernamefromlogin = intent2.getExtras().getString("username2");
   String url5 = url.concat(usernamefromlogin);
   TextView text = (TextView) findViewById(R.id.errorchecking);
   text.setText(url5);


    setContentView(R.layout.reshomepage);

    // Creating new JSON Parser
    JSONParser jParser = new JSONParser();

    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting JSON Array
        user = json.getJSONArray(TAG_USER);
        JSONObject c = user.getJSONObject(0);

        // Storing  JSON item in a Variable
        String uid = c.getString(TAG_ID);
        String name = c.getString(TAG_NAME);
        String display = c.getString(TAG_DISPLAY);
        String email = c.getString(TAG_EMAIL);
        String pw = c.getString(TAG_PW);
        String created = c.getString(TAG_CREATED);
        String updated = c.getString(TAG_UPDATED);



        //Importing TextView
        final TextView uid1 = (TextView)findViewById(R.id.tvuid);
        final TextView name1 = (TextView)findViewById(R.id.tvfullname);
        final TextView display1 = (TextView)findViewById(R.id.tvdisplayname);
        final TextView email1 = (TextView)findViewById(R.id.tvemail);
        final TextView pw1 = (TextView)findViewById(R.id.tvpassword);
        final TextView created1 = (TextView)findViewById(R.id.tvcreated_at);
        final TextView updated1 = (TextView)findViewById(R.id.tvupdated_at);


        //Set JSON Data in TextView
        uid1.setText(uid);
        name1.setText(name);
        display1.setText(display);
        email1.setText(email);
        pw1.setText(pw);
        created1.setText(created);
        updated1.setText(updated);


} catch (JSONException e) {
    e.printStackTrace();
}

}

}

JSONParser.java

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

Main.XML(第一個登錄屏幕)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<!-- Text at Top !-->    
<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/lbl_top" 
android:textSize="16sp" 
android:typeface="sans" 
android:text="Please Login" 
/>

<!-- Username Text Above Field  !-->
<TextView android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/lbl_username" 
android:text="User Name (e-mail)" 
/>    

<!-- Username Field  !-->
<EditText 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:textSize="18sp" 
android:id="@+id/txt_username" 
/>

<!-- Password Text Above Field  !-->
<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/lbl_password" 
android:text="Password" 
/>

<!-- Password Field  !-->
<EditText 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:password="true" 
android:id="@+id/txt_password" 
/>

<!--  Login Button  !-->
<Button 
android:layout_width="match_parent" 
android:layout_height="35dp" 
android:id="@+id/btn_login" 
android:text="Login"
android:onClick="LoginScreenButton"
/>

<!--  Register Button  !-->

<Button 
android:layout_width="match_parent" 
android:layout_height="35dp" 
android:id="@+id/register" 
android:text="New Registration"
android:onClick="RegisterButton"
/>



<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:id="@+id/tbl_result"
android:textColor="#00FF00"
/>

<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:id="@+id/tbl_result2"
android:textColor="#00FF00"
/>

</LinearLayout>

reshomepage.XML(我嘗試向其發送意圖的第二個屏幕)

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
<TextView
    android:id="@+id/tvuid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

<TextView
    android:id="@+id/tvfullname"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
<TextView
    android:id="@+id/tvdisplayname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

<TextView
    android:id="@+id/tvemail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

    <TextView
    android:id="@+id/tvpassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

    <TextView
    android:id="@+id/tvcreated_at"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

    <TextView
    android:id="@+id/tvupdated_at"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

       <TextView
    android:id="@+id/errorchecking"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

</LinearLayout>

這里的問題是您創建2個intent(intent和intent2),然后將用戶名保存在intent2中,但是正在調用startActivity(intent)。

因此,基本上,刪除其中一個意圖,您的代碼應如下所示:

Intent intent = new Intent(this, Homepage.class);
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
intent.putExtra("username2", username2);
startActivity(intent);

讓我知道這是怎么回事

這里的問題是,您已經將用戶名2附加附加到了intent2,但沒有使用intent2。

您開始活動,然后在傳入的意圖中查找額外的“ username2”,因為您發送的意圖不包含額外的“ username2”,因此您從登錄名中獲得的username分配了null值,並導致您在您的堆棧跟蹤。

只需擺脫第二個意圖,然后將字符串多余地放在開始活動時使用的字符串中:

Intent intent = new Intent(this, Homepage.class);
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
intent.putExtra("username2", username2);
startActivity(intent);

為了安全起見,在運行和使用它之前,請確保有此目的。

Intent intent = getIntent(); 
if (intent.hasExtra("username2") {
   String usernamefromlogin = intent.getExtras().getString("username2");
   String url5 = url.concat(usernamefromlogin);
   TextView text = (TextView) findViewById(R.id.errorchecking);
   text.setText(url5);
} else {
    // ...appropriate error handling goes here!
}

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM