2015-04-21 3 views
0

Мы пытаемся прочитать файл JSON с сервера и отобразить его в нашем приложении Android с помощью функции Retrofit GET. Мы основываем наш код на существующем и рабочем приложении для Android, но вместо Activity мы используем Fragment (lib: android.support.v4.app.Fragment). Выполнение этого дает нам следующее сообщение об ошибкеПолучение NullPointerException в OnResume() с использованием Retrofit

Caused by: java.lang.NullPointerException 
     at com.example.myapp2.AgendaSettingModule.onResume(AgendaSettingModule.java:50) 

это наш класс, который вызывает метод ДООСНАСТКЕ

import adapter.QuestionASMAdapter; 
import android.app.Activity; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ListView; 
import android.widget.Toast; 
import application.DemoApplication; 
import model.QuestionASM; 
import retrofit.Callback; 
import retrofit.RetrofitError; 
import retrofit.client.Response; 
import java.util.List; 

public class AgendaSettingModule extends Fragment implements Callback<List<QuestionASM>>{ 

private QuestionASMAdapter questionASMAdapter; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.agendasettings_module, container, false); 


    questionASMAdapter=new QuestionASMAdapter(view.getContext()); 
    ListView listView=(ListView) view.findViewById(R.id.listQuestionASM); 
    View emptyView=view.findViewById(R.id.txtEmptyASM); 
    listView.setAdapter(questionASMAdapter); 
    listView.setEmptyView(emptyView); 

    return view; 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    DemoApplication.getQuestionASMService().getQuestionsASM(this); 
    //This is where the NullPointerException occurs (line 50) 
} 

@Override 
public void success(List<QuestionASM> questionASMs, Response response) { 
    questionASMAdapter.setQuestionsAsm(questionASMs); 
} 

@Override 
public void failure(RetrofitError retrofitError) { 
    Toast.makeText(getView().getContext(), getString(R.string.error), Toast.LENGTH_LONG).show(); 

} 
} 

DemoApplication.java

public class DemoApplication extends Application { 
    private static QuestionASMService questionASMService; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     questionASMService = createQuestionASMService(this); 
    } 

    public static QuestionASMService getQuestionASMService() { 
     return questionASMService; 
    } 

    private QuestionASMService createQuestionASMService(Context context) { 
     final Gson gson = new GsonBuilder() 
       .setDateFormat("yyyy-MM-dd HH:mm:ss") 
       .create(); 

     return new RestAdapter.Builder() 
       .setConverter(new GsonConverter(gson)) 
       .setEndpoint(context.getString(R.string.baseUrl)) 
       .setLogLevel(RestAdapter.LogLevel.FULL) 
       .build() 
       .create(QuestionASMService.class); 
    } 
} 

и наш интерфейс, который имеет дооснащения GET

import retrofit.Callback; 
import retrofit.http.Body; 
import retrofit.http.GET; 

import java.util.List; 
public interface QuestionASMService { 

    @GET("/questions.html") 
    void getQuestionsASM(Callback<List<QuestionASM>> callback); 
} 

и это код, в котором мы основывали наш класс на

public class QuestionsActivity extends Activity implements Callback<List<Question>> { 
    private QuestionAdapter questionAdapter; 

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

    @Override 
    protected void onResume() { 
     super.onResume(); 
     getDemoService().getQuestions(this); 
    } 


    @Override 
    public void success(final List<Question> questions, final Response response) { 
     questionAdapter.setQuestions(questions); 
    } 

    @Override 
    public void failure(final RetrofitError error) { 
     Toast.makeText(this, getString(R.string.tFailure), Toast.LENGTH_LONG).show(); //Foutmelding 
     Log.e(TAG, error.toString()); //Logging 
    } 
} 

ответ

0

Я предлагаю положить это от DemoApplicaiton

questionASMService = createQuestionASMService(this); 

внутри onResume вместо OnCreate

public class DemoApplication extends Application { 
    private static QuestionASMService questionASMService; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     questionASMService = createQuestionASMService(this); 
    } 

Заменить

public class DemoApplication extends Application { 
    private static QuestionASMService questionASMService; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     questionASMService = createQuestionASMService(this); 
    } 
+0

I не совсем понимаю, мы используем getQuestionASMService() из DemoApplication, чтобы вернуть этот объект. – Edward

+0

Я обновил свой ответ, чтобы быть более явным – Vyncent

+0

Это невозможно, поскольку DemoApplication расширяет приложение и нет такого метода для перезаписывания http://developer.android.com/reference/android/app/Application.html – Edward

Смежные вопросы