gpt4 book ai didi

android - 在 Android Studio 中从 Api 创建 Spinner

转载 作者:行者123 更新时间:2023-11-29 23:01:11 26 4
gpt4 key购买 nike

我正在尝试从 API 数据在 Android 3.2 版中创建 Spinner。编写所有代码后,我得到了致命异常。我还创建了一个 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 接口(interface)

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;
}
}

主 Activity

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());
}
}

错误

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 应用程序崩溃了。我想知道我在哪里犯了这个愚蠢的错误。

最佳答案

尝试使用您的 CollectionActivity 的以下代码,希望它会起作用。使用前应检查列表的空值。

 import android.app.DatePickerDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
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();

if (CategoryList != null && CategoryList.size() > 0) {
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());
}
}

关于android - 在 Android Studio 中从 Api 创建 Spinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com