cannot find symbol variable Android Studio 0.8.1 - android-studio

I am new to android studio and I am trying to run this code.
My code:
package app.sunshine.android.example.com.sunshine;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
// Create some dummy data for the ListView. Here's a sample weekly
// Represented as "day, whether, high/low"
String[] forecastArray= {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
// Now that we have some dummy forecast data, create an ArrayAdapter.
// The ArrayAdapter will take data from a source ( Like our dummy forecast
// use to populate the ListView it's attached to
mforecastAdapter =
new ArrayAdapter<String>(
//The current context( this fragment's parent activity
getActivity(),
// ID of list item layout
R.layout.list_item_forecast,
// ID of the textview to populate
R.id.list_item_forecast_textview,
// Forecast data
weekForecast);
// Get a reference to the LIstView and attach this adpater to it
ListView listView = (ListView) rootView.findViewById(
R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}
}
but I get the following error : cannot find symbol variable
I tried cleaning the project gradle and restarted android application .
but I am still encountering the issue
any help would be greatly appreciated :)
I am following this tutorial https://www.udacity.com/course/viewer#!/c-ud853/l-1395568821/e-1395668601/m-1395668603

You need to declare mForecastAdapter.
public static class PlaceholderFragment extends Fragment {
ArrayAdapter<String> mForecastAdapter;
public PlaceholderFragment() {
}
Since you have not done that yet it does not recognize the variable mForecastAdapter. Hope this helps.

Related

new View.OnClickListener () greyed out ->" No Adapter Attached, skipping Layout" error message

I copied code for a recycler View from a Youtube tutorial but it won't work out for me. The new View.OnClickListener() is greyed out, with Android Studio suggesting to replace out with lambda. This is the only difference from my code to the one from the tutorial... The App runs through, but doesn't show the Layout, as I get the error message E/RecyclerView: No adapter attached; skipping layout.
what can I do to fix this?
This is the Adapter class:
package com.example.yourfoodweek;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class MealsRecViewAdapter extends RecyclerView.Adapter<MealsRecViewAdapter.ViewHolder>{
private static final String TAG = "MealsRecViewAdapter";
private ArrayList <Food> meals = new ArrayList<>();
private Context mContext;
public MealsRecViewAdapter(Context mContext) {
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_meals_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: Called");
holder.txtName.setText(meals.get(position).getName());
Glide.with(mContext)
.asBitmap()
.load(meals.get(position).getImageUrl())
.into(holder.imgFood);
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
Toast.makeText(mContext, meals.get(position).getName() + "Selected", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return meals.size();
}
public void setMeals(ArrayList<Food> meals) {
this.meals = meals;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private CardView parent;
private ImageView imgFood;
private TextView txtName;
public ViewHolder(#NonNull View itemView){
super(itemView);
parent = itemView.findViewById(R.id.parent);
txtName = itemView.findViewById(R.id.txtMealName);
imgFood = itemView.findViewById(R.id.imgFood);
}
}
}
both problems are totally different. first one was suggestion means if you don't want to apply you can skip it. but i will not suggest to do that.
for example:
(without Lambda)
myButton.setOnClickListener(new View.OnClickListerner(){
#Override
void onClick(View v) {
// do some stuff related to action
}
});
(with Lambda)
myButton.setOnClickListener(v -> {
// do some stuff related to action
})
for other question
no layout manager attached:
if your RecyclerView doesn't have any LayoutManager attached to it then it will skip cause it will not know how to arrange/show items.
Some LayoutManagers:
LinearLayoutManager
GridLayoutManager
StaggeredGridLayoutManager
if you want to create your own LayoutManager you can do it by just extending class LayoutManager
how to use it:
....
LinearLayoutManager layoutManager = new LinearLayoutManager();
layoutManager.setOrientation = LinearLayoutManager.HORIZONTAL
myRecyclerViewObj.setLayoutManager(layoutManager);
....
no adapter attached
similar to no layout manager this will be shown when no adapter attached to recycler view for this you have to use setAdapter method to set your adapater
for example:
....
MealsRecViewAdapter adapter = new MealsRecViewAdapter(this);
myRecyclerViewObj.setAdapter(adapter);
....

OnClicklistener in RecyclerView [duplicate]

Thank you in advance and dont be very hard with me, it is my first question.
I was trying to add a new item to my recyclerView through the adapter by declaring a method in my adapter called addItem(String newItem)
Then I tried to call this method when the floating button is clikced and the problem is that the method does not even appear when i hit cntrl+space and if i write it down it gets on red.
I have already tried to rebuild the project and nothing changes.
¿Any ideas about how to solve it?
MainActivity class
package com.example.sakur.recyclerviewapp;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private FloatingActionButton mFloatingActionButton;
private List<String> recyclerItems = Collections.emptyList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerItems = new ArrayList<>();
recyclerItems.add("First item");
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(recyclerItems);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.floating_action_button);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemNuevo = "New Card";
mAdapter.addItem(itemNuevo);
Snackbar.make(view, "Item added successfully", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_main, 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);
}
}
and the MyAdapter class
package com.example.sakur.recyclerviewapp;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by Sakur on 19/12/2015.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mDataset= Collections.emptyList();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<String> myDataset) {
mDataset = myDataset;
}
public void addItem(String newItem){
mDataset.add(newItem);
notifyDataSetChanged();
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_card, parent, false);
// set the view's size, margins, paddings and layout parameters
//...
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ImageView mImageView;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text_card);
}
}
}
addItem(String) is not a method of RecyclerView.Adapter, but of your MyAdapter subclass. Obviously, RecyclerView.Adapter has no knowledge of the existence neither of your MyAdapter nor of your addItem(String).
you can either change
private RecyclerView.Adapter mAdapter;
into
private MyAdapter mAdapter;
or cast mAdapter. E.g.
if (mAdater instanceof MyAdapter) {
((MyAdapter) mAdapter).addItem(...);
}

Alarm notification is not working for API>=26 android emulators

I am trying to send a notification that appears under the top navigation bar as follows:
My codes work for android emulator with API < 26, but they do not work for android emulator with API >= 26. I found that it is because I need to add channel, so I did. However, although the codes compile well and go through all loops, and there is no error in logcat. Still, the notification does not appear on the screen.
Any help will be greatly appreciated. FYI, here is my FragmentAlarm.java:
package com.example.dailybible3;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import java.util.Calendar;
public class FragmentAlarm extends Fragment {
private View view;
private CheckBox box_sun, box_mon, box_tue, box_wed, box_thu, box_fri, box_sat;
private CheckBox order_history, order_bible;
private CheckBox ninety_days, one_year;
private Button btn_save;
public static FragmentAlarm newInstance() {
FragmentAlarm fragmentAlarm = new FragmentAlarm();
return fragmentAlarm;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_alarm, container, false);
/* start of set notification */
createNotificationChannel();
/* end of set notification */
//save button
btn_save = (Button) view.findViewById(R.id.save_button);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "This is a notificaiton example";
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getContext(), "notifyBibleVerse"
)
.setSmallIcon(R.drawable.ic_bible_english)
.setContentTitle("Today's Verse")
.setContentText("Genesis 1 - 3")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
/* start of setting notification */
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("message", message);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notiifcationManager = (NotificationManager) getActivity().getSystemService(
Context.NOTIFICATION_SERVICE
);
notiifcationManager.notify(0, builder.build());
toastMessage("Alarm is set!");
}
});
return view;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "DailyBibleChannel";
String description = "Channel for Bible Verse Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyBibleVerse", name, importance);
channel.setDescription(description);
}
}
private void toastMessage(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
}
I am still not sure how to solve the above problem, but I found the working code from here: https://codinginflow.com/tutorials/android/alarmmanager. The major difference I see is that the working code has AlarmManager. Hope this help someone who is having troubles to set a notification.

FindViewById in android studio

hi im beginner an trying to define a button on android studio. i get an as i write "FindV" and android studio have no suggestion for me. if complete code myself, get error. here is the code:
package com.example.neomn.myapplication1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) FindV // no suggestions
}
#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_main, 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);
}
}
Can you try to type as findViewById?
It should start from small letter f.
Without completing findViewById you will get error if you run.
Check if Power Save Mode on File menu is disabled,that may cause disabling auto complete features

Do I need to create these many classes for this android app?

I am an absolute beginner at programming so I just want to make sure I am doing this right or if there is an easier way. basically the app I am creating is a school app that will list all courses needed for different majors.
So opening screen has two buttons undergrad and grad. The next screen would list all majors for either grad or undergrad, which ever one the user chose, then say a person clicked accounting it would then list all courses for accounting major. My question is do I need to create a seperate class for each course and major?? Below is the code I have been doing.
package Class.Review;
import Class.Review.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
public class ClassReviewActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Undergrad = (Button) findViewById(R.id.BUNGrad);
Undergrad.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent myIntent =
new Intent(view.getContext(), undergrad.class);
startActivityForResult(myIntent, 0);
}
});
}
}
Then say the user clicked undergrad i created another class
package Class.Review;
import Class.Review.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.content.Intent;
public class undergrad extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.undergrad);
setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent replyIntent = new Intent();
setResult(RESULT_OK, replyIntent);
finish();
}
});
}
private void setOnClickListener(OnClickListener onClickListener) {
// TODO Auto-generated method stub
Button Accounting = (Button) findViewById(R.id.Accounting);
Accounting.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent myIntent =
new Intent(view.getContext(), accounting.class);
startActivityForResult(myIntent, 0);
}
});
}
}
Then choice a specific course within Accounting
package Class.Review;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.Intent;
public class accReview extends Activity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accreview);
setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent replyIntent = new Intent();
setResult(RESULT_OK, replyIntent);
finish();
}
});
}
private void setOnClickListener(OnClickListener onClickListener) {
// TODO Auto-generated method stub
Button review = (Button) findViewById(R.id.reviews);
review.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent myIntent =
new Intent(view.getContext(), fundReview.class);
startActivityForResult(myIntent, 0);
}
});
}
}
Unless you need different functionality for each course, you're probably better of using a single Course class with a few fields containing course name (String), max number of students (some integer type), maybe a Professor object, or whatever you need to describe the course. You don't want to rewrite, recompile and redistribute the code each time you want to add, remove or rename a course, do you?
Also, this doesn't just apply to this specific case, this question has probably been asked tons of times before.

Resources