我想在另一个帖子中获取谷歌日历名称后更新微调器对象。当我执行它时,它会崩溃。我不确定是否需要使用不同的方法使其工作,或者是否存在问题。
private void updateGoogleCalendar() {
try {
Thread.sleep(4000);
List<String> list = new ArrayList<String>();
list.add("Sample Calendar");
updatedCalendarNames = list.toArray(new String[0]);
progressBar.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void initializeWidgets() {
final Spinner spinner = (Spinner) layout.findViewById(R.id.googleCalendarSelection);
final Button refreshCalendarBtn = (Button) layout.findViewById(R.id.refreshCalendarBtn);
refreshCalendarBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
progressBar = ProgressDialog.show(getContext(), "", "Loading...");
new Thread(new Runnable() {
@Override
public void run() {
updateGoogleCalendar();
final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
while (updatedCalendarNames == null) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (String calendarName : updatedCalendarNames) {
CharSequence charSequence = calendarName + "";
adapter.add(charSequence);
}
}
}).start();
}
});
}
答案 0 :(得分:1)
你没有说 它崩溃或者如何崩溃,但我想这可能是因为你试图从非UI线程更新UI。请查看AsyncTask
(请参阅here)了解相关信息。
答案 1 :(得分:1)
您需要将您的ui更新代码添加到事件线程中,并且要通知UI /事件线程您需要实现Handler或AsyncTask,例如您可以通过处理程序更新如下:
public void initializeWidgets() {
final Spinner spinner = (Spinner) layout.findViewById(R.id.googleCalendarSelection);
final Button refreshCalendarBtn = (Button) layout.findViewById(R.id.refreshCalendarBtn);
refreshCalendarBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
progressBar = ProgressDialog.show(getContext(), "", "Loading...");
new Thread(new Runnable() {
@Override
public void run() {
updateGoogleCalendar();
final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
while (updatedCalendarNames == null) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (String calendarName : updatedCalendarNames) {
Message msg=handler.obtainMessage();
msg.obj = calendarName + "";
handler.sendMessage(msg);
}
}
}).start();
}
});
}
Handler handler=new Handler()
{
public void handleMessage(Message msg)
{
String str=(String)msg.obj;
adapter.add(charSequence);
}
};