i am using ListView in main activity and class adapter extends ArrayAdapter with login form only one row.
code adapter like this"
public class AdapterLogin extends ArrayAdapter<ListArrayItem> {
Context mContext;
int layoutResourceId;
ListArrayItem data[] = null;
public AdapterLogin(Context mContext, int layoutResourceId, ListArrayItem[] data) {
super(mContext, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.data = data;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
}
//here i have for login like this
lin_form = new LinearLayout(mContext);
EditText email_input = new EditText(mContext);
Button btn_sign = new Button(mContext);
btn_sign.setOnClickListener(login_btn_clicked);
TextView login_status_message = new TextView(mContext);
lin_form.addView(email_input);
lin_form.addView(btn_sign);
lin_form.addView(login_status_message);
rowitem = (RelativeLayout)convertView.findViewById(R.id.rowitem);
rowitem.addView(lin_form);
return convertView;
}
public OnClickListener login_btn_clicked = new OnClickListener() {
String email_value = email_input.getText().toString();
// i want to see email_value but doesnt show me any thing
login_status_message.setText("email value:"+ email_value);
};
in main activity i have a code like this:
FillFooter fillfooter= new FillFooter();
fillfooter.setFooter(MainActivity.this,"mainactivity");
fillfooter.fillFooter();
public static void gotoLogin(Context context){
Activity activity = (Activity)context;
activity.setTitle("Broonza: Вход");
list = new HashMap<String, String>();
listarraymain[0] = new ListArrayItem(1, list);
AdapterLogin adapter = new AdapterLogin(context, R.layout.row_item, listarraymain);
listviewtmain.clearFocus();
listviewtmain.setAdapter(adapter);
}
in the class fill footer
public class FillFooter {
public void setFooter(Context context,String typeactivity){
this.context = context;
this.activity = (Activity) context;
linaccount = new LinearLayout(context);
linaccount.setOnClickListener(gotologin);
}
public OnClickListener gotologin= new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.gotoLogin(context);
}
};
}
row_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="1dp"
android:paddingBottom="0dp"
android:paddingTop="10dp"
android:id="#+id/rowitem" >
load form login with all fields from adapter to listview work fine, but when clicking button login if email field content text doesn't show that text.
The problem is not in the printed error!, The problem in the printing field email value! OnCLickListener() doesnt work. it will work only if i will add text for email_field onto inside adapter like this! email_input.setText("example#mail.ru")
I think that instead of
if(error !=""){
login_status_message.setText(error);
}
should be this:
if(!error.equals(""){
login_status_message.setText(error);
}
This is basically a string comparsion. If you want to compare a string to a string, you should use equals() instead of !=.
Your problem is that the error value is always null and you can not see the value of email, it is not calling login_status_message.setText("email value:"+ email_value);
Change this
btn_sign.setOnClickListener(login_btn_clicked);
TextView login_status_message = new TextView(mContext);
by this:
TextView login_status_message = new TextView(mContext);
btn_sign.setOnClickListener(login_btn_clicked);
Your is initializing under the getView method and is local to that block;
How you are accessing this field outside the method?
You have created the object local with the method as-
EditText email_input = new EditText(mContext);
TextView login_status_message = new TextView(mContext);
inside the getView method.
You need to put your Listener inside the getView method as
btn_sign.setOnClickListener(new OnClickListener() {
String email_value = email_input.getText().toString();
// i want to see email_value but doesnt show me any thing
login_status_message.setText("email value:"+ email_value);
});
Re-examine the code if you are having another duplicate fields for that.
Thank you for all). after restart eclipse, it work fine.
Related
I have 2 different activities but both of them has a listview. My first activity is empty in terms of data. It just has a button for passing to my second activity.
Each row contains one imageView, textView and checkBox in my second activity.
When I make the checkbox active in my second activity any row, I want to send data to my first activity. For example, I click a checkbox for selecting a line, and when I back in first activity, I should see this line (with ImageView, TextView). Actually, in addition, I want to delete data in first activity when checkbox isn't active. However, I am thinking that I can find this solution if you help me for my first question.
MY FIRST ACTIVITY (I should see rows in here)
ImageView image = (ImageView) findViewById(R.id.image);
Bundle bundleObject = getIntent().getExtras();
if (bundleObject != null) {
String resultText = bundleObject.getString("RESULT_TEXT");
dbHelper.insertNewTask(resultText);
byte[] byteArray = bundleObject.getByteArray("picture");
Bitmap b = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
image.setImageBitmap(b); //ERROR IS HERE!!!!! IT ISN'T WORKING
MY SECOND ACTIVITY
byte[] byteArray;
Bitmap bmp;
int[] images = {R.drawable.book, R.drawable.watchingtv};
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.book);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
class MyAdapter extends ArrayAdapter<String> implements View.OnClickListener {
Context context;
int[] images;
String[] mytitles;
MyAdapter(Context c, String[] titles, int images[]) {
super(c, R.layout.row_2, R.id.newTaskTitle, titles);
this.context = c;
this.images = images;
this.mytitles = titles;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.row_2, parent, false);
ImageView myImage = (ImageView) row.findViewById(R.id.newImage);
final TextView myTitle = (TextView) row.findViewById(R.id.newTaskTitle);
myImage.setImageResource(images[position]);
myTitle.setText(mytitles[position]);
checkBox = (CheckBox) row.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Boolean durum = checkBox.isChecked();
if(durum=true){
Intent intent = new Intent (dinlenmeEkrani_newOptions.this, dinlenmeEkrani.class);
intent.putExtra("picture", byteArray);
intent.putExtra("RESULT_TEXT", myTitle.getText().toString());
startActivity(intent);
}
else{
}
}
});
return row;
}
Second activity might has mistakes. When I try to reach the solution, I might do some mistakes.
I want to say these : I have succeeded in terms of passing textview. So, When I delete some codes related to Image (especially in my first activity), I see passing textView which is coming from String.xml. And also, I just have tried R.Drawable.book because if it works, I think that I can add others drawables.
(if you wonder dbHelper, it is here)
public class Database extends SQLiteOpenHelper
public static final String DB_TABLE = "Task";
public static final String DB_COLUMN = "TaskName";
public void insertNewTask (String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.insertWithOnConflict(DB_TABLE,null,values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
Isn't possible to share any view object between activities, because their are linked with the Activity and Activities are completely independent. You need to create a logic to identify and deal with states just passing small pieces of data between activities, like you are already doing with the intent.
I am running into some difficulty with populating values to a listview, which currently displays no rows.
Firstly I am retrieving values from my database table and storing them in Arrays within onPostExecute.
LikedListAdapter listAdapter = new LikedListAdapter(context, R.layout.liked_list_main, restID, restName, restAddr1, restAddr2, restImgPath);
lvPlaces.setAdapter(listAdapter);
These values are then successfully passed into my ListAdapter.
public LikedListAdapter(Context context, int resource, String[] restID, String[] restName, String[] restAddr1, String[] restAddr2, String[] restImgPath) {
super(context, resource);
this.context = context;
this.resource = resource;
this.restID = restID;
this.restName = restName;
this.restAddr1 = restAddr1;
this.restAddr2 = restAddr2;
this.restImgPath = restImgPath;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout likedItemsView;
if(convertView==null) {
likedItemsView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, likedItemsView, true);
}
else {
likedItemsView = (LinearLayout) convertView;
}
ImageView restaurantImg = (ImageView)likedItemsView.findViewById(R.id.listItemThumbImg);
TextView restaurantName =(TextView)likedItemsView.findViewById(R.id.listItemTitle);
TextView restaurantDesc = (TextView)likedItemsView.findViewById(R.id.listItemSubText);
restaurantName.setText(restName[position]);
restaurantDesc.setText(restAddr1[position] + ", " + restAddr2[position]);
Picasso
.with(getContext())
.load(restImgPath[position])
.into(restaurantImg);
return likedItemsView;
}
However, when i run the app the Listview is empty. When debugging i notice that the values are successfully passed to my listAdapter (on debugging it displays the values retrieved being displayed in the constructor) however it never hits the method getView, where values are set to each listview widget.
Is there something i am misunderstanding, or do i need to call the getView method at some point? Thanks in advance.
Did you override
getCount()
method? If not then return the size of your rows. Ex-
#Override
public int getCount() {
return restName.length;
}
Hope your problem will be solved. If already populated list then use
adapter.notifyDataSetChanged()
method.
LikedListAdapter listAdapter = new LikedListAdapter(context, R.layout.liked_list_main, restID, restName, restAddr1, restAddr2, restImgPath);
lvPlaces.setAdapter(listAdapter);
listAdapater.notifyDataSetChanged(); // <-- add this
I'm having troubles saving the state of a selected radiobutton when the user hits the back key and then comes back to the activity. My class extends ListActivity. Here's the onCreate and onBackPressed() methods of the class that creates the listview.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_manager);
dataInfo = new HandleData(ProfileMaker.this);
dataInfo.open();
people = dataInfo.getAllComments();
userAdapter = new ArrayAdapter<People>(ProfileMaker.this, android.R.layout.simple_list_item_single_choice, people);
setListAdapter(userAdapter);
registerForContextMenu(getListView());
addUser = (Button) findViewById(R.id.buttonAddUser);
graphUser = (Button) findViewById(R.id.buttonGraph);
addUser.setOnClickListener(this);
graphUser.setOnClickListener(this);
idSharing = getSharedPreferences(idPref, 0);
nameSharing = getSharedPreferences(namePref, 0);
ageSharing = getSharedPreferences(agePref, 0);
weightSharing = getSharedPreferences(weightPref, 0);
genderSharing = getSharedPreferences(genderPref, 0);
otherName = getSharedPreferences(nameThere, 0);
otherAge = getSharedPreferences(ageThere, 0);
otherWeight = getSharedPreferences(weightThere, 0);
otherGender = getSharedPreferences(genderThere, 0);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent newIntent = new Intent(ProfileMaker.this, Monitor.class);
startActivity(newIntent);
}
Whenever I press the home button and come back to the application, the radiobutton that I selected is still selected, but when I press the back key to go to the previous activity and then come back to this one, the radiobutton is not selected. How can I save the state of a previously selected radiobutton? These radiobuttons are in a radiogroup. Any help is highly appreciated. Thanks.
EDIT:
Ok, so this is what I got.
public class AdapterClass extends ArrayAdapter<People>{
private final List<People> list;
private final Activity context;
public AdapterClass(Activity context, List<People> list) {
super(context, R.layout.profile_manager, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected RadioButton radioButton;
RadioGroup group;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.button_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.radioButton = (RadioButton) view.findViewById(R.id.check);
viewHolder.radioButton
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
People element = (People) viewHolder.radioButton
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.radioButton.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).radioButton.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.radioButton.setChecked(list.get(position).isSelected());
return view;
}
I got excited when it actually had a radiobutton selected. But the problem is it only selects the first button in the list an nothing else even if I deselected it and selected another item. Also, it's letting me select more than one radio button which I don't want. What am I missing?
You are losing the state of the radiogroup as you are navigating using intent when the back key is pressed, so activity reinitializing (i.e Again when you come to your screen it will start from oncreate) , you need to add extras to your intent send you radio button states
example like this
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent newIntent = new Intent(ProfileMaker.this, Monitor.class);
newIntent.putExtra("somename",state of the radiobutton);
startActivity(newIntent);
}
and in ProfileMaker activity check is there any extra , if there is an extra get that and select radiobutton according to that.
if (getIntent().getExtras().getString("yourextraname") != null)
applicant = getIntent().getExtras().getString("applicant");
Make an boolean array and fill it with false value as number of radio buttons.Now when ever you click radio button make that index true if it was false and if clicked again do it false. Use your own list adapter it will helps you more . I had done similar in case of check box you can see my post Unable to check/uncheck CheckedTextView inside getView . Reply me if this helps you ...
This one has me quite stumped. I'm sure it is just something simple I am missing, but I cant seem to find out what...
When I run the program, it opens up the dialog box and displays the AutoCompleteTextView I have initialized. When I try to type something into it, nothing drops down or is displayed other than the text I type in. I have created a similar system in another part of my program with the same mechanics, but using a regular ArrayAdapter and it works fine so the interface is not the problem.
Here is where I initialize my custom ArrayList. I have been trying to use just strings to make it simpler.
final Dialog weaponDialog = new Dialog(BattleScreen.this);
weaponDialog.setContentView(R.layout.weapon_selection_dialog);
weaponDialog.setTitle("Add a Weapon");
weaponDialog.setCancelable(true);
String[] weaponStringArrayList = ConstantEquipmentHelper.getCondensedWeaponString();
WeaponArrayAdapter weaponAdapter = new WeaponArrayAdapter(this, R.layout.weapon_list_item, weaponStringArrayList);
weaponDialogAcTextView = (AutoCompleteTextView) weaponDialog.findViewById(R.id.weaponSelectionAutoCompleteTxt);
weaponDialogAddButton = (Button) weaponDialog.findViewById(R.id.weaponSelectionAddButton);
weaponDialogWeaponInfo = (TextView) weaponDialog.findViewById(R.id.weaponSelectionInformationTxt);
...
...
...
Here is my custom ArrayAdapter Class
public class WeaponArrayAdapter extends ArrayAdapter<String> {
private Context context;
String[] objects;
public WeaponArrayAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId);
this.objects = objects;
this.context = context;
}
private class WeaponItemHolder {
TextView weaponName;
TextView weaponCat;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
final WeaponItemHolder holder;
if (convertView == null) {
//Sets up a new holder to temporaraly hold the listeners that will be assigned to the binded variables
holder = new WeaponItemHolder();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.weapon_list_item, null);
//Find the IDs! Find them!!!!
holder.weaponName = (TextView) convertView.findViewById(R.id.weaponListItemName);
holder.weaponCat = (TextView) convertView.findViewById(R.id.weaponListItemCategory);
//"Sets the tag associated with this view. A tag can be used
//to mark a view in its hierarchy and does not have to be unique within the hierarchy."
convertView.setTag(holder);
} else {
holder = (WeaponItemHolder) convertView.getTag();
}
String spellName = objects[position];
String[] weaponInfo = spellName.split("\\:");
weaponInfo[1] = weaponInfo[1].trim();
holder.weaponName.setText(weaponInfo[0]);
holder.weaponCat.setText(weaponInfo[1]);
return convertView;
}
}
Additional Info: I have tried debugging it and it never reaches getView. This makes sense of course, as its not displaying anything.
Thanks,
-Andrew
EDIT: I have found out how to implement the above problem:
I used a SimpleAdapter with a custom layout.
However, now I can not select any of the items... onItemClick is not even called when I try to click it. It probably has to do with using the SimpleAdapter??
LINK: http://lemonbloggywog.wordpress.com/2011/02/15/customer-autocomplete-contacts-android/
ArrayList<Map<String, String>> weaponStringArrayList = ConstantEquipmentHelper.getCondensedWeaponString();
//The adapter that recieves the layout type from android and the array creatd by the above function.
SimpleAdapter simpleAdapter = new SimpleAdapter(this, weaponStringArrayList, R.layout.weapon_list_item ,new String[] {"name", "category"}, new int[] { R.id.weaponListItemName, R.id.weaponListItemCategory});
//Find the view blah blah blah...
weaponDialogAcTextView = (AutoCompleteTextView) weaponDialog.findViewById(R.id.weaponSelectionAutoCompleteTxt);
weaponDialogAddButton = (Button) weaponDialog.findViewById(R.id.weaponSelectionAddButton);
weaponDialogWeaponInfo = (TextView) weaponDialog.findViewById(R.id.weaponSelectionInformationTxt);
//Set that adapter!
weaponDialogAcTextView.setAdapter(simpleAdapter);
You have to implement getCount() and set the count of your data, i.e. objects.length.
You also have to set the adapter to the view using the method setAdapter().
Hope this helps!
Before making my own SimpleAdapter object because I wanted to change the color of the rows, I was just using new SimpleAdapter(...). Now that I am using my own custom SimpleAdapter, the row color is changing, but my text is not getting updated. I have called adapter.notifyDataSetChanged(), but it is still showing only the sample text- "TextView". As I said, everything was working fine when I didn't create my own adapter. I suspect it might have something to do with the order I am initializing things:
public class AddScreen extends Activity implements OnClickListener,
OnItemClickListener, OnItemLongClickListener {
SimpleAdapter adapter;
List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();
ListView listthings;
int[] to;
String[] from;
public void onCreate(Bundle savedInstanceState) {
...
listthings = (ListView) findViewById(R.id.listthings);
from = new String[] { "row_1", "row_2" };
to = new int[] { R.id.row1, R.id.row2 };
adapter = new Adapter(this, painItems, R.layout.mylistlayout,
from, to);
listthings.setAdapter(adapter);
...
}
public class Adapter extends SimpleAdapter{
HashMap<String, String> map = new HashMap<String, String>();
public Adapter(Context context, List<? extends Map<String, String>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
if (row == null) {
LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.mylistlayout, parent, false);
}
row.setBackgroundColor(0xFF0000FF);
TextView rw1 = (TextView)findViewById(R.id.row1);
// TextView rw2 = (TextView)findViewById(R.id.row2);
rw1.setText(map.get(position));
return row;
}
}
// to add the item, put it in the map, and add the map into the list
private void addItem() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("row_1", row1);
map.put("row_2", row2);
map.put("row_3", painLevelString);
map.put("row_4", painLocation);
map.put("row_5", timeOfPainString);
map.put("row_6",textTreatmentString);
painItems.add(map);
adapter.notifyDataSetChanged();
}
EDIT:Added Code
This is how I am getting the data from the intent(onActivityResult()), placed before the addItem Code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
row1 = data.getStringExtra("com.painLogger.row1");
row2 = data.getStringExtra("com.painLogger.row2");
painLevelString = data.getStringExtra("com.painLogger.painLevel");
painLocation = data.getStringExtra("painLocation");
timeOfPainString = data.getStringExtra("com.painLogger.painTime");
textTreatmentString = data
.getStringExtra("com.painLogger.treatment");
addItem();
}
}
*Also, just in case this is relevant the order of placement is this: onCreate() -> custom Adapter class -> onActivityResult() -> addItem()* **
Here is a screenshot of what it looks like. The two TextView fields in each item should be filled with info(which they were, until I did this).
If it worked previously with just using new SimpleAdapter(...) then in your getView(...) implementation change the first line to this:
View row = super.getView(position, convertView, parent);
And see if that is what you're expecting. Take out the LayoutInflater stuff too.
In getView(), about where you are setting the row background, you should also set the text for the TextView.
Calling notifyDataSetChanged(), doesn't automagically set your texts right, it just causes the ListView to redraw the visible rows with the new data...practically calling getView() for each row that needs a refresh.
I also suggest setting the background color from the mylistlayout.xml file, and if the getView() function starts taking on a few findViewByID's, you should also consider using a "view holder" approach like in this sample: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html
You need to set the text in getView(). Like this:
public View getView(int position, View convertView, ViewGroup parent){
TextView text;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.mylistlayout, parent, false);
text = (TextView) convertView.findViewById(R.id.more_list_text);
}
convertView.setBackgroundColor(0xFF0000FF);
text.setText(map.get(position));
return convertView;
}
Also, and this is VERY important - store you map as a member variable of the SimpleAdapter
ie, put this line at the top of your object definition:
HashMap<String, String> map = new HashMap<String, String>();