Update field if text changed AND has focus - android

I am trying to implement an activity which converts units. There are five fields which I want to be able to convert between on the fly. I can't simply use TextWatcher because when I change a field then that changes all the other fields and cause a circular call which crashes.
I looked at OnFocusChangeListener but that only works when the focus changes whereas I want the update to occur on the fly.
I then thought I could combine the two so I have my TextWatcher and inside that I put this
public void afterTextChanged(Editable s)
{
if (convert_kg.hasfocus())
{
if (convert_kg.getText().toString().matches("")) sums=0.0;
else sums=Double.parseDouble(convert_kg.getText().toString());
answer=(int)Math.round(sums*2.205);
convert_lbs.setText(String.format("%d", answer));
}
}
but I am getting an error of The method hasfocus() is undefined for the type EditText
These are my imports:
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.text.Editable;
import android.text.TextWatcher;
As far as I can tell from http://developer.android.com/reference/android/widget/EditText.html it should be supported? I'm sure this is simple but any ideas?
EDIT: In case anyone was wondering all the fields are EditText
convert_kg=(EditText)findViewById(R.id.convert_kg);

See the comments. isFocused() was the method I needed to use.

Related

Error importing and using RecyclerView

I have a problem when creating a simple RecyclerView
When I import what is necessary to use it, I always get the same error message.
In the main class i have the following imports:
import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
and in then adapter class, the followings:
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
I want to emphasize that I have imported import android.view.View; by the need of the ViewHolder (View view = mInflater.inflate ...)
Well, I always get an error with the following message:
Something that I find very curious is also that in the ViewHolder of the adapter, with a TextView, the same thing happens to me:
In my build.gradle file, these are my imports:
I am using Android Studio 3.1.2
I appreciate the help.
Thanks in advance.
You need to cast your view like
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
Your problem will be solved.
But if you compile your app with API 26, you don't even need to cast, and your existing code will work. :) like
In older versions:
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
In AS3.0 with sdk 26:
RecyclerView recyclerView = findViewById(R.id.rv);

how to fill string arraylist with userinput EditText android eclipse

i am beginner in android programming and English language :) !!
i want to get names from user and show the names that user inputs randomly by pressing a button.
how can i store a user input names in a array list?
and As regards I don't know how many names he wants to enter and don't show a name twice and after showing the name erase that name in array list.
tanks a LOT.
package farshid.mk.teststringarraylist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class StringArraylistActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayList<String> inputs = new ArrayList<String>();
Well, there are many ways to do this but one would be:
Create an EditText, a view that allows user input
Create a Button that the user would click to indicate that he/she is done entering the name in the EditText
Create an OnClickHanlder for the button so that you can get the text from the EditText, convert it to a String (EditText returns an Editable object), and add it to your ArrayList<String>
// add the string
myArrayList.add(myEditText.getText().toString().trim());
To remove duplicates from the List you will need to convert it to a Set... google "java arraylist remove duplicates (First Link)
Also, in Java, it's best practice to use Generics:
// psuedocode
List inputs = new ArrayList
There are many ways you could display this list of text to the user in Android, you will need to research that on your own.
You simply clear the ArrayList when you are done with the names.
This should get you going =)
There's a lot of things you'd need to do to achieve this:
Define the EditText in your layout's XML.
Get a reference to it from the Activity by calling findViewById(R.id.your_edittext_id).
From that reference, call getText().toString() to get the value from the EditText.
Add that String to your ArrayList.
That's basically the main idea behind what you're trying to achieve. I could give you the code but then perhaps its best for you to do it yourself (so that the next time you need to do this, you'd understand the concept).
Good luck! :)

FATAL EXCEPTION: main android validation

I have an application in which i want to add validation, but when i run only validation page it works fine but when i rut it with this page it gives me error.
I think i am doing mistake where i am adding an imagebutton by which i call the validation page which name is propertysearch.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
Well the stacktrace says there's a NullPointerException at line 32 in your ViewPagerStyle1Activity. Look what call is at that line and you should know the culprit.
You are trying to find imageButton1 in your layout main, but it is actually located in your layout layout_one. The fix now depends on what you are actually plan to do with your fragment. You could just set the fragment layout as the layout for your ViewPagerStyle1Activity by replacing setContentView(R.layout.main); with setContentView(R.layout.layout_one); in its' onCreate method.
Update: maybe you should read a bit first about Android Activities, Layouts and Fragments. This is very basic stuff and you won't get far without learning it in and out.
Of course you can't find the imageButton1, if you hard-code findViewById to return null in your fragment.
private ImageButton findViewById(int imagebutton1) {
// TODO Auto-generated method stub
return null;
}
But I get the sense you really don't know what you are actually trying to do.

getLoaderManager().initLoader() doesn't accept 'this' as argument though the class (ListFragment) implements LoaderManager.LoaderCallbacks<Cursor>

I'm having trouble following a guide on using SQLite in Android. I'm using a ListFragment instead of a ListActivity(as in the example), so I have the ListFragment implement LoaderManager.LoaderCallbacks<Cursor> instead. Then, in the fillData() method in the ListFragment:
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { NotesSQLiteHelper.COLUMN_TITLE };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
getLoaderManager().initLoader(0, null, this); //error
adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.notes_row, null, from, to, 0);
setListAdapter(adapter);
}
I get the error:
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks<D>) in the type LoaderManager is not applicable for the arguments (int, null, NotesActivity.ArrayListFragment)
on the marked line even though this implements LoaderManager.LoaderCallbacks<Cursor>.
Thank you for any ideas.
You are not using the right implementations of CursorLoader and Loader.
Remove your old imports and use these ones:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
But I have the same Problem using SherlockActionBar:
As I have to extend SherlockListActivity there is NO method getSupportLoadManager().
Any ideas on this?
EDIT: follow this tutorial if you do not know how to use fragments. Create a new Class with extends SherlockFragment and move your display logic there. Make your old activity extend SherlockFragmentActivity and show the newly created SherlockFragment. This way I got it working. Thanks to #JakeWharton!
A few things to watch out for (from my recent experience battling with this):
If your minSDK is set to less than 11 (i.e. level 10 for Gingerbread) and you are using the Support Pack for backward compatibility, make sure you use
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
You mentioned this when you said you are using ListFragment, but it bears repeating: Do not extend Activity, otherwise the support package will not work. Instead, extend the FragmentActivity class or the ListFragment class.
For your imports, make sure you are using the correct versions if your minSDK < 11:
android.support.v4.app.FragmentActivity;
android.support.v4.app.LoaderManager;
android.support.v4.content.Loader;
Hope this helps you... or at least someone else...
Casting the third argument solved the problem in my case:
from
getLoaderManager().initLoader(0, null, this);
to
getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
Note:
minSdk was 8 and i was using support library v4.
(android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>) this)
did not work.
getSupportLoaderManager() or getSupportLoadManager()
did not work.
This code was inside activity not fragment
It's late but maybe help some one.
if you use loader maneger in fragment and you min api is below HONEYCOMB
you shuld use this imports
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.app.Fragment;
and for initiate loader use this code
getActivity().getSupportLoaderManager().initLoader(/loader stuff*/);
hope this help some one.
Change your imports to
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
and use
getSupportLoaderManager().initLoader(0, null, this);
This is what you have:
getLoaderManager().initLoader(0, null, this);
This is what you should have:
LoaderManager.getInstance(this).initLoader(0, null, this);
Reason for the first one not working:
/**
* #deprecated Use
* {#link LoaderManager#getInstance(LifecycleOwner) LoaderManager.getInstance(this)}.
*/
My error was beacause this:
//import android.app.ListFragment; Error when doesnt import from support.v4
import android.support.v4.app.ListFragment;
In my case I had to have my Activity extend ActionBarActivity from the android.support.v7.app package. I was then able to use
getSupportLoaderManager().initLoader(0, null, this);
I'm using ActionBarSherlock with my app and I as well was running into this issue and worked through all the steps discussed by others in this question. However I was continuing to have the same problem after trying all the suggested resolutions.
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks<D>) in the type LoaderManager is not applicable for the arguments (int, null, this)
The issue was I had fallen into expecting Eclipse to tell me when I was missing something and it was telling me that but not in the way I was used to. Typically Eclipse in other cases would tell me I'm missing the overrides to make something work but it's not directly saying that here. I finally picked up on the "LoaderManager.LoaderCallbacks" being the issue and realized I had no callbacks for it thus this error was actually a very valid error. Adding the basic overrides resolved my issue and allowed me to move forward.
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// do work
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
adapter.swapCursor(null);
}
I was having a similar issue where my AsyncTaskLoader was not returning my List, but my resolution was to change the call from .initLoader to .restartLoader.
So I actually never called .initLoader and just immediately called .restartLoader.
I had a onListItemClick listener in my fragment and every time backed out of the fragment and reloaded the onListItemClick and navigated through the app it kept crashing.
It might just be specific to my app but hopefully it helps others if they are having fragment backstack reload issues.
This was part of a file manager portion in my app so it is specific to clicking multiple onListItemClicks in the fragment you are loading.
I got around this by using a SherlockListFragment (or you could use ListFragment, I suppose), but have it contained within a Activity. I first created a generic FragmentHolderActivity class that looks like this:
FragmentHolderActivity.java
public class FragmentHolderActivity extends SherlockFragmentActivity {
public static final String FRAGMENT_LAYOUT_RESOURCE_ID = "fragment_layout_resource_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Integer fragmentLayoutResourceId = getIntent().getIntExtra(FRAGMENT_LAYOUT_RESOURCE_ID, Integer.MAX_VALUE);
Assert.assertNotSame(fragmentLayoutResourceId, Integer.MAX_VALUE);
setContentView(fragmentLayoutResourceId);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return false;
default:
return super.onOptionsItemSelected(item);
}
}
}
Then you need to create an XML file for your fragment.
your_list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.example.YourListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment" />
And here's the code you use to start the fragment:
Intent intent = new Intent();
intent.setClass(this, FragmentHolderActivity.class);
intent.putExtra(FragmentHolderActivity.FRAGMENT_LAYOUT_RESOURCE_ID, R.layout.your_list_fragment);
startActivity(intent);
You just tell the FragmentHolderActivity to use the your_list_fragment layout, which in turn loads the YourListFragment.java
You can then use: getSherlockActivity().getSupportLoaderManager().initLoader(...) in YourListFragment.java
Not sure if this is the correct approach, but it keeps all my logic in Fragments, which is nice.
Ran into the same problem. My minSdkVersion is 14, so cannot use android.support.v4 package.
I figured it by extending LoaderCallbacks, instead of LoaderManager.LoaderCallbacks and use these packages
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
If you have tried all the above methods and still facing the same error with the "this" parameter, then follow these steps :
Go to settings and enable imports on the fly option.(by default it'll
be enabled and you can do this by using Alt+Enter keys).
Cut the whole code of the activity which had implemented
LoaderCallback... and paste it in a text editor.
Then at last copy the whole code of that activity from the text editor
where you had pasted, without any import commands.( Only the code of
the class/activity).
You'll get lots of errors as you have imported nothing yet.
Just press Alt+Enter wherever you're getting the errors and it's
libraries will be imported automatically.
Note : Choose android.app... library for CursorLoaders.
Try these 2 lines it will work
android.support.v4.app.LoaderManager loaderManager = getSupportLoaderManager();
loaderManager.initLoader(LOADER_ID, null, this);
I am using minSDK 27 and had this same issue, I tried to cast like #Dexter suggest, but that gave an error saying cannot be cast to android.app.LoaderManager$LoaderCallbacks, so I then tried to use different import statements and this worked. I commented out the v4 versions and this is what I have now and the app is working:
//import android.support.v4.app.LoaderManager;
import android.app.LoaderManager;
import android.support.v4.app.NavUtils;
//import android.support.v4.content.CursorLoader;
import android.content.CursorLoader;
//import android.support.v4.content.Loader;
//import android.content.Loader;
Not quite sure when/how the v4 versions were imported.
0
After a long sacrifice i got this solution if you are using fragments then just use this code.
getActivity().getSupportLoaderManager().initLoader(1, null, YourActivity.this);
i hope this is helpful for you
I was trying to call initLoader() inside an activity. For me this worked
changing
getSupportLoaderManager().initLoader(LOADER_ID,null,this);
to
getLoaderManager().initLoader(LOADER_ID,null,this);
If you use API 28 or later, instead of getLoaderManager use:
getSupportLoaderManager().initLoader(id, null, this);
If you use API 29, instead of getLoaderManager use:
getSupportLoaderManager().initLoader(id, null, this);

Android cannot be resolved to a type

I'm getting "cannot be resolved to a type" in my code. I'm looking for solution but all solutions are not working.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class Vortex extends Activity {
private static final String LOG_TAG = Vortex.class.getSimpleName();
private VortexView _vortexView; //there is the problem
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_vortexView = new VortexView(this);
setContentView(_vortexView);
}
}
The problem is with VortexView in this code. Eclipse tell me that VortexView cannot be resolved to a type.
Any solution?
Do you have VortexView class in your project, if so, ctrl+shift+O will resolve the issue. Otherwise add class/jar to classpaht and do ctrl+shift+O (organize imports).
VortexView is your custom view? If there exists VortexView.class
Probably, you have made either of the following two mistakes.
You have not extended a view named VortexView at all
You have extended it correctly, but you haven't made it available to the current package
When you are doing such things, it is better to define custom views inside the same package. Or even though you are defining it somewhere else, make it avilable where it is used.
import yourPackage.VortexView;
Hope this helps.

Categories

Resources