简体   繁体   中英

Second Activity call Main Activity Function crashed in Android

this is the code in Second Activity OnCreate

final Button arrayBtn = (Button) findViewById(buttonQtyID[i]);
            arrayBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    ClearQtyBtnColor(); 
                    arrayBtn.getBackground().setColorFilter(0xffff9999, PorterDuff.Mode.MULTIPLY);
                    MainActivity  cls2= new MainActivity();

                    String Price = cls2.CheckUnitPrice("NORMAL"); // ERROR AT HERE
                    TextView view = (TextView) findViewById(R.id.Harga_lblPrice);
                    //view.setText((Double.parseDouble(Price) * Integer.parseInt(arrayBtn.getText().toString()))+"");
                }
             });

this is the coding in Main Activity

public Cursor DB_GetUnitPrice(){
    DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
    myDbHelper = new DataBaseHelper(this);
    try { 
    myDbHelper.createDataBase();  
    } catch (IOException ioe) { 
    throw new Error("Unable to create database"); 
    }  
    try {  
    myDbHelper.openDataBase();         
    }catch(SQLException sqle){  
    throw sqle;  
    }
    SQLiteDatabase db = myDbHelper.getReadableDatabase();

    String Insert_Data="Select Normal_Rate,Discounted_Rate FROM Tbl_Rate WHERE Route_ID="+global.Route_ID+" AND ((From_LocationID="+global.From_LocationID+" AND To_LocationID="+global.To_LocationID+") OR (From_LocationID="+global.To_LocationID+" AND To_LocationID="+global.From_LocationID + "))";
    Cursor c = db.rawQuery(Insert_Data, null);

    //c.close(); // cannot will error
    //db.close(); // cannot will error
    //myDbHelper.close();
    return c;
}

public String CheckUnitPrice(String PriceType){
    if ((global.To_LocationID != 0) && (global.From_LocationID != 0)) {
            Cursor c = DB_GetUnitPrice();
            double Normal_Rate = 0;
            double Discounted_Rate = 0;
            while (c.moveToNext()) {
                Normal_Rate = c.getDouble(c.getColumnIndex("Normal_Rate"));
                Discounted_Rate = c.getDouble(c.getColumnIndex("Discounted_Rate"));
            }
            if (PriceType.equalsIgnoreCase("NORMAL")){
                return String.format("%.2f",(Normal_Rate));
            }else{
                return String.format("%.2f",(Discounted_Rate));
            }
    }else{
        return "0.00";
    }
}

this is my global variable declaration in Class Global

public class Global extends Application {
    String Driver_Code;
    String Driver_Name;
    long Driver_ID;

    long Vehicle_ID;
    String Plat_No;

    long Route_ID;

    int From_LocationID;
    int To_LocationID;
    String From_LocationName;
    String To_LocationName;
    int From_Tag;
    int To_Tag;

}

this is the Log cat Error log

12-02 14:13:48.718: E/AndroidRuntime(10643): FATAL EXCEPTION: main
12-02 14:13:48.718: E/AndroidRuntime(10643): java.lang.NullPointerException
12-02 14:13:48.718: E/AndroidRuntime(10643):    at com.example.abc2.MainActivity.CheckUnitPrice(MainActivity.java:246)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at com.example.abc2.SecondActivity$2.onClick(SecondActivity.java:58)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at android.view.View.performClick(View.java:2485)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at android.view.View$PerformClick.run(View.java:9080)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at android.os.Handler.handleCallback(Handler.java:587)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at android.os.Looper.loop(Looper.java:123)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at android.app.ActivityThread.main(ActivityThread.java:3647)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at java.lang.reflect.Method.invokeNative(Native Method)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at java.lang.reflect.Method.invoke(Method.java:507)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-02 14:13:48.718: E/AndroidRuntime(10643):    at dalvik.system.NativeStart.main(Native Method)

calling CheckUnitPrice on Main activity are working fine, can return the Price from Sqlite, but when calling from another activity, occurs problem. please help

You should make the variables in Global class as public, and get the access to the class from the ApplicationContext.

Global state = ((Global) getApplicationContext());
int value = state.To_LocationID

Also, make an entry in Manifest file under the application tag which will let the system know about your application class.

android:name="Global"

Note: You should make member variable in Global as private and generate getters and setters for these variables. Avoid direct access to variables.

If MainActivity class extends Activity you cannot use this construction:

MainActivity  cls2= new MainActivity();

Create simple class and make static methods inside it.

Try this.. you need to give variable as public static then only you can get that variable

public class Global extends Application {
    public static String Driver_Code;
    public static String Driver_Name;
    public static long Driver_ID;

    public static long Vehicle_ID;
    public static String Plat_No;

    public static long Route_ID;

    public static int From_LocationID;
    public static int To_LocationID;
    public static String From_LocationName;
    public static String To_LocationName;
    public static int From_Tag;
    public static int To_Tag;

}

You can access variable like below..

if ((Global.To_LocationID != 0) && (Global.From_LocationID != 0)) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM