I'm trying to pass a value from an ArrayList in one Activity (LensActivity) to a TextView on my MainActivity. On this site i found the Intent method and was experimenting with that, but seem unable to pass it, the info is getting fetched in the String lensString, and passed to the Intent, but in Main Activity seems to not be passing or getting on the TextView, and in some experiments, since the getIntent is on MainActivity, i got a null pointer.
Here is the code for the LensActivity which has the Button that send the info.
package com.komorebiestudio.cam_report_funcionality;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class LensActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private LensAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private TextView LensChange;
private String lensString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lens_activity);
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
final ArrayList <LensItem> lensList = new ArrayList<>();
lensList.add(new LensItem(R.drawable.zeiss,"24mm","Zeiss Compact Prime"));
lensList.add(new LensItem(R.drawable.ic_camera,"35mm","Angenieux"));
lensList.add(new LensItem(R.drawable.cooke,"50mm","Cooke S5I"));
mRecyclerView = findViewById(R.id.lens_list);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new LensAdapter(lensList);
LensChange = findViewById(R.id.lensinfo);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
final Intent ChangeLens = new Intent(this, MainActivity.class);
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
startActivity(new Intent(LensActivity.this,MainActivity.class));
}
});
}
}
and here is the code of the MainActivity that receives it.
package com.komorebiestudio.cam_report_funcionality;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements FpsDialog.FpsDialogListener{
private TextView textViewinfo1;
private Button button1;
private Button lensButton;
private TextView lensInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lensInfo = findViewById(R.id.lensinfo);
lensInfo.setText(getIntent().getStringExtra("LensIntent"));
textViewinfo1 = findViewById(R.id.info1);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
openDialog();
}
});
lensButton = findViewById(R.id.lensbutton);
lensButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,LensActivity.class));
}
});
}
public void openDialog(){
FpsDialog fps_dialog = new FpsDialog();
fps_dialog.show(getSupportFragmentManager(),"Fps Dialog");
}
#Override
public void applyText(String fpsinfo) {
textViewinfo1.setText(fpsinfo);
}
}
In your LensActivity, you're creating an Intent that you never use. The Intent is this one:
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
Instead, you should create it in the Item Click Listener. Just remove the code above, and modify the listener in this way:
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
startActivity(lensIntent);
}
});
You need to use the putExtra method after you assign a value to the variable lensString
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
lensIntent.putExtra("LensIntent",lensString);
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
// Notice that you are not using your previously created intent in you
// original code.
startActivity(lensIntent);
}
});
Related
I have an android studio assignment that requires us to create 3 activities, one of these activities has a spinner and text and we must pass the text and selected spinner value from the activity to another activity to show the input I figured out how to pass the text but I can't quite figure how to do the same to the spinner. this is the spinner code.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class Homepage<adapter> extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button btn;
EditText et;
String st;
String selectedItem="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
btn = findViewById(R.id.Btnstart);
et = findViewById(R.id.Std_Name);
Spinner spinner = findViewById(R.id.major_spinner);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Homepage.this, Input.class);
st = et.getText().toString();
i.putExtra("Value", st);
startActivity(i);
finish();
}
});
/**
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Homepage.this, Input.class);
selectedItem = spinner.getSelectedItem().toString();
intent.putExtra("selectedItem", selectedItem);
startActivity(intent);
}
});
**/
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.majors, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Move your text variable to the scope of the activity and pass in the Intent, like you did with your st variable.
So I'm adding an expandable fab, but I'm having this error and I don't understand why...
this is the exact error in log:
ava.lang.ClassCastException: com.nambimobile.widgets.efab.ExpandableFabLayout cannot be cast to com.nambimobile.widgets.efab.ExpandableFab
at CategoryActivity.onCreate(CategoryActivity.java:56)
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class CategoryActivity extends AppCompatActivity implements CategoryAdapter.onCategoryClickListener {
public static final String CATEGORY_NAME = "category_name";
private NoteViewModel noteViewModel;
private CategoryAdapter adapter;
private RecyclerView recyclerView;
private List<FolderWithNotes> folderWithNotes;
private Note note;
private Folder folder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteViewModel = new ViewModelProvider.AndroidViewModelFactory(this.getApplication()).create(NoteViewModel.class);
recyclerView = findViewById(R.id.category_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
noteViewModel.getFolderWithNotes().observe(this, folderWithNotes -> {
});
ExpandableFab exFab = findViewById(R.id.exFab);
exFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case (R.id.exfab_add_category):
Intent intent = new Intent(CategoryActivity.this, AddCategoryActivity.class);
startActivity(intent);
case (R.id.exfab_delete_category):
default:
break;
}
}
});
ActivityResultLauncher<Intent> launcher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
String category = data.getStringExtra(AddCategoryActivity.CATEGORY_REPLY);
String notes = data.getStringExtra(AddNoteActivity.NOTE_REPLY);
Folder folder = new Folder(note.getFolder_name());
noteViewModel.insert(folder, note);
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter = new CategoryAdapter(folderWithNotes, this, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCategoryClick(int position) {
// code to transfer to AddNoteActivity (where the note list is) by clicking the category folder
noteViewModel.getFolderWithNotes().observe(this, folderWithNotes -> {
Intent intent = new Intent(CategoryActivity.this, NotesActivity.class);
intent.putExtra(CATEGORY_NAME, folderWithNotes.get(position).getFolder().getFolderName());
});
}
public void addCategoryClicked(View view) {
EditText editCategory = findViewById(R.id.et_add_category);
String categoryTitle = editCategory.getText().toString().trim();
Intent intent = new Intent(CategoryActivity.this, AddCategoryActivity.class);
}
public void deleteCategoryClicked(View view) {
}
// #Override
// public void addCategoryClicked(int position) {
//
// }
//
}
I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted to create a button that should delete the listview item that was clicked on. Here is the code I came with.
MainActivity
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
ArrayList<String> new_post = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView post_view = findViewById(R.id.news_feed);
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
//create click event and pass values of arrays
post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
intent.putExtra("Subject", new_subject);
intent.putExtra("Post", new_post);
intent.putExtra("position", id);
// getApplicationContext().startActivity(intent);
startActivityForResult(intent, 2);
}
});
//create button connection and create keylistener
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final ListView post_view = findViewById(R.id.news_feed);
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
//get subject and post from second activity
String new_subject_value = data.getStringExtra("newSubject");
String new_post_value = data.getStringExtra("newPost");
new_subject.add(new_subject_value);
new_post.add(new_post_value);
newslist_adapter = new ArrayAdapter<>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
if (requestCode == 2) {
if(resultCode == Activity.RESULT_OK){
String item2delete = data.getStringExtra("id");
new_subject.remove(item2delete);
newslist_adapter = new ArrayAdapter<>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
}
}
SecondActivity
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class full_post_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_post_activity);
final int id = getIntent().getExtras().getInt("id");
//create view reference
final TextView subject_edit = findViewById(R.id.subject_input);
final TextView post_edit = findViewById(R.id.post_input);
//create button reference
Button delete_button = findViewById(R.id.full_post_delete_btn);
//create click event
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("id", id);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");
String subject_string = subject_array.get(0);
String post_string = post_array.get(0);
//set textview text
subject_edit.setText(subject_string);
post_edit.setText(post_string);
}
}
My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?
You cannot get id value to MainActivity. This line in second activity cause problem
final int id = getIntent().getExtras().getInt("id");
In Main Activity, You can put id value using name index "position"
intent.putExtra("position", id);
So you should change them to
In Second Activity
final int id = getIntent().getExtras().getInt("position");
or Main Activity
intent.putExtra("id", id);
UPDATED try this in Main Activity
intent.putExtra("id", position);
If you want to stay in the activity where the delete button is I would suggest creating a getter and a setter for the list behind your ListView(Easily generate them with ALT+INSERT).
You can then make an instance of your MainActivity inside the delete_buttons OnClick methode and get said List with the getter.
Remove the Item you need to remove and update the list with your setter, again using your MainActivity instance.
Edit: here are some code samples
Getter and Setter:
public ArrayList<String> getNewPost() {
return this.new_post;
}
public void setNewPost(ArrayList<String> np) {
this.new_post = np;
}
delete_button OnClick methode:
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity main=new MainActivity();
ListView<String> np=main.getNewPost();
np.remove("StringToRemove");
main.setNewPost(np);
}
});
I would also suggest you to make a back_button to check if the list was updated, you can use your old delete_button onclick for that.
I'm trying to pass data from a custom listview to a new activity and populate its TextViews. It does work but it always takes the first position that was added and passes it through. How do I get it to pass the data clicked on?
MainActivity
package uk.co.jaunt_app.jaunt;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
import static uk.co.jaunt_app.jaunt.R.id.Posts;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton addmap;
private Button settingbtn;
private TextView mNameTextView;
private TextView mEmailTextView;
ListView mPosts;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ArrayAdapter<String> adapter;
private FirebaseAuth auth;
private ArrayList<feed> feedPop = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.jauntlogodark);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase(Config.FIREBASE_URL);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uid = currentFirebaseUser.getUid();
Firebase usersRef = ref.child("Users").child(uid).child("name");
Firebase emailRef = ref.child("Users").child(uid).child("email");
Firebase postRef = ref.child("Users").child(uid).child("Maps");
postRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (final DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
final String mapName = person.getMapName();
final String mapid = person.getMapID();
final String mapStartLat = person.getStartLat();
final String mapStartLong = person.getStartLong();
final String mapEndLat = person.getEndLat();
final String mapEndLong = person.getEndLong();
adapter.notifyDataSetChanged();
feedPop.add(
new feed(mapName, mapStartLat, mapStartLong, mapEndLat, mapEndLong));
final ArrayAdapter<feed> adapter = new feedArrayAdapter(MainActivity.this, 0, feedPop);
ListView listView = (ListView) findViewById(R.id.customListView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this, ViewUserMapActivity.class);
intent.putExtra("mapName", mapName.toString());
intent.putExtra("mapStartLat", mapStartLat.toString());
intent.putExtra("mapStartLong", mapStartLong.toString());
intent.putExtra("mapEndLat", mapEndLat.toString());
intent.putExtra("mapEndLong", mapEndLong.toString());
startActivity(intent);
}
});
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(),
"Cancelled", Toast.LENGTH_LONG)
.show();
}
});
//create property elements
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mPosts = (ListView) findViewById(Posts);
mPosts.setAdapter(adapter);
List<Nav> navList= new ArrayList<Nav>();
navList.add(new Nav("Profile"));
navList.add(new Nav("Feed"));
navList.add(new Nav("Maps"));
navList.add(new Nav("Most Popular"));
navList.add(new Nav("Settings"));
navList.add(new Nav("Report a Bug"));
ArrayAdapter<Nav> navadapter = new ArrayAdapter<Nav>(this,android.R.layout.simple_list_item_1, navList);
final ListView lv= (ListView) findViewById(R.id.left_drawer);
lv.setAdapter(navadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition = position;
switch(itemPosition) {
case 0:
Intent menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 1:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 2:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 3:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 4:
menuItem = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(menuItem);
break;
case 5:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
}
}
});
mNameTextView = (TextView) findViewById(R.id.NameTextView);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue(String.class);
mNameTextView.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mEmailTextView = (TextView) findViewById(R.id.EmailTextView);
emailRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
mEmailTextView.setText(email);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
addmap = (FloatingActionButton) findViewById(R.id.add_map);
addmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Answers.getInstance().logCustom(new CustomEvent("Added Map"));
Intent intent = new Intent(MainActivity.this, MapStartActivity.class);
startActivity(intent);
}
});
settingbtn = (Button) findViewById(R.id.settingbtn);
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu_drawer, menu);
return true;
}
}
//custom ArrayAdapter
class feedArrayAdapter extends ArrayAdapter<feed>{
private Context context;
private List<feed> feedPop;
//constructor, call on creation
public feedArrayAdapter(Context context, int resource, ArrayList<feed> objects) {
super(context, resource, objects);
this.context = context;
this.feedPop = objects;
}
//called when rendering the list
public View getView(int position, View convertView, ViewGroup parent) {
//get the property we are displaying
feed feed = feedPop.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.feed_listview, null);
TextView others = (TextView) view.findViewById(R.id.others);
TextView mapname = (TextView) view.findViewById(R.id.address);
//set address and description
String completeOthers = feed.getFeedStartLat() + ", " + feed.getFeedStartLong() + ", " + feed.getFeedEndLat() + ", " + feed.getFeedEndLong();
others.setText(completeOthers);
//set address and description
String completeAddress = feed.getFeedName();
mapname.setText(completeAddress);
return view;
}
}
Get value from ArrayList based on position then pass to activity
intent.putExtra("mapName", feedPop.get(position).getmapName().toString());
I am working on an app with tab views that needs the Android app combat theme. I want to implement a listview in this app. However, I need to extend the Main Activity Class with the AppCombat Activity Class and the List Activity Class, to get both working - which is not possible in one class, as far as I know. I´m a bit stuck here and any help would be appreciated.
MainActivity.class
package com.example.TodoList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.TodoList.db.TaskContract;
import com.example.TodoList.db.TaskDBHelper;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ListAdapter listAdapter;
private TaskDBHelper helper;
private Toolbar toolbar;
private Button btnIconTextTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateUI();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnIconTextTabs = (Button) findViewById(R.id.btnIconTextTabs);
btnIconTextTabs.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText inputField = new EditText(this);
builder.setNegativeButton("Cancel", null);
switch (item.getItemId()) {
case R.id.action_add_task:
builder.setTitle("Add an article to your shopping list");
builder.setMessage("What would you like to add?");
builder.setView(inputField);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK, task);
db.insertWithOnConflict(TaskContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
builder.create().show();
return true;
case R.id.action_remove_task:
builder.setTitle("Remove an article from the shopping list");
builder.setMessage("Did you found this article?");
builder.setNegativeButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
updateUI();
}
});
case R.id.action_show_mylocation:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
//Intent intent=new Intent(this,LbsGeocodingActivity.class);
//startActivity(intent);
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
MainActivity.this.startActivity(GeoLocationIntent);
}
builder.create().show();
return true;
}
private void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
public void onSubmitPriceClick(View view) {
Intent SubmitPriceIntent = new Intent(MainActivity.this, SubmitPriceActivity.class);
MainActivity.this.startActivity(SubmitPriceIntent);
}
public void onScrollViewButtonClick(View view) {
Intent SubmitPriceIntent = new Intent(MainActivity.this, IconTextTabsActivity.class);
MainActivity.this.startActivity(SubmitPriceIntent);
}
public void onWebViewButtonClick(View view) {
Intent intent = new
Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.batprice.com:1337"));
startActivity(intent);
finish();
}
public void onGeoLocationButtonClick(View view) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
MainActivity.this.startActivity(GeoLocationIntent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnIconTextTabs:
startActivity(new Intent(MainActivity.this, IconTextTabsActivity.class));
break;
}
}
}
I get the error "Cannot resolve method 'setListAdapter(android.widget.ListAdapter)'.
How can I solve this problem?
You are extending AppCompatActivity not ListActivity, AppCompatActivity does not inherently implement a ListView, so there is no setListAdapter() method. You need to either extend ListActivity (which does not extend AppCompatActivity, so this may not be preferable) or put a ListView in your layout and call setAdapter() on your ListView. Something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(listAdapter);
...
}
Or you can use an android.support.v4.app.ListFragment, which is implemented in a similar manner to ListActivity.