I'm trying to use a Custom ListView Adapter to switch to different activities, but am having trouble doing so, as there is an error that I can't seem to get rid of.
Relevant code
Category Table:
public class CategoryTable extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_table);
populateTable();
goToPreviousActivity();
}
private void populateTable() {
final ListView mListView = findViewById(R.id.listView);
Category 1 = new Category(" One");
Category 2 = new Category(" Two");
Category 3 = new Category(" Three");
Category 4 = new Category(" Four");
final ArrayList<Category> categoryList = new ArrayList<>();
categoryList.add(1);
categoryList.add(2);
categoryList.add(3);
categoryList.add(4);
CategoryListAdapter adapter = new CategoryListAdapter(this, R.layout.adapter_view_layout, categoryList);
mListView.setAdapter(adapter);
}
private void goToPreviousActivity() {
ImageButton btn = findViewById(R.id.backButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public static Intent makeIntent(Context context) {
return new Intent(context, CategoryTable.class);
}
}
Category List Adapter:
public class CategoryListAdapter extends ArrayAdapter<Category> {
private Context mContext;
int mResource;
public CategoryListAdapter(Context context, int resource, ArrayList<Category> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String name = getItem(position).getName();
Category category = new Category(name);
final LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
Button catName = convertView.findViewById(R.id.btnNextTbl);
catName.setText(name);
catName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 0) {
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
mContext.startActivity(intent);
} else {
Toast toast = Toast.makeText(getContext(), "Clicked2", Toast.LENGTH_SHORT);
toast.show();
}
}
});
return convertView;
}
}
(I commented above the erroneous piece of code)
All Tools Table:
public class AllToolsTable extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_tools_table);
}
public static Intent makeIntent(Context context) {
return new Intent(context, AllToolsTable.class);
}
}
I will provide any other relevant code/details if needed.
Any help will be greatly appreciated.
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
Your AllToolsTable.makeIntent() method requires a Context argument. Normally you'd be fine with something like AllToolsTable.makeIntent(MainActivity.this) because Activity is a subclass of Context. However, CategoryListAdapter is not.
So you need to get your hands on a Context object somehow.
Luckily, the getView() method passes you a non-null ViewGroup parent object, and all views have a context. So you can replace your intent creation with this code:
Context context = parent.getContext();
Intent intent = AllToolsTable.makeIntent(context);
Related
I need to display name, phoneNumber and accountNumber in EditText in the class ConsumerdescAndEdit, so how do pass these values when OnItemClickListener is executed?
ShowAll.java:
I have the ListView that inflated from CustomAdapter.
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
startActivity(intent);
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects){
this.objects = objects;
this.mContext = context;
}
public CustomAdapter(){
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout,null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
return convertView;
}
}
ConsumerDescAndEdit.java (where do I need to use variables):
public class ConsumerDescAndEdit extends AppCompatActivity {
Button updateButton;
EditText nameEditTextVar;
EditText phoneEditTextVar;
EditText accountEditTextVar;
// Variables to store user inputted data.
String nameEdit;
String phoneEdit;
String accountEdit;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_desc_and_edit);
dbHelper = new DatabaseHelper(this);
updateButton = findViewById(R.id.updateButton);
nameEditTextVar = findViewById(R.id.nameEditScreen);
phoneEditTextVar = findViewById(R.id.phoneNumberEditScreen);
accountEditTextVar = findViewById(R.id.accountNumberEditScreen);
String s_intent = getIntent().getStringExtra("EXTRA_SESSION_ID");
nameEditTextVar.setText(s_intent);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameEdit = nameEditTextVar.getText().toString();
phoneEdit = phoneEditTextVar.getText().toString();
accountEdit = accountEditTextVar.getText().toString();
if (nameEdit.isEmpty() || phoneEdit.isEmpty() || accountEdit.isEmpty()) {
Toast.makeText(ConsumerDescAndEdit.this, "Data Insufficient", Toast.LENGTH_SHORT).show();
} else {
boolean b = dbHelper.updateData(nameEdit, phoneEdit, accountEdit);
if (b)
Toast.makeText(ConsumerDescAndEdit.this, "Data updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(ConsumerDescAndEdit.this, "Could not update data", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When you create the Intent for the edit Activity, add the data from the selected item as "extras" to the Intent, like this:
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
intent.putExtra("name", name);
intent.putExtra("phone", phone);
intent.putExtra("account", account);
startActivity(intent);
In the edit Activity, extract the data from the Intent like this:
String name = intent.getStringExtra("name");
String phone = intent.getStringExtra("phone");
String account = intent.getStringExtra("account");
Try below code
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
private ItemClickListener itemClickListener;
public interface ItemClickListener {
void onItemClick(Consumer consumer);
}
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects, ItemClickListener itemClickListener) {
this.objects = objects;
this.mContext = context;
this.itemClickListener = itemClickListener;
}
public CustomAdapter() {
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout, null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(consumer);
}
}
});
return convertView;
}
}
In Activity do following
public class ConsumerActivity extends AppCompatActivity implements CustomAdapter.ItemClickListener {
CustomAdapter adapter;
ArrayList<Consumer> objects;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer);
adapter = new CustomAdapter(this, objects, this);
}
#Override
public void onItemClick(Consumer consumer) {
Intent intent = new Intent(this, CustomerEdit.class);
intent.putExtra("Consumer", consumer);
startActivity(intent);
}
}
I've the following Activity that uses a ListView to display a list of subjects. Each row has a textview which is set to red to indicate the question for that subject has not yet been answered. When the user clicks on a row it should launch an Activity that asks a question on that subject.
I want to launch the Activity by calling startActivityForResult, this will update the row with the fact the question has been asked and turn the textview green.
My question is how to update a particular row in the listview from onActivityResult?
public class QuestionListForInTransaction extends ActionBarActivity {
ListView listView;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.questionlistforintxlayout);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
setTitle("Call Question(s)");
listView = (ListView)findViewById(R.id.txinquestionlist);
String[] values = new String[] { "Are you the driver?", "Question 2", "Question 3", };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(listener);
}//end of onCreate
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.questionlisttxinrowlayout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.questionlisttxinrowlayout, parent, false);
TextView question = (TextView) rowView.findViewById(R.id.tvquestionforintx);
question.setText(values[position]);
TextView answered = (TextView) rowView.findViewById(R.id.rowstatusbox);
answered.setBackgroundColor(Color.RED);
String questionStr = values[position];
rowView.setTag(questionStr);
return rowView;
}
} //end of adapter class
OnItemClickListener listener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(QuestionListForInTransaction.this, "pos = " + position, Toast.LENGTH_LONG).show();
String question = (String)view.getTag();
if(question.equalsIgnoreCase("Are you the driver?")){
//Toast.makeText(QuestionListForInTransaction.this, "Are you the driver?" + position, Toast.LENGTH_LONG).show();
final int QUESTION_REQUEST = 1;
Intent questionIntent = new Intent(QuestionListForInTransaction.this, Question.class);
startActivityForResult(questionIntent, QUESTION_REQUEST);
//TextView answered = (TextView) view.findViewById(R.id.rowstatusbox);
//answered.setBackgroundColor(Color.GREEN);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
if(extras != null)
int result = extras.getInt("result");
//*********************update a row green**********************
}
} //end of class
Just Create some custom wrapper class like this:
public class QuestionWrapper {
private String mQuestionText;
private boolean mIsAsked;
public QuestionWrapper(String defaultQuestionText, boolean isAsked) {
mQuestionText = defaultQuestionText;
mIsAsked = isAsked;
}
public boolean isAsked() {
return mIsAsked;
}
public void setIsAswked(boolean isAsked) {
mIsAsked = isAsked;
}
public String getQuestionText() {
return mQuestionText;
}
}
then you need to set List of this wrappers to Adapter:
public class QuestionListForInTransaction extends ActionBarActivity {
List<QuestionWrapper> mWrappers = new ArrayList<>();
MySimpleArrayAdapter mAdapter;
....
public void onCreate(Bundle icicle) {
....
wrappers.add(new QuestionWrapper("Are you the driver?",false));
wrappers.add(new QuestionWrapper("Question 2",false));
wrappers.add(new QuestionWrapper("Question 3",false));
mAdapter = new MySimpleArrayAdapter(this, wrappers);
....
and Update Your Adapter like this:
public class MySimpleArrayAdapter extends ArrayAdapter<QuestionWrapper> {
private final Context context;
private final List<QuestionWrapper> mWrappers;
public MySimpleArrayAdapter(Context context, List<QuestionWrapper> wrappers) {
super(context, R.layout.questionlisttxinrowlayout, wrappers);
this.context = context;
this.mWrappers = wrappers;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.questionlisttxinrowlayout, parent, false);
QuestionWrapper wrapper = mWrappers.get(position);
TextView question = (TextView) rowView.findViewById(R.id.tvquestionforintx);
question.setText(wrapper.getQuestionText());
TextView answered = (TextView) rowView.findViewById(R.id.rowstatusbox);
if (wrapper.isAsked()) {
answered.setBackgroundColor(Color.GREEN);
} else {
answered.setBackgroundColor(Color.RED);
}
rowView.setTag(wrapper.getQuestionText());
return rowView;
}
onActivityResult - Need to update your wrapper class and adpater:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
....
mWrappersList.get(yourPosition).setAsked(true/false);
if (mAdapter!=null){
mAdapter.notifyDataSetChanged();
}
...
}
I think for RequestCode in startActivityForResult you can use Adapter click position.
Hi I want to add an item to a listview.
This is my New message activity in which I wan to pass an item to my Main Activity. I'm not quite sure how to pass this data through an intent any help would be greatly appreciated.
public class NewMessage extends ActionBarActivity {
EditText new_message;
Button post_new_message_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_message);
new_message = (EditText) findViewById(R.id.message_content);
post_new_message_button = (Button) findViewById(R.id.message_send);
post_new_message_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView username = (TextView) findViewById(R.id.conversation_username2);
itemAdapter.add(new MessageItem(1656,"Bill Smith", "image", DateTime.now(), new_message.getText().toString()));
itemAdapter.notifyDataSetChanged();
if (v.getId() == R.id.message_send);
new_message.setText("");
}
});
}
}
This is my main activity I want to pass in the data
public class MainActivity extends ActionBarActivity {
TextView threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newMessage = (Button) findViewById(R.id.new_message_button);
newMessage.setOnClickListener (new View.OnClickListener(){
#Override
public void onClick(View v){
Intent newMessage = new Intent(MainActivity.this, NewMessage.class);
startActivity(newMessage);
}
});
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
listView.setAdapter(itemAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
listView.getAdapter().getItem(position);
}
});
}
// Get dummy data for Activity Feed
public ArrayList<MessageItem> MessageFeedData() {
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
items.add(new MessageItem(1, "Bob Doe", "image", DateTime.now(), "Hello how are you?"));
items.add(new MessageItem(200, "John Smith", "image", DateTime.now(), "Hello what are you doing"));
return items;
}
class ActivityFeedTask extends AsyncTask<Integer, Void, Void> {
ArrayList<MessageItem> recentTracks;
}
public class ActivityAdapter extends ArrayAdapter<MessageItem> {
private final Context context;
private final ArrayList<MessageItem> items;
//private int currentPage = 0;
public ActivityAdapter(Context context, ArrayList<MessageItem> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = getLayoutInflater().inflate
(R.layout.message_list_item, parent, false);
//final MessageItem item = items.get(position);
rowView = convertView;
TextView comment2 = (TextView) rowView
.findViewById(R.id.messaging_username);
comment2.setText(items.get(position).Username);
ImageView comment3 = (ImageView) rowView
.findViewById(R.id.messaging_photo);
if (items.get(position).Image == null) {
comment3.setImageResource(R.drawable.ic_launcher);
}
TextView comment4 = (TextView) rowView
.findViewById(R.id.messaging_date);
comment4.setText(items.get(position).DateTimeStamp.toString());
TextView comment5 = (TextView) rowView
.findViewById(R.id.messaging_string);
comment5.setText(items.get(position).MessageString);
}
return convertView;
}
}
}
if you just want to pass data back and forth between the two activities, maybe you should use:
startActivityForResult(Intent intent, int requestCode)
and
onActivityResult(int requestCode, int resultCode, Intent data)
So that when the NewMessageActivity finishes, it can send the data back to the main activity.
I don't know neither how to write my question so I hope you will understand from my code:
So i have this EXAMPLE code:
MAIN:
public class ListImageButton extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
//HERE THIS IS WORKING
boolean_toast = false;
timer.cancel();
zanimivosti.cancel();
Intent intent = new Intent(ListImageButton.this,
ANOTHER_ACTIVITY.class);
startActivity(intent);
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
And the ADAPTER:
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
//HERE THIS IS NOT WORKING
boolean_toast = false;
timer.cancel();
zanimivosti.cancel();
Intent intent = new Intent(ListImageButton.this,
ANOTHER_ACTIVITY.class);
startActivity(intent);
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
So I would like to stop some timers and cancel some toast that I have in the main activity/class, and also I would like to start a new activity.
Ok I thought about it and the answer was very simple..looks like I was to tired to think about it..
I made this function in the main activity:
public static void preklopi() {
boolean_toast = false;
cas = 0;
perioda = 0;
timer.cancel();
zanimivosti.cancel();
Intent intent = new Intent(Context, kasper.api.Najdi_osebo.class);
Context.startActivity(intent);
}
And then I called the function from main activity in the other class..
Please tell me how to add items in listview arrayadapter?
I found only how to make for standard adapter
Activity:
public class Activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.m);
ListView lv=(ListView) findViewById(R.id.lv);
String[] Id1={"1","2","3"}, Text1={"one","two","three"};
CustomAdapter ad = new CustomAdapter(this, Id1 , Text1);
ad.setCustomListener(new LVListener() {
public void onClick(String text) {
Log.d("APP", text);
}
});
lv.setAdapter(ad);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setVisibility(View.GONE);
String[] Id2={"4","5","6"},Text2={"four","five","six"};
// add Id2 and Text2 in listview
}
});
}
}
CustomAdapter:
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] id, text;
private ListViewListener micl;
public CustomAdapter(Context context, String[] id, String[] text) {
super(context, R.layout.list, id);
this.context = context;
this.id = id;
this.text = text;
}
public void setCustomListener(ListViewListener micl) { this.micl = micl; }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View View = inflater.inflate(R.layout.list, parent, false);
final int pos = position;
final TextView tView = (TextView) View.findViewById(R.id.textView);
tView.setText(text[pos]);
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (micl != null)
micl.onClick(text[pos]);
}
});
return View;
}
}
I tried to do with notifyDatasetChanged() but nothing happened.
Please tell me how to do that.
ArrayAdapter has the add method, but in order to use it the dataset you provide to the super can not be an array, that's because the using Arrays.asList(objects), that returns an immutable list. From the documentation
Returns a List of the objects in the specified array. The size of the
List cannot be modified, i.e. adding and removing are unsupported, but
the elements can be set. Setting an element modifies the underlying
array.