Я пытаюсь создать Spinner в Android версии 3.2 из API Data. После написания всех кодов я получаю Fatal Exception. Я также создал TOAST, чтобы показать всплывающие данные Api, но всплывающее окно не отображается, Spinner получает нулевое значение.
Это мои данные API
[
{
"oid": "PCATxxx008",
"pcat_text": "008",
"pcat_name": "MDSP Project (Cyclone Center)",
"pcat_actv": "1"
},
{
"oid": "PCATxxx001",
"pcat_text": "001",
"pcat_name": "Plastic",
"pcat_actv": "1"
},
{
"oid": "PCATxxx002",
"pcat_text": "002",
"pcat_name": "PVC",
"pcat_actv": "1"
},
{
"oid": "PCATxxx003",
"pcat_text": "003",
"pcat_name": "Household",
"pcat_actv": "0"
},
{
"oid": "PCATxxx004",
"pcat_text": "004",
"pcat_name": "Furniture",
"pcat_actv": "0"
},
{
"oid": "PCATxxx005",
"pcat_text": "005",
"pcat_name": "LGED",
"pcat_actv": "1"
},
{
"oid": "PCATxxx006",
"pcat_text": "006",
"pcat_name": "Export",
"pcat_actv": "1"
},
{
"oid": "PCATxxx007",
"pcat_text": "007",
"pcat_name": "Tender",
"pcat_actv": "1"
}
]
Это интерфейс Java
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface api {
String BASE_URL ="http://192.168.1.95:55069/api/";
@GET("Category")
Call<List<Category>> getCategory();
}
Это категория класса
public class Category {
private String oid;
private String pcat_text;
private String pcat_name;
private String pcat_actv;
public Category(String oid, String pcat_text, String pcat_name, String pcat_actv) {
this.oid = oid;
this.pcat_text = pcat_text;
this.pcat_name = pcat_name;
this.pcat_actv = pcat_actv;
}
public String getOid() {
return oid;
}
public String getPcat_text() {
return pcat_text;
}
public String getPcat_name() {
return pcat_name;
}
public String getPcat_actv() {
return pcat_actv;
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLaout;
ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLaout = findViewById(R.id.drawerId);
NavigationView navigationView = findViewById(R.id.navigationId);
navigationView.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(this,drawerLaout,R.string.nav_open,R.string.nav_close);
drawerLaout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
//creating the api interface
api api = retrofit.create(api.class);
//now making the call object
//Here we are using the api method that we created inside the api interface
Call<List<Category>> call = api.getCategory();
//then finallly we are making the call using enqueue()
//it takes callback interface as an argument
//and callback is having two methods onRespnose() and onFailure
//if the request is successfull we will get the correct response and onResponse will be executed
//if there is some error we will get inside the onFailure() method
call.enqueue(new Callback<List<Category>>() {
@Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
List<Category> Category = response.body();
}
@Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG+5000).show();
}
});
}
CollectionActivity где мой Spinner должен показывать данные
public class CollectionActivity extends AppCompatActivity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
DatePicker picker;
TextView dateText;
EditText dateView;
DatePickerDialog.OnDateSetListener setListener;
private static final String CHANNEL_ID = "Notification";
private static final String CHANNEL_NAME = "Test Notification";
private static final String CHANNEL_DESC = "Test Notification Desc";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
addItemsOnSpinner2();
addListenerOnButton();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
dateText = findViewById(R.id.dateText);
dateView = findViewById(R.id.dateView);
Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
dateView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
DatePickerDialog datePickerDialog = new DatePickerDialog(
CollectionActivity.this,android.R.style.Theme_Holo_Light_Dialog_MinWidth
,setListener,year,month,day);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
setListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String date = day+"/"+month+"/"+year;
dateView.setText(date);
}
};
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
//List<String> list = new ArrayList<String>();
//list.add("LGED");
//list.add("PVC");
//list.add("Plastic");
Retrofit retrofit =new Retrofit.Builder()
.baseUrl(api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
api api =retrofit.create(api.class);
Call<List<Category>> call = api.getCategory();
call.enqueue(new Callback<List<Category>>() {
@Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
List<Category> CategoryList = response.body();
String[] Categorys = new String[CategoryList.size()];
for(int i=0; i< CategoryList.size(); i++){
Categorys[i]= CategoryList.get(i).getPcat_name();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(CollectionActivity.this, android.R.layout.simple_spinner_item, Categorys);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner2.setAdapter(spinnerArrayAdapter);
}
/*ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Categorys);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);*/
}
@Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
dateView =(EditText)findViewById(R.id.dateView);
//picker= (DatePicker)findViewById(R.id.date);
btnSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(CollectionActivity.this,
"You have selected : " +
"\nLocation : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nCategory : "+ String.valueOf(spinner2.getSelectedItem()) +
//"\nSelected Date: "+ picker.getDayOfMonth()+"/"+ (picker.getMonth() + 1)+"/"+picker.getYear(),
"\nDate : " + dateView.getText().toString(),
Toast.LENGTH_LONG).show();
addNotifications();
}
});
}
private void addNotifications() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
dateView =(EditText)findViewById(R.id.dateView);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.ic_sms_black_24dp)
.setContentTitle("New Collection Added")
.setContentText(
"You have selected : " +
"\nLocation : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nCategory : "+ String.valueOf(spinner2.getSelectedItem()) +
"\nDate : " + dateView.getText().toString()
)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(this);
mNotificationMgr.notify(1,builder.build());
}
}
Error
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.TEST, PID: 23249
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.example.talukdergroup.CollectionActivity$3.onResponse(CollectionActivity.java:114)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Я дал все, что закодировал. Когда я вхожу, мое приложение CollectionActivity выходит из строя. Мне интересно, когда я сделал глупую ошибку.