2014-01-29 55 views
0

我目前正在开发一个android应用程序,我遇到了我的注销按钮的麻烦。每当我在运行时按下它,应用程序就会停止。此外,运行我的应用程序时显示ErrorsDashboard屏幕,而我想要显示的是登录屏幕。 这是一个很长的帖子,所以请耐心等待。 这里是我的代码:NullPointerException和不需要的屏幕加载

对于LoginActivity

package com.example.sabre7; 

import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

import com.example.sabre7.library.DatabaseHandler; 
import com.example.sabre7.library.UserFunctions; 

public class LoginActivity extends Activity { 
    Button btnLogin; 
    //Button btnLinkToRegister; 
    EditText inputEmail; 
    EditText inputPassword; 
    TextView loginErrorMsg; 

    // JSON Response node names 
    private static String KEY_SUCCESS = "success"; 
    private static String KEY_UID = "uid"; 
    private static String KEY_NAME = "name"; 
    private static String KEY_EMAIL = "email"; 
    private static String KEY_CREATED_AT = "created_at"; 

    private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> { 

     protected JSONObject doInBackground(String... params) { 
       UserFunctions userFunction = new UserFunctions(); 
       if (params.length != 2) 
         return null; 
       JSONObject json = userFunction.loginUser(params[0], params[1]); 
       return json; 
     } 

     protected void onPostExecute(JSONObject json) { 
       try { 
      if (json != null && json.getString(KEY_SUCCESS) != null) { 
       loginErrorMsg.setText(""); 
       String res = json.getString(KEY_SUCCESS); 
       if(Integer.parseInt(res) == 1){ 
        // user successfully logged in 
        // Store user details in SQLite Database 
        DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
        JSONObject json_user = json.getJSONObject("user"); 

        // Clear all previous data in database 
        UserFunctions userFunction = new UserFunctions(); 
        userFunction.logoutUser(getApplicationContext()); 
        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));       

        // Launch Main Screen 
        Intent main = new Intent(getApplicationContext(), MainActivity.class); 

        // Close all views before launching Dashboard 
        main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(main); 

        // Close Login Screen 
        finish(); 
       }else{ 
        // Error in login 
        loginErrorMsg.setText("Incorrect username/password"); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     } 
} 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.login); 

     // Importing all assets like buttons, text fields 
     inputEmail = (EditText) findViewById(R.id.loginEmail); 
     inputPassword = (EditText) findViewById(R.id.loginPassword); 
     btnLogin = (Button) findViewById(R.id.btnLogin); 
     //btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); 
     loginErrorMsg = (TextView) findViewById(R.id.login_error); 

     // Login button Click Event 
     btnLogin.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       String email = inputEmail.getText().toString(); 
       String password = inputPassword.getText().toString();     
       new MyAsyncTask().execute(email, password); 
      } 

     }); 
    } 
} 

对于在MainActivity

package com.example.sabre7; 

import com.example.sabre7.library.UserFunctions; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 

public class MainActivity extends Activity{ 
    UserFunctions userFunctions; 
    Button Errorsbtn; 
    Button Serversbtn; 
    Button btnLogout; 

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

     // Check login status in database 
     userFunctions = new UserFunctions(); 
     if(userFunctions.isUserLoggedIn(getApplicationContext())){ 
     // user already logged in show databoard 
      setContentView(R.layout.main); 
      btnLogout = (Button) findViewById(R.id.btnLogout); 

      btnLogout.setOnClickListener(new View.OnClickListener() { 

       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        userFunctions.logoutUser(getApplicationContext()); 
        Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
        login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(login); 
        // Closing dashboard screen 
        finish(); 
       } 
      }); 

      Errorsbtn.setOnClickListener(new View.OnClickListener() { 

       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        Intent Errors = new Intent(getApplicationContext(), ErrorsDashboardActivity.class); 
        startActivity(Errors); 
        // Closing dashboard screen 
        finish(); 
       } 
      }); 

     }else{ 
      // user is not logged in show login screen 
      Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
      login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(login); 
      // Closing dashboard screen 
      finish(); 
     } 

    } 

} 

对于ErrorsDashboardActivity

package com.example.sabre7; 

import org.achartengine.ChartFactory; 
import org.achartengine.GraphicalView; 
import org.achartengine.chart.BarChart.Type; 
import org.achartengine.chart.PointStyle; 
import org.achartengine.model.CategorySeries; 
import org.achartengine.model.SeriesSelection; 
import org.achartengine.model.XYMultipleSeriesDataset; 
import org.achartengine.model.XYSeries; 
import org.achartengine.renderer.XYMultipleSeriesRenderer; 
import org.achartengine.renderer.XYSeriesRenderer; 

import android.app.Activity; 
import android.content.Intent; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.Toast; 

import com.example.sabre7.library.UserFunctions; 

public class ErrorsDashboardActivity extends Activity { 
    UserFunctions userFunctions; 
    Button btnLogout; 

    // First Create a Graphical View object called mChart. 
    private GraphicalView mChart; 
    private String[] mErrors = new String[] {"E0001", "E0002" , "E0003", "E0004", "E0005"}; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.dashboard); 
     btnLogout = (Button) findViewById(R.id.btnLogout); 

     btnLogout.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       userFunctions.logoutUser(getApplicationContext()); //this is line 43 
       Intent login = new Intent(getApplicationContext(), LoginActivity.class); 
       login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(login); 
       // Closing dashboard screen 
       finish(); 
      } 
     }); 
     LineChart(); 
     BarChart(); 
    } 

    //LINE CHART 
    private void LineChart() 
    { 
    // Define the number of elements you want in the chart. 
    int z[]={0,1,2,3,4}; 
    int x[]={10,18,32,21,48}; 


    // Create XY Series for X Series. 
    XYSeries xSeries=new XYSeries("X Series"); 

    // Adding data to the X Series. 
    for(int i = 0; i < z.length; i++) 
    { 
     xSeries.add(z[i], x[i]); 

    } 

    // Create a Dataset to hold the XSeries. 
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); 

    // Add X series to the Dataset. 
    dataset.addSeries(xSeries); 

    // Create XYSeriesRenderer to customize XSeries 
    XYSeriesRenderer Xrenderer=new XYSeriesRenderer(); 
    Xrenderer.setColor(Color.GREEN); 
    Xrenderer.setPointStyle(PointStyle.SQUARE); 
    Xrenderer.setDisplayChartValues(true); 
    Xrenderer.setLineWidth(2); 
    Xrenderer.setFillPoints(true); 

    // Create XYMultipleSeriesRenderer to customize the whole chart 
    XYMultipleSeriesRenderer mRenderer=new XYMultipleSeriesRenderer(); 
    mRenderer.setChartTitle("Top 5 Errors"); 
    mRenderer.setXTitle("Errors"); 
    mRenderer.setYTitle("Instances"); 
    mRenderer.setLabelsTextSize(16); 
    mRenderer.setLegendTextSize(20); 
    mRenderer.setShowGrid(true); 
    mRenderer.setExternalZoomEnabled(true); 
    mRenderer.setYLabelsPadding(2); 
    mRenderer.setAxesColor(Color.GREEN); 
    //mRenderer.setChartValuesTextSize(15); 
    mRenderer.setZoomButtonsVisible(true); 
    mRenderer.setBackgroundColor(Color.WHITE); 
    mRenderer.setXLabels(0); 
    mRenderer.setShowGrid(true); 
    mRenderer.setClickEnabled(true); 
    for(int i=0;i<z.length;i++) 
    { 
     mRenderer.addXTextLabel(i, mErrors[i]); 
    } 

    // Adding the XSeriesRenderer to the MultipleRenderer. 
    mRenderer.addSeriesRenderer(Xrenderer);  
    LinearLayout chart_container=(LinearLayout)findViewById(R.id.Chart_layout); 

    // Creating an intent to plot line chart using dataset and multipleRenderer 
    mChart=(GraphicalView)ChartFactory.getLineChartView(getBaseContext(), dataset, mRenderer); 

    // Adding click event to the Line Chart. 
    mChart.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View arg0) { 
    // TODO Auto-generated method stub 

    SeriesSelection series_selection=mChart.getCurrentSeriesAndPoint(); 

    if(series_selection!=null) 
    { 
    int series_index=series_selection.getSeriesIndex(); 

    String select_series="X Series"; 
    if(series_index==0) 
    { 
     select_series="X Series"; 
    }else 
    { 
     select_series="Y Series"; 
    } 

    String servers=mErrors[(int)series_selection.getXValue()]; 
    int amount=(int)series_selection.getValue(); 
    Toast.makeText(getBaseContext(), select_series + "in" + servers + ":" + amount, Toast.LENGTH_LONG).show(); 
    } 
    } 
    }); 

    // Add the graphical view mChart object into the Linear layout. 
    chart_container.addView(mChart); 
    } 


    //BAR CHART 
    private void BarChart(){ 

     //Defining the number of elements in chart 
     int z[]={0,5,10,15,20}; 
     int x[]={14,5,10,20,16}; 

     CategorySeries series = new CategorySeries("Error Bar Graph"); 
     for (int i = 0; i < x.length; i++){ 
      series.add("Bar " + (i+1), x[i]); 

     } 

     XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); 
     dataset.addSeries(series.toXYSeries()); 

     // Create XYMultipleSeriesRenderer to customize the whole chart 
     XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); 
     mRenderer.setBackgroundColor(Color.WHITE); 
     mRenderer.setBarSpacing(1); 
     mRenderer.setChartTitle("Top 5 Errors"); 
     mRenderer.setXTitle("Errors"); 
     mRenderer.setYTitle("Instances"); 
     mRenderer.setLabelsTextSize(16); 
     mRenderer.setLegendTextSize(20); 
     mRenderer.setExternalZoomEnabled(true); 
     mRenderer.setYLabelsPadding(2); 
     mRenderer.setShowGrid(true); 
     mRenderer.setClickEnabled(true); 
     mRenderer.setAxesColor(Color.GREEN); 

     for(int i=0;i<z.length;i++) 
     { 
      mRenderer.addXTextLabel(i, mErrors[i]); 
     } 

     // Create XYSeriesRenderer to customize XSeries 
     XYSeriesRenderer renderer = new XYSeriesRenderer(); 
     renderer.setShowLegendItem(true); 
     renderer.setColor(Color.GREEN);   

     // Adding the XSeriesRenderer to the MultipleRenderer. 
     mRenderer.addSeriesRenderer(renderer); 
     LinearLayout Barchart_container = (LinearLayout)findViewById(R.id.BarChart_layout); 

     // Creating an intent to plot bar chart using dataset and multipleRenderer 
     mChart=(GraphicalView)ChartFactory.getBarChartView(getBaseContext(), dataset, mRenderer, Type.DEFAULT); 

     // Add the graphical view mChart object into the Linear layout. 
     Barchart_container.addView(mChart); 

     // Adding click event to the Bar Chart. 
     mChart.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
     // TODO Auto-generated method stub 

     SeriesSelection series_selection=mChart.getCurrentSeriesAndPoint(); 

     if(series_selection!=null) 
     { 
     int series_index=series_selection.getSeriesIndex(); 

     String select_series="X Series"; 
     if(series_index==0) 
     { 
      select_series="X Series"; 
     }else 
     { 
      select_series="Y Series"; 
     } 

     String servers=mErrors[(int)series_selection.getXValue()]; 
     int amount=(int)series_selection.getValue(); 
     Toast.makeText(getBaseContext(), select_series + "in" + servers + ":" + amount, Toast.LENGTH_LONG).show(); 
     } 
     } 
     }); 
    } 
} 

对于UserFunctions活动

package com.example.sabre7.library; 

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONObject; 

import android.content.Context; 

public class UserFunctions { 

    private JSONParser jsonParser; 

    // Testing in localhost using wamp or xampp 
    // use http://10.0.2.2/ to connect to your localhost ie http://localhost/ 
    private static String loginURL = "http://10.0.2.2/Sabre1/"; 

    private static String login_tag = "login"; 

    // constructor 
    public UserFunctions(){ 
     jsonParser = new JSONParser(); 
    } 

    /** 
    * function make Login Request 
    * @param email 
    * @param password 
    * */ 
    public JSONObject loginUser(String email, String password){ 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", login_tag)); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("password", password)); 
     JSONObject json = jsonParser.makeHttpRequest(loginURL, "POST", params); 
     return json; 
    } 

    /** 
    * Function get Login status 
    **/ 
    public boolean isUserLoggedIn(Context context){ 
     DatabaseHandler db = new DatabaseHandler(context); 
     int count = db.getRowCount(); 
     if(count > 0){ 
      // user logged in 
      return true; 
     } 
     return false; 
    } 

    /** 
    * Function to logout user 
    * Reset Database 
    * */ 
    public boolean logoutUser(Context context){ 
     DatabaseHandler db = new DatabaseHandler(context); 
     db.resetTables(); 
     return true; 
    } 
} 

对于数据库处理器活动

package com.example.sabre7.library; 

import java.util.HashMap; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

public class DatabaseHandler extends SQLiteOpenHelper { 


    // All Static variables 
    // Database Version 
    private static final int DATABASE_VERSION = 1; 

    // Database Name 
    private static final String DATABASE_NAME = "android_api"; 

    // Login table name 
    private static final String TABLE_LOGIN = "login"; 

    // Login Table Columns names 
    private static final String KEY_ID = "id"; 
    private static final String KEY_NAME = "name"; 
    private static final String KEY_EMAIL = "email"; 
    private static final String KEY_UID = "uid"; 
    private static final String KEY_CREATED_AT = "created_at"; 

    public DatabaseHandler(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    // Creating Tables 
    @Override 
    public void onCreate(SQLiteDatabase db) { 
     String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "(" 
       + KEY_ID + " INTEGER PRIMARY KEY," 
       + KEY_NAME + " TEXT," 
       + KEY_EMAIL + " TEXT UNIQUE," 
       + KEY_UID + " TEXT," 
       + KEY_CREATED_AT + " TEXT" + ")"; 
     db.execSQL(CREATE_LOGIN_TABLE); 
    } 

    // Upgrading database 
    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     // Drop older table if existed 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN); 

     // Create tables again 
     onCreate(db); 
    } 

    /** 
    * Storing user details in database 
    */ 
    public void addUser(String name, String email, String uid, String created_at) { 
     SQLiteDatabase db = this.getWritableDatabase(); 

     ContentValues values = new ContentValues(); 
     values.put(KEY_NAME, name); // Name 
     values.put(KEY_EMAIL, email); // Email 
     values.put(KEY_UID, uid); // Email 
     values.put(KEY_CREATED_AT, created_at); // Created At 

     // Inserting Row 
     db.insert(TABLE_LOGIN, null, values); 
     db.close(); // Closing database connection 
    } 

    /** 
    * Getting user data from database 
    * */ 
    public HashMap<String, String> getUserDetails(){ 
     HashMap<String,String> user = new HashMap<String,String>(); 
     String selectQuery = "SELECT * FROM " + TABLE_LOGIN; 

     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 
     // Move to first row 
     cursor.moveToFirst(); 
     if(cursor.getCount() > 0){ 
      user.put("name", cursor.getString(1)); 
      user.put("email", cursor.getString(2)); 
      user.put("uid", cursor.getString(3)); 
      user.put("created_at", cursor.getString(4)); 
     } 
     cursor.close(); 
     db.close(); 
     // return user 
     return user; 
    } 

    /** 
    * Getting user login status 
    * return true if rows are there in table 
    * */ 
    public int getRowCount() { 
     String countQuery = "SELECT * FROM " + TABLE_LOGIN; 
     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(countQuery, null); 
     int rowCount = cursor.getCount(); 
     db.close(); 
     cursor.close(); 

     // return row count 
     return rowCount; 
    } 

    /** 
    * Re create database 
    * Delete all tables and create them again 
    * */ 
    public void resetTables(){ 
     SQLiteDatabase db = this.getWritableDatabase(); 
     // Delete All Rows 
     db.delete(TABLE_LOGIN, null, null); 
     db.close(); 
    } 
} 

我dashboard.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="@drawable/adservereport"> 

    <TextView android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="@string/DashboardWelcometxt" 
       android:textSize="20sp" 
       android:gravity="center" 
       android:layout_marginTop="50dip"/> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="170dp" 
     android:id="@+id/Chart_layout" 
     android:orientation="vertical" 
     android:textSize="15sp" 
     android:layout_marginLeft="45dp" 
     android:layout_marginRight="45dp" 
     android:layout_marginTop="20dp" > 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="170dp" 
     android:id="@+id/BarChart_layout" 
     android:orientation="vertical" 
     android:textSize="15sp" 
     android:layout_marginLeft="45dp" 
     android:layout_marginRight="45dp" 
     android:layout_marginTop="0dp" > 
    </LinearLayout> 

    <Button 
     android:id="@+id/btnLogout" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/LogOutbtntxt" 
     android:textSize="20sp" 
     android:layout_marginLeft="40dp" 
     android:layout_marginRight="40dp"/> 

</LinearLayout> 

我logcat的错误:

01-28 20:52:58.729: E/AndroidRuntime(1290): FATAL EXCEPTION: main 
01-28 20:52:58.729: E/AndroidRuntime(1290): Process: com.example.sabre7, PID: 1290 
01-28 20:52:58.729: E/AndroidRuntime(1290): java.lang.NullPointerException 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at com.example.sabre7.ErrorsDashboardActivity$1.onClick(ErrorsDashboardActivity.java:43) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at android.view.View.performClick(View.java:4424) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at android.view.View$PerformClick.run(View.java:18383) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at android.os.Handler.handleCallback(Handler.java:733) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at android.os.Handler.dispatchMessage(Handler.java:95) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at android.os.Looper.loop(Looper.java:137) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at android.app.ActivityThread.main(ActivityThread.java:4998) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at java.lang.reflect.Method.invokeNative(Native Method) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at java.lang.reflect.Method.invoke(Method.java:515) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593) 
01-28 20:52:58.729: E/AndroidRuntime(1290):  at dalvik.system.NativeStart.main(Native Method) 

真的希望你能有所帮助。谢谢!

回答

0

你得到NPE这里

userFunctions.logoutUser(getApplicationContext()); 

,因为你还没有初始化userFunctions。你在这里声明

UserFunctions userFunctions; 

但你需要初始化它(给它一个值),然后试图调用它的函数。

只要错误的Activity显示当你开始你的Activity,我会认为你的manifest.xml作为启动器声明了你的错误Activity。请确保在Login Activity<actviity>标记中,您在Activity上只有IntentFilter只有。喜欢的东西

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

并请工作在发帖时用出发最相关的代码。这是太多的代码。如果我们认为需要,我们总是可以请求更多的代码。

+0

谢谢!我完全忘了更新我的清单文件。至于发布的代码,我有点绝望,真的想给你一个清晰的想法,我正在尝试做什么。我会记得在下一次调低它:) –

0
btnLogout = (Button) findViewById(R.id.btnLogout); 
userFunctions = new UserFunctions(); // need to add this line 
+0

?? ?? dint刷新屏幕,而通过代码和回答工作的 –

+0

!谢谢! :) –