2011-08-03 3 views
2

На самом деле у меня есть два класса java, из которых один из классов активности теперь из этого класса активности. Я хочу вызвать функции второго класса, который не является классом деятельности. Все работы отлично, но когда я использую SharedPreferences внутри этой функции, он показывает мне ошибку «Невозможно запустить Activity ComponentInfo java.lang.NullPointerException» .. код для двух java-файлов - это..пожалуйста, помогите ..Невозможно начать работу ComponentInfo java.lang.NullPointerException

код для первого Java файл:

public class SplashScreen extends Activity 
{ 
    public void onCreate(Bundle savedInstanceState) 
    { 
      super.onCreate(savedInstanceState); 

      setContentView(R.layout.splash_screen); 


      CycleManager.getSingletonObject().test();//call functions of another class 

    } 
} 

код для второго файла Java:

public class CycleManager 
{  

    private static CycleManager cycleMangrObject;  

    private CycleManager() {    
      onInitialization(); 

      //Compute averages using data loaded from register 
      ComputeAverages(); 
    } 

    public static synchronized CycleManager getSingletonObject() {   
      if (cycleMangrObject == null) { 
      cycleMangrObject = new CycleManager(); 
      } 

      return cycleMangrObject; 
    } 

    public Object clone() throws CloneNotSupportedException {   
      throw new CloneNotSupportedException(); 

    } 

    public void test() 
    { 
     SharedPreferences preferences1 =getSharedPreferences("myPreferences", 0); 
    } 


public void setAlertOnDevice(){     
       //Delete data 
       Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events"); 
       int id = 1; // calendar entry ID 
       ContentResolver cr = getContentResolver(); 
       EVENTS_URI= ContentUris.withAppendedId(EVENTS_URI, id); 
       cr.delete(EVENTS_URI, "calendar_id=1", null); 
       Resources res=getResources(); 

       //set Alerts in device calendar 
       Date dtStartDate = CycleManager.getSingletonObject().getStartDate(); 

       boolean bDeleteAndReturn = false; 

       Calendar cal = Calendar.getInstance(); 


       if (dtStartDate.getTime() == CycleManager.getSingletonObject().getDefaultDate().getTime()) 
       { 
         bDeleteAndReturn = true; 
         dtStartDate = cal.getTime(); 
       } 

       getOffsetsForCycleStages(CycleManager.getSingletonObject().iAvgCycleTime); 

       if(bDeleteAndReturn==false) 
       { 
        if (CycleManager.getSingletonObject().bNextCycleAlert && iStart>0) 
        { 
         cal.setTime(dtStartDate); 
         cal.add(Calendar.DATE, iStart);     
         // ContentResolver cr = getContentResolver(); 
         String str=res.getString(R.string.alert_start); 
         String strDescription=res.getString(R.string.alert_start_msg); 
         ContentValues values = new ContentValues(); 
         values.put("calendar_id", 1); 
         values.put("title", str); 
         values.put("description", strDescription); 
         values.put("dtstart", cal.getTimeInMillis()); 
         values.put("dtend", cal.getTimeInMillis()); 
         cr.insert(EVENTS_URI, values); 
        } 
        if (CycleManager.getSingletonObject().bSafeAlert) 
        { 
         if (iSafe1>0) 
         { 
          cal.setTime(dtStartDate); 
          cal.add(Calendar.DATE, iSafe1);      
          // ContentResolver cr = getContentResolver(); 
          String str=res.getString(R.string.alert_safe); 
          String strDescription=res.getString(R.string.alert_safe_msg) + " " + new Integer(iUnsafe1-iSafe1-1); 
          ContentValues values = new ContentValues(); 
          values.put("calendar_id", 1); 
          values.put("title", str); 
          values.put("description", strDescription); 
          values.put("dtstart", cal.getTimeInMillis()); 
          values.put("dtend", cal.getTimeInMillis()); 
          cr.insert(EVENTS_URI, values); 
         } 
         if (iSafe2>0) 
         { 
          cal.setTime(dtStartDate); 
          cal.add(Calendar.DATE, iSafe2);       
          // ContentResolver cr = getContentResolver(); 
          String str=res.getString(R.string.alert_safe); 
          String strDescription=res.getString(R.string.alert_safe_msg) + " " + new Integer(CycleManager.getSingletonObject().iAvgCycleTime-iSafe2-1); 
          ContentValues values = new ContentValues(); 
          values.put("calendar_id", 1); 
          values.put("title", str); 
          values.put("description", strDescription); 
          values.put("dtstart", cal.getTimeInMillis()); 
          values.put("dtend", cal.getTimeInMillis()); 
          cr.insert(EVENTS_URI, values);  
         } 
        } 
        if (CycleManager.getSingletonObject().bUnsafeAlert) 
        { 
         if (iUnsafe1>0) 
         { 
          cal.setTime(dtStartDate); 
          cal.add(Calendar.DATE, iUnsafe1);       
          // ContentResolver cr = getContentResolver(); 
          String str=res.getString(R.string.alert_unsafe); 
          String strDescription=res.getString(R.string.alert_unsafe_msg) + " " + new Integer(iFertile-iUnsafe1-1); 
          ContentValues values = new ContentValues(); 
          values.put("calendar_id", 1); 
          values.put("title", str); 
          values.put("description", strDescription); 
          values.put("dtstart", cal.getTimeInMillis()); 
          values.put("dtend", cal.getTimeInMillis()); 
          cr.insert(EVENTS_URI, values); 
         } 
         if (iUnsafe2>0) 
         { 
          cal.setTime(dtStartDate); 
          cal.add(Calendar.DATE, iUnsafe2); 
          // ContentResolver cr = getContentResolver(); 
          String str=res.getString(R.string.alert_unsafe); 
          String strDescription=res.getString(R.string.alert_unsafe_msg) + " " + new Integer(iSafe2-iUnsafe2-1); 
          ContentValues values = new ContentValues(); 
          values.put("calendar_id", 1); 
          values.put("title", str); 
          values.put("description", strDescription); 
          values.put("dtstart", cal.getTimeInMillis()); 
          values.put("dtend", cal.getTimeInMillis()); 
          cr.insert(EVENTS_URI, values); 
         } 
        } 
        if (CycleManager.getSingletonObject().bFertileAlert && iFertile>0) 
        { 
         cal.setTime(dtStartDate); 
         cal.add(Calendar.DATE, iFertile); 
         // ContentResolver cr = getContentResolver(); 
         String str=res.getString(R.string.alert_fertile); 
         String strDescription=res.getString(R.string.alert_fertile_msg) + " " + new Integer(iUnsafe2-iFertile-1); 
         ContentValues values = new ContentValues(); 
         values.put("calendar_id", 1); 
         values.put("title", str); 
         values.put("description", strDescription); 
         values.put("dtstart", cal.getTimeInMillis()); 
         values.put("dtend", cal.getTimeInMillis()); 
         cr.insert(EVENTS_URI, values); 
        } 
        if (CycleManager.getSingletonObject().bPMSAlert) 
        { 
         cal.setTime(dtStartDate); 
         cal.add(Calendar.DATE, iStart-7);      
         // ContentResolver cr = getContentResolver(); 
         String str=res.getString(R.string.alert_pms); 
         String strDescription=res.getString(R.string.alert_pms_msg); 
         ContentValues values = new ContentValues(); 
         values.put("calendar_id", 1); 
         values.put("title", str); 
         values.put("description", strDescription); 
         values.put("dtstart", cal.getTimeInMillis()); 
         values.put("dtend", cal.getTimeInMillis()); 
         cr.insert(EVENTS_URI, values); 
        } 
       } 
    } 

    private String getCalendarUriBase(Activity act){    
       String calendarUriBase = null; 
       Uri calendars = Uri.parse("content://calendar/calendars"); 
       Cursor managedCursor = null; 

       try 
       { 
        managedCursor = act.managedQuery(calendars, null, null, null, null); 
       } 
       catch (Exception e) {} 

       if (managedCursor != null) 
       { 
        calendarUriBase = "content://calendar/"; 
       }    
       else 
       { 
        calendars = Uri.parse("content://com.android.calendar/calendars"); 
        try 
        { 
         managedCursor = act.managedQuery(calendars, null, null, null, null); 
        } 
        catch (Exception e){} 

        if (managedCursor != null) 
        { 
         calendarUriBase = "content://com.android.calendar/"; 
        } 
       } 
       return calendarUriBase; 
    } 
+0

Не могли бы вы опубликовать всю трассировку стека? –

+0

см. Обновленный ответ .... – ngesh

+0

Я не вижу ваш код .. – ngesh

ответ

2

Его не представляется возможным, потому что другой класс does't знаю, что есть нечто, называемое SharedPreference .. так

public void test(Context c) 
    { 
     SharedPreferences preferences1 =c.getSharedPreferences("myPreferences", 0); 
    } 

и при вызове

CycleManager.getSingletonObject().test(this);//call functions of another class 

и снова

c.getContentResolver().delete(EVENTS_URI, null, null); 
+0

yeh его работающий сейчас .. еще одна подобная ошибка возникает, когда я использую Uri EVENTS_URI = Uri.parse (getCalendarUriBase (это) + «события»); \t \t \t \t getContentResolver(). Delete (EVENTS_URI, null, null); внутри этой функции так, как это можно решить. – AndroidDev

+0

где вы это делаете. – ngesh

+0

внутри тестовой функции на самом деле всякий раз, когда я использовал sharepreference и uri events. эта ошибка возникает. Теперь общие настройки решены, так как я могу решить эту следующую ошибку – AndroidDev

1
CycleManager.getSingletonObject().test(this); 

public void test(Context c) 
    { 
    SharedPreferences prefs; 
prefs = PreferenceManager.getDefaultSharedPreferences(c); 
} 
0

N o вы не можете использовать функции Activity или Android в обычном простом классе java. Так как вы можете использовать только библиотеку Java в том, что простой Java класс

Одно из возможных решений:

Создание общедоступного статический SharedPreferences объект в деятельности и создать объект SplashScreen вроде этого:

public static SharedPreferences pref = null; 
public static SplashScreen sp; 

В onCreate из заставки сделать это

sp = this; 

В вашем методе класса Java это сделать

SplashScreen.pref = SplashScreen.sp.getSharedPreferences("my pref", 0); 
Смежные вопросы