If I start application in landscape mode it runs fine, but if I
change the mode from landscape or profile it crashes.
can anyone see some obvious errors in my code?
I have tried to set only portrait mode in manifest but no success with that.
code:
public class MainActivity extends Activity implements OnClick {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_timeline, new TimeLineFragment());
transaction.commit();
}
#Override
public void OnClickListener(Status status) {
if(findViewById(R.id.fragment_detailedtweet) != null) {
Bundle bundle = new Bundle();
bundle.putSerializable("StatusData", status);
DetailTweetFragments detailTweetFragment = new DetailTweetFragments();
detailTweetFragment.SetStatus(status);
detailTweetFragment.setArguments(bundle);
FragmentTransaction trancationTableView = getFragmentManager().beginTransaction();
trancationTableView.replace(R.id.fragment_detailedtweet, detailTweetFragment);
trancationTableView.commit();
} else {
Bundle bundle = new Bundle();
bundle.putSerializable("StatusData", status);
DetailTweetFragments detailTweetFragment = new DetailTweetFragments();
detailTweetFragment.SetStatus(status);
detailTweetFragment.setArguments(bundle);
FragmentTransaction trancationTableView = getFragmentManager().beginTransaction();
trancationTableView.replace(R.id.fragment_timeline, detailTweetFragment);
trancationTableView.addToBackStack(null);
trancationTableView.commit();
}
}
#Override
public void OnMakeTweet() {
Intent intent = new Intent(MainActivity.this, TwitterUpdateActivity.class);
startActivity(intent);
}
#Override
public void OnProfile() {
Intent intent = new Intent(MainActivity.this, TwitterProfileActivity.class);
startActivity(intent);
}
}
public class TimeLineAdapter extends ArrayAdapter<Status>{
private Activity activityContext;
public TimeLineAdapter(Context context) {
super(context, R.layout.status_item);
activityContext = (Activity) context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Status status = this.getItem(position);
View view = activityContext.getLayoutInflater().inflate(R.layout.status_item, null);
TextView tweetText = (TextView) view.findViewById(R.id.tweet_from_timeLine);
tweetText.setText(status.getText());
TextView profileName = (TextView) view.findViewById(R.id.profile_name_status);
profileName.setText(status.getUser().getName());
LinearLayout layout = (LinearLayout) view.findViewById(R.id.left_layout);
ImageView imageView = new ImageView(getContext());
layout.addView(imageView);
public class TimeLineFragment extends Fragment {
Button timeLine_button;
Button makeTweet_button;
Button profile_button;
TimeLineAdapter adapter;
OnClick onClickListener;
public ResponseList<twitter4j.Status> statuses;
public interface OnClick {
public void OnClickListener(Status status);
public void OnMakeTweet();
public void OnProfile();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onClickListener = (OnClick) activity;
}catch(ClassCastException e){
e.printStackTrace();
}
}
#Override
public void onDetach() {
super.onDetach();
onClickListener = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_timeline, null);
ListView list = (ListView) view.findViewById(R.id.tweet_list);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapter, View praent, int position,
long id) {
onClickListener.OnClickListener(statuses.get(position));
}
});
makeTweet_button = (Button) view.findViewById(R.id.makeTweet_button);
makeTweet_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onClickListener.OnMakeTweet();
}
});
profile_button = (Button) view.findViewById(R.id.profile_button);
profile_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onClickListener.OnProfile();
}
});
new LoadTmeLine().execute();
return view;
}
private class LoadTmeLine extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Twitter twitter = TwitterLogInActivity.twitter;
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new TimeLineAdapter(getActivity());
for(twitter4j.Status status : statuses) {
adapter.add(status);
}
ListView list = (ListView) getActivity().findViewById(R.id.tweet_list);
list.setAdapter(adapter);
}
}
EXCEPTION:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:104)
.adapters.TimeLineAdapter.<init>(TimeLineAdapter.java:31)
.fragments.TimeLineFragment$LoadTmeLine.onPostExecute(TimeLineFragment.java:132)
.fragments.TimeLineFragment$LoadTmeLine.onPostExecute(TimeLineFragment.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
MANIFEST:
application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="twitter.TwitterLogInActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="twitter.MainActivity"
android:label="#string/app_name" >
</activity>
When the orientation changes, the activity is killed and recreated. You typically get null pointers like this when you are not saving state correctly. As for forcing the app to portrait mode. This should do it.
<activity
android:name=".MyActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" />
If you have different folders for layouts (layout-land for landscape, and layout for normal), then make sure both of them has the same views. Sometimes I happened to add a new view to the normal layout, but forgot to add it too into the landscape layout
Related
I am trying to create a recycle view list of NBA teams and when each team is clicked it will display a recycler view list of the NBA players in that particular team. To do this, I have constructed my main activity, which will launch the "NBA_Adapter" in the OnCreate method as shown below:
package com.example.nba;
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
state state = new state();
private NBA_Adapter adapter;
private RecyclerView recyclerView;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {//originally 'protected'
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
adapter = new NBA_Adapter(getApplicationContext());
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false));
}
}
NBA_Adapter:
package com.example.nba;
public class NBA_Adapter extends RecyclerView.Adapter<NBA_Adapter.NBAViewHolder> implements Filterable {
public static class NBAViewHolder extends RecyclerView.ViewHolder { //constructer for recyclerview adapter
public LinearLayout containerView;
public TextView textView;
NBAViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.nba_row);
textView = view.findViewById(R.id.nba_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TEAMS current = (TEAMS) containerView.getTag();
Intent intent = new Intent(v.getContext(), SecondMain.class);
intent.putExtra("id", current.getId());
v.getContext().startActivity(intent);
}
});
}
}
}
Second Main:
public class SecondMain extends AppCompatActivity implements SearchView.OnQueryTextListener {
private int team_id;
private Player_Adapter rapter;
private RecyclerView mrecyclerView;
private RecyclerView.LayoutManager layoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {//originally 'protected'
Log.v("cs100", "I exist!");
team_id = getIntent().getIntExtra("id",0);
Log.v("cs100", "" + team_id);
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
mrecyclerView = findViewById(R.id.mrecycler_view);
rapter = new Player_Adapter(getApplicationContext());
mrecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
state.setstate(false);
mrecyclerView.setAdapter(rapter);
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nba">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SecondMain">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Now I am able to launch the "SecondMain" class as evident of a Log.v statement printing(Meaning at this point the teams but not the players in the teams are displaying). Since "MainActivity" is almost identical to "SecondMain" I assumed that similar to how "MainActivity" launches "NBA_Adapter" so will "SecondMain" launch "Player_Adapter". Player_Adapter is almost identical to "NBA_Adapter" but it is not launching at all. This is why I suspect that the problem is how I described "SecondMain" in the Android Manifest. I only included the relevant parts for each class. Any tips or links on this issue is appreciated, thanks!
EDIT: Included Player_Adapter class below:
public class Player_Adapter extends RecyclerView.Adapter<Player_Adapter.PlayerViewHolder> implements Filterable {
private int team_id;
public class myclass extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
team_id = getIntent().getIntExtra("id",0);
recyclerView.setAdapter(adapter);
Log.v("Player",""+ team_id); //Not displaying statement which indicates that "Player_Adapter" is not being launched
}
}
public static class PlayerViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView textView;
PlayerViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.Player_List_row);
textView = view.findViewById(R.id.Player_List_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Players current = (Players) containerView.getTag();
Intent intent = new Intent(v.getContext(), Compare_Stats.class);
//we get the "fullName"
intent.putExtra("id", current.getPlayer_id());
v.getContext().startActivity(intent);
}
});
}
}
#NonNull
#Override
public PlayerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.player_list, parent, false);
return new PlayerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PlayerViewHolder holder, int position) {
Players current = PlayersList.get(position);
holder.textView.setText(current.FullName());
holder.containerView.setTag(current);
}
#Override
public int getItemCount() {
return PlayersList.size();
}
}
Inside the class myclass you are definitely setting the adapter , but it looks like you are missing the code that sets the LayoutManager to RecyclerView .
recyclerView.setLayoutManager(new LinearLayoutManager(this/*Context here*/));
Another suggestion is that you should keep activity separately and not nest it inside a adapter.
I tried to change my Launcher Activity in my Manifest file. After changing it, I went reseted my code of again (re-edited so that it was the same as before). So I just copy pasted this code between my activities
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
After reseting my code the app won't open.
I got an error
java.lang.IllegalArgumentException: AppCompat does not support the current theme features, poiting out on my setContentView(R.layout.activity_main);
I got really frustrated by this problem cause I didn't change anything in my code (it is excaclty as it used to be when it was working)
Here is my manifest file code
<manifest package="com.inthessaloniki.cityguide"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:installLocation="auto">
<!-- versionCode, versionName, minSdkVersion, targetSdkVersion properties are set via Gradle script -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- allows the API to access Google web-based services -->
<!-- maps API needs OpenGL ES 2.0 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="false"/>
<!--
You can easily change the main theme. Just modify application.android:theme attribute.
There are 8 main themes you can use:
Theme.CityGuide.Blue
Theme.CityGuide.Brown
Theme.CityGuide.Carrot
Theme.CityGuide.Gray
Theme.CityGuide.Green
Theme.CityGuide.Indigo
Theme.CityGuide.Red
Theme.CityGuide.Yellow
Don't forget to modify also MainActivity's theme.
-->
<application
android:name=".CityGuideApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.CityGuide.Indigo"
tools:replace="android:icon">
<!--
Themes for MainActivity:
Theme.CityGuide.TransparentStatusBar.Blue
Theme.CityGuide.TransparentStatusBar.Brown
Theme.CityGuide.TransparentStatusBar.Carrot
Theme.CityGuide.TransparentStatusBar.Gray
Theme.CityGuide.TransparentStatusBar.Green
Theme.CityGuide.TransparentStatusBar.Indigo
Theme.CityGuide.TransparentStatusBar.Red
Theme.CityGuide.TransparentStatusBar.Yellow
-->
<activity
android:name=".activity.MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.CityGuide.TransparentStatusBar.Indigo"
android:launchMode="standard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.PoiDetailActivity"
android:label="#string/title_poi_detail"
android:launchMode="standard"/>
<activity
android:name=".activity.TourDetailActivity"
android:label="#string/title_tour_detail"
android:launchMode="standard"/>
<activity
android:name=".activity.MapActivity"
android:label="#string/title_map"
android:launchMode="standard"/>
<activity
tools:replace="android:configChanges"
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|uiMode|smallestScreenSize"/>
<activity
android:name=".activity.DescriptionDetailsActivity"
android:label="#string/title_activity_description_details"
android:theme="#style/Theme.CityGuide.TransparentStatusBar.Indigo">
</activity>
<activity
android:name=".activity.MailFormActivity"
android:label="#string/title_tour_detail"
android:theme="#style/Theme.CityGuide.TransparentStatusBar.Indigo">
</activity>
<provider
android:name=".content.PoiSearchRecentSuggestionsProvider"
android:authorities="com.inthessaloniki.cityguide.content.PoiSearchRecentSuggestionsProvider"
android:exported="false"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<meta-data
android:name="com.google.android.gms.analytics.globalConfigResource"
android:resource="#xml/analytics_global_tracker"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/maps_api_key"/>
</application>
Main Activity Code
public class MainActivity extends AppCompatActivity implements DrawerAdapter.CategoryViewHolder.OnItemClickListener, OnSearchListener
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ScrimInsetsFrameLayout mDrawerScrimInsetsFrameLayout;
private DrawerAdapter mDrawerAdapter;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private List<CategoryModel> mCategoryList;
public static Intent newIntent(Context context)
{
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
setupRecyclerView();
setupDrawer(savedInstanceState);
// init analytics tracker
((CityGuideApplication) getApplication()).getTracker();
}
#Override
public void onStart()
{
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// open or close the drawer if home button is pressed
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// action bar menu behaviour
switch(item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfiguration)
{
super.onConfigurationChanged(newConfiguration);
mDrawerToggle.onConfigurationChanged(newConfiguration);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle("");
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/nexa-bold.otf");
final TextView toolbarName = (TextView) findViewById(R.id.toolbar_title);
toolbarName.setText(mTitle);
}
#Override
public void onItemClick(View view, int position, long id, int viewType)
{
// position
int categoryPosition = mDrawerAdapter.getCategoryPosition(position);
selectDrawerItem(categoryPosition);
}
#Override
public void onSearch(String query)
{
Fragment fragment = PoiListFragment.newInstance(query);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(0));
setTitle(getString(R.string.title_search) + ": " + query);
}
private void setupActionBar()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setDisplayUseLogoEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
private void setupRecyclerView()
{
// reference
RecyclerView recyclerView = getRecyclerView();
// set layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// load categories from database
loadCategoryList();
// set adapter
if(recyclerView.getAdapter()==null)
{
// create adapter
mDrawerAdapter = new DrawerAdapter(mCategoryList, this);
}
else
{
// refill adapter
mDrawerAdapter.refill(mCategoryList, this);
}
recyclerView.setAdapter(mDrawerAdapter);
// add decoration
List<Integer> dividerPositions = new ArrayList<>();
dividerPositions.add(3);
RecyclerView.ItemDecoration itemDecoration = new DrawerDividerItemDecoration(
this,
null,
dividerPositions,
getResources().getDimensionPixelSize(R.dimen.global_spacing_xxs));
recyclerView.addItemDecoration(itemDecoration);
}
private void setupDrawer(Bundle savedInstanceState)
{
mTitle = getTitle();
mDrawerTitle = getTitle();
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/nexa-bold.otf");
final TextView toolbarName = (TextView) findViewById(R.id.toolbar_title);
toolbarName.setText(mTitle);
toolbarName.setTypeface(typeface);
// reference
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_layout);
mDrawerScrimInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(R.id.activity_main_drawer);
// set drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerLayout.setStatusBarBackgroundColor(ResourcesHelper.getValueOfAttribute(this, R.attr.colorPrimaryDark));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View view)
{
toolbarName.setText(mTitle);
getSupportActionBar().setTitle("");
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView)
{
toolbarName.setText(mTitle);
getSupportActionBar().setTitle("");
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// show initial fragment
if(savedInstanceState == null)
{
selectDrawerItem(0);
}
}
private void selectDrawerItem(int position)
{
long mCategoryId = mCategoryList.get(position).getId();
Fragment fragment = null;
if(mCategoryId==PoiListFragment.CATEGORY_ID_ALL || mCategoryId==PoiListFragment.CATEGORY_ID_FAVORITES ){
fragment = PoiListFragment.newInstance(mCategoryId);
}else{
fragment = SubCategoryListFragment.newInstance(mCategoryId);
}
FragmentManager fragmentManager = getSupportFragmentManager();
String categoryName = mCategoryList.get(position).getName();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment, categoryName).addToBackStack(categoryName).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(position));
setTitle(categoryName);
mDrawerLayout.closeDrawer(mDrawerScrimInsetsFrameLayout);
}
public void showPOIFragment(long categoryId, String categoryName){
PoiListFragment fragment = PoiListFragment.newInstance(categoryId);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment, categoryName).addToBackStack(categoryName).commitAllowingStateLoss();
if (!TextUtils.isEmpty(categoryName)){
setTitle(categoryName);
}
}
public void showSubCategoryFragment(long categoryId, String categoryName){
SubCategoryListFragment fragment = SubCategoryListFragment.newInstance(categoryId);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment, categoryName).addToBackStack(categoryName).commitAllowingStateLoss();
if (!TextUtils.isEmpty(categoryName)){
setTitle(categoryName);
}
}
private void loadCategoryList()
{
try
{
mCategoryList = CategoryDAO.readAll(-1l, -1l);
}
catch(SQLException e)
{
e.printStackTrace();
}
CategoryModel Thessaloniki = new CategoryModel();
Thessaloniki.setId(PoiListFragment.CATEGORY_ID_THESSALONIKI);
Thessaloniki.setName("Thessaloniki");
Thessaloniki.setImage("drawable://" + R.drawable.ic_category_all);
CategoryModel all = new CategoryModel();
all.setId(PoiListFragment.CATEGORY_ID_ALL);
all.setName(getResources().getString(R.string.drawer_category_all));
all.setImage("drawable://" + R.drawable.ic_category_all);
CategoryModel favorites = new CategoryModel();
favorites.setId(PoiListFragment.CATEGORY_ID_FAVORITES);
favorites.setName(getResources().getString(R.string.drawer_category_favorites));
favorites.setImage("drawable://" + R.drawable.ic_category_favorites);
mCategoryList.add(0,Thessaloniki);
mCategoryList.add(1, all);
mCategoryList.add(2, favorites);
}
private RecyclerView getRecyclerView()
{
return (RecyclerView) findViewById(R.id.activity_main_drawer_recycler);
}
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 1) {
finish();
}else{
getSupportFragmentManager().popBackStack();
String name = getSupportFragmentManager().getBackStackEntryAt(count-2).getName();
setTitle(name);
}
// super.onBackPressed();
}
}
I had face similar issue when i had firstly created project in android stdio with API 23 so for fixing these issue try to do some changes.
Please change your activity code first line :-
public class MainActivity extends AppCompatActivity
to these :-
public class MainActivity extends Activity
It had worked for me when i was in same problem.
Hi so I have been going at this for days and I keep getting a crash everytime I try to move into my list view activity. I have rewritten the list view activity twice here is the activity code:
protected List<ParseObject> exercise_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exersise_display);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Exercises");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if(e==null){
//success
exercise_name = list;
Excercise_Adapter adapter = new Excercise_Adapter(getListView().getContext(), exercise_name);
setListAdapter(adapter);
}
else {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_exersise__display, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
here is the Exercise Adapter class
protected Context mContext;
protected List mExercise;
public Excercise_Adapter (Context context, List exercise){
super(context, R.layout.da_excerisises, exercise);
mContext = context;
mExercise = exercise;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.da_excerisises, null);
holder = new ViewHolder();
//holder.exerciseImage = (ImageView)convertView.findViewById(R.id.Exersise_image);
holder.exerciseName = (TextView) convertView.findViewById(R.id.Exersise_name_menu);
convertView.setTag(holder);
}
else{
holder = (ViewHolder)convertView.getTag();
}
ParseObject exercise_object = mExercise.get(position);
String title = exercise_object.getString("exercise_name");
holder.exerciseName.setText(title);
return convertView;
}
public static class ViewHolder{
//ImageView exerciseImage;
TextView exerciseName;
}
and here is the calling code:
protected Button fitcalcmain;
protected Button excersise;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Parse.initialize(this, "BEFmOu6ru7ulUKCaFaNP8JdGU73RBc4wFfvOjfWp", "dV460EGCxMwhzvRhHQDne2zlYoeOQu2aDypfuTTW");
fitcalcmain = (Button)findViewById(R.id.FitnessCalcMain);
excersise = (Button)findViewById(R.id.ExersisesMain);
fitcalcmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gomeasure = new Intent(MainActivity.this, fitcalc.class);
startActivity(gomeasure);
}
});
excersise.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goexcercises = new Intent(MainActivity.this, Exersise_Display.class);
startActivity(goexcercises);
}
});
}
here is the log (sorry it doesn't let me paste it into here because of "bad formatting":google doc with logcat
XML file of activity:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
here is the manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Workout Buddy"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/Mainmenu" >
</activity>
<activity
android:name=".RegisterActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name=".fitcalc"
android:label="#string/title_activity_fitcalc" >
</activity>
<activity
android:name=".Exersise_Display"
android:label="#string/title_activity_exersise__display" >
</activity>
<activity
android:name=".Types_Activity"
android:label="#string/title_activity_types_" >
</activity>
</application>
You should return convertView in your adapter getView instead of calling super. Plus if this didnt help you please post the code to start your activity.
edit
Please add the two of your activities into the manifest inside of application tag ex:
<activity android:name="myActivity">
<activity android:name="myActivity"Two>
I'm using the NotificationService and a Broadcastreceiver to get the incoming notifications. The service starts from the manifest:
<service android:name="com.myapp.notifications.MyNotificationListenerService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
and it's this;
public class MyNotificationListenerService extends NotificationListenerService{
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
When a notification arrives the log shows me the title, the package and the other informations correctly.. The problem is this one;
I have an Activity that is the MainActivity in which i have the NavigationDrawer. The class where i want show the incoming notifications is a Fragment! So i created in the MainActivity the Broadcastreceiver and then i inflate with LayoutInflater the layout of the fragment to get all component i need in this way:
public BroadcastReceiver onNotice= new BroadcastReceiver() {
LinearLayout notificationLayout;
Drawable icon;
#Override
public void onReceive(Context context, Intent intent) {
final String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
LayoutInflater mInf = LayoutInflater.from(context);
View myView = mInf.inflate(R.layout.activity_main, null);
notificationLayout = (LinearLayout)myView.findViewById(R.id.notificationLayout);
TextView notificationDescription = (TextView) myView.findViewById(R.id.notificationDesc);
TextView notificationTitle = (TextView) myView.findViewById(R.id.notificationTitle);
CircularImageView notificationImage = (CircularImageView) myView.findViewById(R.id.img_thumbnail);
Toast.makeText(DrawerActivity.this, title, Toast.LENGTH_SHORT).show();
if(!pack.equals("") || !title.equals("") || !text.equals("")) {
notificationLayout.setVisibility(View.VISIBLE);
notificationTitle.setText(title);
notificationDescription.setText(text);
try {
icon = DrawerActivity.this.getPackageManager().getApplicationIcon(pack);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
notificationImage.setImageDrawable(icon);
} else {
notificationLayout.setVisibility(View.INVISIBLE);
}
}
};
When the notification arrives now appears the Toast that notify me the title of the notification but i can't see the values in the view.. the layout of the notification is empty.. How is possible?
Or how can i put the values from the activity to my fragment?
Whne you inflate a layout, it creates a new tree made up of new objects.
The way to accomplish what you are trying to would be to cache whatever views that you will change in your onCreate and refer to them in your BroadcastReceiver's onReceive.
private TextView textView;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//TODO: Update Views
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.my_fragment, container, false);
//Cache views
textView = (TextView) root.findViewById(R.id.textview);
return root;
}
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(broadcastReceiver, filter);
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(broadcastReceiver);
}
So i am trying to run the Quickblox sample chat and XMPP Sample Chat.
Im using Eclipse with the newest Android sdk/build.
After importing the sample, the way the Quickblox guide tells, i had a few errors in the in the code, but not much more than a few imports missing, but when im trying to run the app i get an error, the app installs correct but right after errors starts popping in on Logcat.
public class SplashActivity extends Activity implements QBCallback {
private static final String APP_ID = "6445";
private static final String AUTH_KEY = "9a4bnSXbP-KN9G8";
private static final String AUTH_SECRET = "FwunQpKdkE2e7AJ";
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
QBSettings.getInstance().fastConfigInit(APP_ID, AUTH_KEY, AUTH_SECRET);
QBAuth.createSession(this);
}
#Override
public void onComplete(Result result) {
progressBar.setVisibility(View.GONE);
if (result.isSuccess()) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
"please. Errors: " + result.getErrors()).create().show();
}
}
#Override
public void onComplete(Result result, Object context)
{
}
}
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
private static final int AUTHENTICATION_REQUEST = 1;
private static final int POSITION_USER = 0;
private static final int POSITION_ROOM = 1;
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private Action lastAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
List<Fragment> tabs = new ArrayList<Fragment>();
tabs.add(UsersFragment.getInstance());
tabs.add(RoomsFragment.getInstance());
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabs);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(sectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
int position = tab.getPosition();
QBUser qbUser = ((App) getApplication()).getQbUser();
if (qbUser != null) {
viewPager.setCurrentItem(position);
} else if (position == POSITION_ROOM) {
lastAction = Action.ROOM_LIST;
showAuthenticateDialog();
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (lastAction) {
case CHAT:
((UsersFragment) sectionsPagerAdapter.getItem(POSITION_USER)).startChat();
break;
case ROOM_LIST:
viewPager.setCurrentItem(POSITION_ROOM);
break;
}
((RoomsFragment) sectionsPagerAdapter.getItem(POSITION_ROOM)).loadRooms();
} else {
showUsersFragment();
}
}
private void showUsersFragment() {
getSupportActionBar().selectTab(getSupportActionBar().getTabAt(POSITION_USER));
viewPager.setCurrentItem(POSITION_USER);
}
public void setLastAction(Action lastAction) {
this.lastAction = lastAction;
}
public void showAuthenticateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Authorize first");
builder.setItems(new String[]{"Login", "Register"}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivityForResult(intent, AUTHENTICATION_REQUEST);
break;
case 1:
intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivityForResult(intent, AUTHENTICATION_REQUEST);
break;
}
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
showUsersFragment();
}
});
builder.show();
}
public static enum Action {CHAT, ROOM_LIST}
public static class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case POSITION_USER:
return "Users";
case POSITION_ROOM:
return "Rooms";
}
return null;
}
}}
My manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.quickblox.sample.chat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".App"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.quickblox.sample.chat.ui.activities.SplashActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ui.activities.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAINMENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ui.activities.ChatActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".ui.activities.LoginActivity"
android:label="Login" />
<activity
android:name=".ui.activities.RegistrationActivity"
android:label="Registration" />
</application>
</manifest>
This is my error message:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.quickblox.sample.chat/com.quickblox.sample.chat.ui.activities.SplashActivity}: java.lang.ClassNotFoundException: com.quickblox.sample.chat.ui.activities.SplashActivity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
Open Properties->Java Build Path->Order and Export and check QB jar library. According to logs you haven't added it to the build.
1) First of all make sure that you have imported "quickblox-android-1.2.2.jar" which comes with QuickBlox SDK in folder named jar then just Right click on project -> Properties -> Got to Java Build Path -> Order and Export -> just check quickblox-android-1.2.2.jar(which is unchecked in list) -> click Ok.
2)Just Clean the project and run it.
Note:- If you do not clean the project after step 1 then project will crash so clean the project before running it.