2013-10-20 49 views
0

我正在爲我們的頂點項目做一個android應用程序。我正在嘗試將唯一的按鈕放在主屏幕中用於登錄目的。顯然,我的代碼還沒有完成,因爲這只是爲了檢查用戶帳戶,這意味着我沒有使用意圖還沒有去另一個屏幕。點擊這個特定的按鈕(id是loginBtn),我正在捕捉一個「空指針異常」。任何幫助將不勝感激。點擊按鈕顯示空指針異常錯誤

這裏是在MainActivity類

package com.feufern.apms; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.Timer; 
import java.util.TimerTask; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.BasicResponseHandler; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import android.os.Bundle; 
import android.os.Handler; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.animation.Animation; 
import android.view.animation.AnimationUtils; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageView; 
import android.widget.RadioButton; 
import android.widget.RadioGroup; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity implements OnClickListener{ 

    //login 
    Button b; 
    EditText et,pass; 
    TextView tv; 
    RadioGroup radioUserGroup; 
    RadioButton radioUserButton; 

    //json 
    HttpPost httppost; 
    StringBuffer buffer; 
    HttpResponse response; 
    HttpClient httpclient; 
    List<NameValuePair> nameValuePairs; 
    ProgressDialog dialog = null; 

    //session 
    public static String student_id; 

    //slideshow variables 
    public int imageIndex=0; 
    Timer timer; 
    TimerTask task; 
    ImageView slidingImages; 
    //end of slideshow variables 

    private int[] IMAGE_ID = {R.drawable.slide1, R.drawable.slide2, R.drawable.slide3, R.drawable.slide4}; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     try{ 
     super.onCreate(savedInstanceState); 
     this.setTitle("Welcome"); 
     setContentView(R.layout.activity_main); 

     //login codes 
      b = (Button) findViewById(R.id.loginBtn); 
      et = (EditText)findViewById(R.id.username); 
      pass= (EditText)findViewById(R.id.password); 

      b.setOnClickListener(this); 

     }catch(Exception e){ 
      Toast.makeText(getApplicationContext(), 
         "Error..." + e.getMessage(), Toast.LENGTH_LONG).show(); 
     } 

     try{ 
     //start of code for slideshow 
     final Handler mHandler = new Handler(); 
     final Runnable mUpdateResults = new Runnable() { 
      public void run() { 
       SlideShow(); 
      } 
     }; 


     int delay = 200; //1sec 
     int period = 4000; //3sec 
     Timer timer = new Timer(); 
     timer.scheduleAtFixedRate(new TimerTask() { 
       public void run() { 
        mHandler.post(mUpdateResults); 
       } 
     }, delay, period); 
     //end of code for slideshow 
     }catch(Exception e){ 
      Toast.makeText(getApplicationContext(), 
         "Error..." + e.getMessage(), Toast.LENGTH_LONG).show(); 
     } 
    } 

    private void SlideShow() { 
     slidingImages = (ImageView)findViewById(R.id.slideBanner); 
     slidingImages.setImageResource(IMAGE_ID[imageIndex%IMAGE_ID.length]); 
     imageIndex++;  
     Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); 
     slidingImages.startAnimation(fadeInAnimation); 
    } 

    void login(){ 
     try{    

      httpclient=new DefaultHttpClient(); 
      httppost= new HttpPost("http://10.0.2.2/mobile/check.php"); 
      //add your data 
      nameValuePairs = new ArrayList<NameValuePair>(2); 
      // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
      nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value']; 
      nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      //Execute HTTP Post Request 
      response=httpclient.execute(httppost); 
      ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      final String response = httpclient.execute(httppost, responseHandler); 
      System.out.println("Response : " + response); 


      if(response.equalsIgnoreCase("User Found")){ 
       runOnUiThread(new Runnable() { 
        public void run() { 
         Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show(); 

        } 
       }); 

       startActivity(new Intent(MainActivity.this, MenuPage.class)); 
       student_id = et.getText().toString().trim(); 
      }else{ 
       startActivity(new Intent(MainActivity.this, MenuPage.class)); 
       student_id = et.getText().toString().trim();   
      } 

     }catch(Exception e){ 
      dialog.dismiss(); 
      System.out.println("Exception : " + e.getMessage()); 
     } 
    } 
    void showAlert(){ 
     try{ 
     MainActivity.this.runOnUiThread(new Runnable() { 
      public void run() { 
       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
       builder.setTitle("Login Error."); 
       builder.setMessage("User not Found.") 
         .setCancelable(false) 
         .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 

          } 
         });      
       AlertDialog alert = builder.create(); 
       alert.show();    
      } 
     }); 
     }catch(Exception e){ 
      Toast.makeText(getApplicationContext(), 
         "Error..." + e.toString(), Toast.LENGTH_LONG).show(); 

     } 
    } 

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

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     switch(v.getId()){ 
     case R.id.loginBtn: 
      try{ 

      login(); 
      }catch(Exception e){ 
       Toast.makeText(getApplicationContext(), 
          "Error..." + e.getMessage(), Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 


} 

的activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_gravity="center|center_vertical" 
    android:background="@color/firstbgcolor" 
    android:orientation="vertical" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:adjustViewBounds="true" 
     android:src="@drawable/banner" /> 

    <ImageView 
     android:id="@+id/slideBanner" 
     android:layout_width="match_parent" 
     android:layout_height="177dp" 
     android:adjustViewBounds="true" 
     android:src="@drawable/slide1" /> 

    <FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="23dp" > 
    </FrameLayout> 

    <FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:layout_weight="0.51" > 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" > 

      <FrameLayout 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_weight="0.08" > 

      </FrameLayout> 

      <ScrollView 
       android:id="@+id/scrollView1" 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_weight="0.18" > 

       <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:orientation="vertical" > 

        <TextView 
         android:id="@+id/textView1" 
         android:layout_width="103dp" 
         android:layout_height="wrap_content" 
         android:text="Username" 
         android:textAppearance="?android:attr/textAppearanceSmall" /> 

        <EditText 
         android:id="@+id/username" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" > 

         <requestFocus /> 
        </EditText> 

        <TextView 
         android:id="@+id/textView2" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:text="Password" 
         android:textAppearance="?android:attr/textAppearanceSmall" /> 

        <EditText 
         android:id="@+id/password" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:ems="10" 
         android:inputType="textPassword" /> 

        <LinearLayout 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" > 

         <TextView 
          android:id="@+id/textView3" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:layout_weight="0.74" 
          android:text="Login as: " 
          android:textAppearance="?android:attr/textAppearanceSmall" /> 
        </LinearLayout> 

        <Button 
         android:id="@+id/loginBtn" 
         style="?android:attr/buttonStyleSmall" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:layout_gravity="center" 
         android:text="Login" /> 
       </LinearLayout> 

      </ScrollView> 

      <FrameLayout 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_weight="0.08" > 
      </FrameLayout> 

     </LinearLayout> 
    </FrameLayout> 

</LinearLayout> 

和清單文件

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.feufern.apms" 
    android:versionCode="1" 
    android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools"> 

    <uses-sdk 
     android:minSdkVersion="10" 
     android:targetSdkVersion="14" tools:ignore="OldTargetApi"/> 

    <uses-permission android:name="android.permission.INTERNET"></uses-permission> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/logo" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 

     <activity 
      android:screenOrientation="portrait" 
      android:name="com.feufern.apms.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <activity 
      android:screenOrientation="portrait" 
      android:name=".MenuPage" 
      android:label="@string/app_name" /> 

    </application> 

</manifest> 

我不知道爲什麼我得到這個錯誤。 :(請幫忙,謝謝!

+0

你確定你得到一個NPE,而不是NetworkOnMainThreadException? – Blackbelt

+0

這樣一長段代碼沒有行號和沒有異常堆棧指定異常行。 Ahhhhh痛苦。在您的最後搜索該行。並在調用其中的任何方法之前查看該語句中的對象已初始化並且不爲null。 – Javanator

+0

@blackbelt是的,我敢肯定,因爲我使用了try/catch塊 –

回答

1

你在得到下面一行

dialog.dismiss(); 

NullPointerException異常既然你沒有初始化對話框。

而且捕捉通用的異常是不是一個好的做法,是抑制一些所以檢查你的日誌爲什麼你的代碼進入異常處理程序,在那裏解僱

+0

謝謝@nandeesh。但現在我正在主線程異常獲得網絡。老實說,我並不完全瞭解在android中使用線程的知識。 –

+2

由於網絡操作可能需要很長時間,因此您需要在單獨的線程上運行它們以避免阻止UI - 導致出現「應用程序無響應」錯誤。你也可以使用'AsyncTask' – Karl