Cannot resolve symbol 'R' please help me - r.java-file

public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", 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;
}
go
#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);
}
}

First you need have an import for R - but your developer tool must import this dependence automatically. Probably you have an error in other code or some problems with your resources. Watch your error logs.

Related

Intent function while running application get crashed

When clicked on this textview the app get crashed and didn't change the activity it is suppose to switch from main activity to another how to resolve it?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etEmail;
private EditText etPassword;
private TextView tvLogin;
private TextView tvSignup;
private Button btnSignin, btMr;
private FirebaseAuth firebaseAuth;
AwesomeValidation awesomeValidation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
updateUI();
firebaseAuth = FirebaseAuth.getInstance();
}
private void updateUI() {
etEmail = (EditText) findViewById(R.id.etEmail);
tvSignup = (TextView) findViewById(R.id.tvSignup);
etPassword = (EditText) findViewById(R.id.etPassword);
tvLogin = (TextView) findViewById(R.id.tvLogin);
btnSignin = (Button) findViewById(R.id.btnLogin);
tvSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signup();
}
public void signup() {
Intent i = new Intent(MainActivity.this, Registration.class);
startActivity(i);
}
});
Here I used awesome validation for validating my form but while running the app shows the toast message, but do not register the user to fire base it validate my form but do not register
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!##\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{8,}";
awesomeValidation.addValidation(MainActivity.this, R.id.etEmail, android.util.Patterns.EMAIL_ADDRESS, R.string.etEmailerr);
awesomeValidation.addValidation(MainActivity.this, R.id.etPassword, regexPassword, R.string.etPasserr);
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (awesomeValidation.validate()) {
Toast.makeText(MainActivity.this, "Data Recieved Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
}
}
});
}
This part register the user to firebase, but after adding this awesome validation this do not work app shows a toast message from validation and do not register or change activity how can i merge both so that my form get validate and also get register to my firebase auth
public void btnLogin_Click(View v) {
final ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Please Wait....", "Processing...", true);
(firebaseAuth.signInWithEmailAndPassword(etEmail.getText().toString(), etPassword.getText().toString()))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "LOGIN SUCCESSFULL", Toast.LENGTH_LONG).show();
Intent signin = new Intent(MainActivity.this, Dashboard.class);
startActivity(signin);
} else {
Log.e("ERROR", task.getException().toString());
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onClick(View view) {
}
}
this is due to the regex function.
the values used in activity1 regex get differ in another activity2 due to which the intent can't switch from one activity to another.
values passed the the regex should be same in all the activity linked.

Volley library throws application exception

I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}

Android reusable view and OnClickListener

I am trying to implement a reusable view and create an OnClickListener that will work for all classes. My code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout)findViewById(R.id.layout1);
Button button = (Button) findViewById(R.id.layout1).findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.layout1).findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.layout1).findViewById(R.id.button3);
applyListener(layout,listener);
applyListener(layout,listener);
applyListener(layout,listener);
}
OnClickListener listener = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Toast.makeText(getApplicationContext(), "ONE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, P2.class);
startActivity(intent);
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "TWO",Toast.LENGTH_LONG).show();
Intent intent2 = new Intent(MainActivity.this, P3.class);
startActivity(intent2);
break;
case R.id.button3:
Toast.makeText(getApplicationContext(), "THREE",Toast.LENGTH_LONG).show();
Intent intent3 = new Intent(MainActivity.this, P4.class);
startActivity(intent3);
break;
}
}
private Context getContext() {
// TODO Auto-generated method stub
return null;
}
};
private static void applyListener(View child, OnClickListener listener) {
if (child == null)
return;
if (child instanceof ViewGroup) {
applyListener((ViewGroup) child, listener);
}
else if (child != null) {
if(child.getId() == R.id.button1) {
child.setOnClickListener(listener);
}
if(child.getId() == R.id.button2) {
child.setOnClickListener(listener);
}
if(child.getId() == R.id.button3) {
child.setOnClickListener(listener);
}
}
}
private static void applyListener(ViewGroup parent, OnClickListener listener) {
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if (child instanceof ViewGroup) {
applyListener((ViewGroup) child, listener);
} else {
applyListener(child, listener);
}
}
}
}
The problem is that once it moves out of the MainActivty, it will crash as soon as I press any button. I am sure it is to do with the line:
Intent intent = new Intent(MainActivity.this, P2.class);
and I think the problem is related to the fact that it is referencing a class that is not active eg MainActivity.this. I have tried replacing MainActivity.this with:
this
and
getContext()
and
getBaseContext()
but they do not work.
I have also tried
Intent intent = new Intent("com.example.APANEL.P2.class");
but this does not work either.
I am sure the applyListener method is being implemented properly as the buttons are all children and are therefore being implemented using the method:
private static void applyListener(ViewGroup parent, OnClickListener listener)
I have read the android documentation and every post I can find, but I cannot seem to find a working solution.
Any help would be greatly apreciated
I solved it myself by doing the following:
In the MainActivity class I created the method:
public void setup(){
LinearLayout layout = (LinearLayout)findViewById(R.id.layout1);
Button button = (Button) findViewById(R.id.layout1).findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.layout1).findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.layout1).findViewById(R.id.button3);
applyListener(layout,listener);
}
Then, all classes that re-use the view eg display the button panel must extend MainActivity, and in the onCreate() method, they implement the method setup()
To summarise, it was nothing to do with the Intent, but was to do with the fact that in the subsequent classes, the listeners were not set up.

How to handle the setText("Some Text") event on a disabled TextBox

I want to fire an event when setting a value in a TextBox with setText("something")
What I tried so far
w.addChangeHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent event) {
isChanged = true;
}
});
And I tried also to have a custom a TextBox that listen to past event
class CustomTextBox extends TextBox implements HasHandlers {
private HandlerManager handlerManager;
public CustomTextBox() {
super();
handlerManager = new HandlerManager(this);
sinkEvents(Event.ONPASTE);
}
#Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (event.getTypeInt()) {
case Event.ONPASTE:{
fireEvent(new TextChangeEvent());
break;
}
default:
// Do nothing
}
}
#Override
public void fireEvent(GwtEvent<?> event) {
handlerManager.fireEvent(event);
}
public HandlerRegistration addTextChangeEventHandler(TextChangeEventHandler handler) {
return handlerManager.addHandler(TextChangeEvent.TYPE, handler);
}
}
With no success, any suggestions would be appreciated.
setText won't fire events.
Add a ValueChangeHandler<String> to your TextBox, then use setValue("something", true) to fire a ValueChangeEvent<String> to all handlers while setting the new value, whether the box id disabled or not.

Return from a pushed BlackBerry screen to the parent screen

I have a main menu in Blackberry application. I want to access different screens when I enter the menu items and need to come back to the main menu. How can I do it?
Here is what I tried but caught up a runtime exception when pressed Back button:
package com.stockmarket1;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.decor.*;
import net.rim.blackberry.api.push.PushApplication;
public class StockMarket extends UiApplication implements FieldChangeListener {
public Screen _clientList;
public Screen _comments;
public Runnable _popRunnable;
public static void main(String[] args)
{
StockMarket theApp = new StockMarket();
theApp.enterEventDispatcher();
}
public StockMarket() {
//Code for MainScreen
final MainScreen baseScreen = new MainScreen();
baseScreen.setTitle("Colombo Stock Exchange");
ButtonField clientList = new ButtonField("View Client List", ButtonField.CONSUME_CLICK);
clientList.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
pushScreen(_clientList);
}
});
ButtonField comments= new ButtonField("View Comments", ButtonField.CONSUME_CLICK);
comments.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
pushScreen(_comments);
}
});
Bitmap bitmap = Bitmap.getBitmapResource("logo1.png");
BitmapField logo = new BitmapField(bitmap, BitmapField.FIELD_HCENTER);
LabelField newLine = new LabelField("\n");
baseScreen.add(logo);
baseScreen.add(newLine);
baseScreen.add(clientList);
baseScreen.add(comments);
//Code for _comments
_comments = new FullScreen();
_comments.setBackground(BackgroundFactory.createSolidBackground(Color.LIGHTCYAN));
LabelField title = new LabelField("Comments",LabelField.FIELD_HCENTER);
LabelField comment = new LabelField("Type");
RichTextField rtfComment = new RichTextField();
_comments.add(title);
_comments.add(comment);
_comments.add(rtfComment);
//Code for _clientList
_clientList = new FullScreen();
_clientList.setBackground(BackgroundFactory.createSolidBackground(Color.LIGHTBLUE));
LabelField clientTitle = new LabelField("Listed Companies\n\n", LabelField.FIELD_HCENTER);
LabelField line = new LabelField("__", LabelField.USE_ALL_HEIGHT);
ButtonField closeClient = new ButtonField("Close", ButtonField.CONSUME_CLICK);
closeClient.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
pushScreen(baseScreen);
}
});
_clientList.add(clientTitle);
_clientList.add(line);
//Events
pushScreen(baseScreen);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}
The code for your 'Close' button is a problem, but I think you said you get a RuntimeException when hitting the 'back' button on the device, which I think has a different cause.
Instead of pushing the menu screen onto the screen stack, you should just pop the current screen. This will return to the menu screen that was displayed previously:
closeClient.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// previous code:
// pushScreen(baseScreen);
// correct code:
popScreen(_clientList);
}
});

Resources