【发布时间】:2014-05-20 05:02:39
【问题描述】:
所以我正在转换我的应用程序,经过大量研究后,我决定将我的活动转换为片段。那是成功的,但现在有点困难的部分来了,实现从我的 Activity 到片段的代码。所以我使用了getView()。和getActivity()。解决问题,一切都很好。如下所示...
public class HomeFragment extends Fragment {
public static HomeFragment newInstance(String title) {
HomeFragment homeFragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
homeFragment.setArguments(bundle);
return homeFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_activity_home, container, false);
// Time function - Displays timeview on Card
final boolean keepRunning = true;
Thread thread = new Thread(){
@Override
public void run(){
while(keepRunning){
// Make the thread wait half a second (if you're only showing time up to seconds, it doesn't need to be updating constantly)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
TextView time = (TextView) getView().findViewById(R.id.time);
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
}
});
}
}
};
thread.start();
// Date function - Displays dateview on Card
final boolean keepRunning1 = true;
Thread thread_two = new Thread(){
@Override
public void run(){
while(keepRunning1){
// Make the thread wait half a second. If you want...
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable(){
@Override
public void run(){
TextView date = (TextView) getView().findViewById(R.id.date);
date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
});
}
}
};
thread_two.start();
return view;
}
}
运行应用程序时,它会显示应用程序大约 2 秒,然后强制关闭,所以我检查了日志是否有任何错误。而这出现了--
05-20 16:54:17.213: E/AndroidRuntime(26473): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
05-20 16:54:17.213: E/AndroidRuntime(26473): at com.activelauncher.fragments.HomeFragment$1$1.run(HomeFragment.java:54)
我对 Fragments 还很陌生,我有更多使用活动的经验,所以我不知道这里有什么问题。所以我检查了第 54 行,就是这一行 --
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
但是我没有看到任何问题或错误?有什么我想念的吗? 感谢您阅读本文。
【问题讨论】:
-
你正在使用线程来创建交易?
标签: java android eclipse class android-fragments