“我正在制作一个新闻应用程序。我想在此应用程序中显示设置活动。”
“这是我的代码”
“ MainActivity.java文件”
public static final String API_KEY="95fa3f89b83f4105a70d552bc7bb7fca";
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<Article>articles = new ArrayList<>();
private Adapter adapter;
private String TAG = MainActivity.class.getSimpleName();
private TextView topHeadlines;
private SwipeRefreshLayout swipeRefreshLayout;
private RelativeLayout errorLayout;
private ImageView errorImage;
private TextView errorTitle,errorMessage;
private Button btnRetry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
topHeadlines = findViewById(R.id.top_headlines);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(false);
onLoadingSwipeRefresh("");
errorLayout = findViewById(R.id.errorLayout);
errorImage = findViewById(R.id.errorImage);
errorTitle = findViewById(R.id.errorTitle);
errorMessage = findViewById(R.id.errorsubTitle);
btnRetry = findViewById(R.id.btnRetry);
}
public void LoadJson(final String keyword){
errorLayout.setVisibility(View.GONE);
topHeadlines.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(true);
ApiInterface apiInterface = ApiClient.getAppClient().create(ApiInterface.class);
String country = Utils.getCountry();
String language = Utils.getLanguage();
Call<News>call;
if (keyword.length() > 0){
call = apiInterface.getNewsSearch(keyword,language,"publishedAt",API_KEY);
} else {
call = apiInterface.getNews(country,API_KEY);
}
call = apiInterface.getNews(country,API_KEY);
call.enqueue(new Callback<News>() {
@Override
public void onResponse(Call<News> call, Response<News> response) {
if (response.isSuccessful() && response.body().getArticle()!=null){
if (!articles.isEmpty()){
articles.clear();
}
articles = response.body().getArticle();
adapter = new Adapter(articles,MainActivity.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
initListener();
topHeadlines.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
} else {
topHeadlines.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
String errorCode;
switch (response.code()){
case 404:
errorCode = "404 not Found";
break;
case 500:
errorCode = "500 server broken";
break;
default:
errorCode = "unknown error";
break;
}
showErrorMessage(R.drawable.no_result,
"No_Result",
"Please Try Again\n" +
errorCode );
}
}
@Override
public void onFailure(Call<News> call, Throwable t) {
topHeadlines.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
showErrorMessage(R.drawable.no_result,
"Oops..",
"Network Failure, Pleasw Try Again\n" +
t.toString() );
}
});
}
private void initListener(){
adapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
@Override
public void OnItemClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.img);
Intent intent = new Intent(MainActivity.this,NewsDetailActivity.class);
Article article = articles.get(position);
intent.putExtra("url",article.getUrl());
intent.putExtra("title",article.getTitle());
intent.putExtra("img",article.getUrltoImage());
intent.putExtra("date",article.getPublishAt());
intent.putExtra("source",article.getSource().getName());
intent.putExtra("author",article.getAuthor());
Pair<View,String> pair = Pair.create((View)imageView, ViewCompat.getTransitionName(imageView));
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(
MainActivity.this,
pair
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
startActivity(intent,optionsCompat.toBundle());
} else {
startActivity(intent);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main,menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setQueryHint("Search Latest News....");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if (query.length() >2){
onLoadingSwipeRefresh(query);
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
LoadJson(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false,false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id== R.id.action_settings){
Intent settingIntent = new Intent(this,SettingsActivity.class);
startActivity(settingIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRefresh() {
LoadJson("");
}
private void onLoadingSwipeRefresh(final String keyword){
swipeRefreshLayout.post(
new Runnable() {
@Override
public void run() {
LoadJson(keyword);
}
}
);
}
private void showErrorMessage(int imageView,String title, String message){
if (errorLayout.getVisibility()== View.GONE){
errorLayout.setVisibility(View.VISIBLE);
}
errorImage.setImageResource(imageView);
errorTitle.setText(title);
errorMessage.setText(message);
btnRetry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onLoadingSwipeRefresh("");
}
});
}
}
“ SettingActivity.java文件”
private Toolbar toolbar_set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
toolbar_set = findViewById(R.id.toolbar_Setting);
// setSupportActionBar(toolbar_set);
//
// getSupportActionBar().setTitle("Settings");
if (findViewById(R.id.fragment_container) != null )
{
if (savedInstanceState != null)
return;
getFragmentManager().beginTransaction().add(R.id.fragment_container,new SettingFragment()).commit();
}
}
}
“ SettingFragment.java文件”
{
@Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
“我的Preference.xml文件”
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/setting_menu_item">
<CheckBoxPreference
android:key="News_alert"
android:title="Alert"
android:defaultValue="true"/>
<ListPreference
android:key="@string/setting_country"
android:title="@string/setting_country"
android:entries="@string/setting_order_by_othercountry"
android:entryValues="@string/setting_order_by_country"/>
</PreferenceScreen>
“这是我的String.xml文件”
<!-- Setting Activity -->
<string name="setting_menu_item">Settings</string>
<string name="setting_title">News Settings</string>
<string name="setting_country">Choose Country</string>
<string name="setting_order_by_country_name" translatable="false">Choose By</string>
<string name="setting_order_by_con">Chose Country</string>
<string name="setting_order_by_country">US</string>
<string name="setting_order_by_othercountry">England</string>
“我已经放置了这些代码,但是当编译运行时,以及当我单击“设置”菜单项应用程序时立即崩溃。”
“我遇到了以下错误”
java.lang.reflect.InvocationTargetException 在java.lang.reflect.Constructor.newInstance0(本机方法)
android.content.res.Resources $ NotFoundException:文本数组资源 ID#0x7f0f004a