Unable to instantiate activity Component, ClassCastExceptioI'm new to android and so i followed different tutorials to accomplish my task. I'm having an error and despite all efforts it's still unable to resolve. I've a main activity through which i call a positive active(if user selects "yes" on alert). The positive activity basically contains a listView of three items and i want to display the contacts of mobile when user clicks on the first item.
I put the code of contacts retrieving in the fragment class but it's giving the error of casting even when i didn't use simple intent to call the fragment.
The code for main activity is as follows:
public class activity_home extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Context context = this;
new AlertDialog.Builder(context)
.setTitle("Alert")
.setMessage("Do you want to enable the app right now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id) {
// go to a new activity of the app
Intent positiveActivity = new
Intent(getApplicationContext(),
PositiveActivity.class);
startActivity(positiveActivity);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setNeutralButton("Remind Me later", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
// do nothing
}
}
)
.
setIcon(android.R.drawable.ic_dialog_alert)
.show();
}}
PositiveActivity.java:
public class PositiveActivity extends FragmentActivity {
ListView listView;
ArrayList<String> listname;
ArrayList<String> list_no;
Context context;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.positive_view);
Context context = this;
listView = (ListView) findViewById(R.id.mobile_list);
TextView textView = new TextView(context);
textView.setTypeface(null, Typeface.BOLD);
textView.setHeight(100);
textView.setText("Define Specifications for Enabling Auto Pickup!");
listView.addHeaderView(textView);
// Array of strings...
String[] mobileArray = new String[] {"Add Numbers to the list","Select
Timer","Pick Selection Mode"};
final ArrayAdapter <String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
mobileArray);
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String)
listView.getItemAtPosition(position);
if (itemPosition == 1) {
ContactListFragment fragmentS1 = new ContactListFragment();
getSupportFragmentManager().beginTransaction().replace
(R.id.headlines_fragment,
fragmentS1).commit();
}}});}}
And the code of Fragment:
import android.support.v4.widget.SimpleCursorAdapter;
public class ContactListFragment extends ListFragment implements
LoaderCallbacks<Cursor> {
private CursorAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create adapter once
Context context = getActivity();
int layout = android.R.layout.simple_list_item_1;
Cursor c = null; // there is no cursor yet
int flags = 0; // no auto-requery! Loader requeries.
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// each time we are started use our listadapter
setListAdapter(mAdapter);
// and tell loader manager to start loading
getLoaderManager().initLoader(0, null, this);
}
// columns requested from the database
private static final String[] PROJECTION = {
Contacts._ID, // _ID is always required
Contacts.DISPLAY_NAME_PRIMARY // that's what we want to display
};
// and name should be displayed in the text1 textview in item layout
private static final String[] FROM = { Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Once cursor is loaded, give it to adapter
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// on reset take any old cursor away
mAdapter.swapCursor(null);
}
}
I'll be grateful if someone points out the mistake in code
try using add instead of replace
getSupportFragmentManager().beginTransaction().add
(R.id.headlines_fragment, fragmentS1).commit();
Related
Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
I was recently working on a todo list application in android studio where the user will input text through an EditText, and then the String will be added to a listView as shown below.
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<>();
itemsAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
itemsAdapter.notifyDataSetChanged();
return true;
}
});
}
public void addTask(View v) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add a New Task");
dialogBuilder.setMessage("Enter what you want to do");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String itemText = edt.getText().toString();
itemsAdapter.add(itemText);
edt.setText("");
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
But the problem I have is that when the user closes the activity, the state of the ListView will change back to it's original value.
I want the ListView to retain the Information that has been put inside it when the activity closes.
How do I go about this?
There are many ways to save data in your app.
You can use the following options:
SharedPreferences
Files
SQLite (with plain sql or with the framework Room)
For more information check this link : https://developer.android.com/training/data-storage/index.html
Usually for this situation using Sqlite
But you can use others way such as Shared preference or File
Like you can see here: https://developer.android.com/guide/topics/data/data-storage.html
I'm making a simple to do list and I want to be able to click on the item and enter a new text which will then replace the text of the TextView in that cell. I've got the dialogAlert working, I just don't know how to grab the cell's TextView and change it
This is what the Activity looks like,
public class MainActivity extends AppCompatActivity {
private ListDataSource ds;
private ListView listViewToDo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context context = this;
Log.d("MainActivity","Attempting to create data source");
try {
ds = new ListDataSource();
}
catch(Exception e)
{
e.printStackTrace();
Log.d("MainActivity","Failed to create data source");
}
Log.d("Main Activity","Attempting to link empty list view to on screen view");
listViewToDo = (ListView)findViewById(R.id.listOfLists);
Log.d("Main Activity","Views linked, Attempting to set adapter to listView");
listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds));
Log.d("Main Activity", "Successfully set Adapter");
// add button listener
listViewToDo.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
AlertDialog.Builder editItem = new AlertDialog.Builder(context);
final EditText edittext = new EditText(context);
editItem.setTitle("Change Item");
editItem
.setMessage("Set new todo item")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//what do I put here?
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alertDialog = editItem.create();
alertDialog.show();
}
});
}
}
ds.remove(position);
ds.add(position,edittext.getText().toString().trim())
ListDataSourceAdapter adapter = new ListDataSourceAdapter(this, ds)
listViewToDo.setAdapter(adapter );
adapter.notifDataSetChanged();
I want to Edit my ListView items. for example; I have a listView item i clicked this item and I add string value with edit text afterwards I again click this item and I add new string value alongside to previous string value, and again, again, again. When I click this item I want edit this listitem. How I do that?
Java sourcecode:
public class MainActivity extends Activity {
TextView tvDers;
EditText etDers, etDersSaati;
EditText etNot;
LinearLayout LayoutDers;
ArrayAdapter<String> adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
}
});
list.setAdapter(adapter);
final AlertDialog alertDers = build.create();
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
}
Save item values in ordering Collection. Set this collection in adapter. Add and remove this values and after call notifyDataSetChanged for adapter.
Try like this.
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String item = (String) parent.getItemAtPosition(int position);
item += "YourText";
ArrayAdapter adapter = (ArrayAdapter ) parent.getAdapter();
adapter.insert(item, position);
}
Sorry, but now I can't test this code. So I can not say for sure that it is correct. Try different variants and you'll get.
UPDATE
From dialog clickListener you can try this:
#Override
public void onClick(DialogInterface dialog, int which) {
ArrayAdapter adapter = (ArrayAdapter ) listView.getAdapter();
String item = (String) listView.getSelectedItem();
item += "YourText";
adapter.insert(item, position);
}