Information from another activity - java

I've been searching my problem but i can't find anything that helps my case.
I have an activity with a ListView where you can see names of people in a Database and when you click in one of the name it should go to another activity to show the details but it crashes when i click the name. Code above:
First Activity:
Code that shows all the names in ListView is working
myview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "clicked", 3000).show();
setContentView(R.layout.fragment_vertodos);
lv=(ListView) findViewById(R.id.listone);
Cursor cursor=mydb.rawQuery("SELECT * FROM teste;", null);
if(cursor.moveToFirst()){
Toast.makeText(getApplicationContext(), "Nome:", 3000).show();
data.clear();
do{
data.add(cursor.getString(cursor.getColumnIndex("name")));
}while (cursor.moveToNext());
ArrayAdapter <String> adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data);
lv.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor.close();}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position,long id) {
// TODO Auto-generated method stub
String name = (String) l.getItemAtPosition(position);
List<String> emailLists = new ArrayList<String>();
emailLists.add(cursor.getString(cursor.getColumnIndex("email")));
String email = emailLists.get(position);
Intent intent = new Intent(MainActivity.this, Detalhes.class);
intent.putExtra("name",name);
intent.putExtra("email",email);
startActivity(intent);
}
});
My question is now. i created a second activity that get's the information but it's giving an error:
Second Activity:
txname = (TextView)findViewById(R.id.txtnome);
txmail = (TextView)findViewById(R.id.txtmail);
Bundle b = getIntent().getExtras();
if(b!=null){
String n =(String) b.get("name");
String m =(String) b.get("email");
txname.setText(n);
txmail.setText(m);
}
The first error is:
java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor

The first error is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
Issue is your trying to type cast the String to Cursor at this line
Cursor detalhes = (Cursor) l.getItemAtPosition(position);
getItemAtPosition will return the data associated with the specified position in the list.
So, in your case your have passed List<String> data as the data for the list items. so each item will have as string object
String name = (String) l.getItemAtPosition(position);
If you need to pass the email of that items. You can create a ArrayList for email and add it from database like this.
List<String> emailLists = new ArrayList<String>();
And, add the emails into the list
data.add(cursor.getString(cursor.getColumnIndex("email")));
Now, When the item selected, get the email from the ArrayList
String email = emailLists.get(position);

I suspect you are setting an ArrayAdapter<String> to your ListView, so in the following line, l.getItemAtPosition(position) returns a String, not a Cursor, and the cast fails.
Cursor detalhes = (Cursor) l.getItemAtPosition(position);

Related

I cannot add items to my RecyclerView from another intent

I have two intents.
Main Activity: Containing the Recycler View, showing some default items to make sure it works. An ArrayList is set to the Recycler View, which is the List containing those default items.
Second Activity: A button which will collect the data on the same page and put the data into an object, the object will be added into the Arraylist which set to the Recycler View of the Main Activity.
I made some Toast Message to confirm the object in the 2nd Activity was added to the ArrayList.
//My item
public item(int id, int money, String date, String category, String
description) {
this.id = id;
Money = money;
Date = date;
Category = category;
Description = description;
}
Then I created a class to control my ArrayList
//Building ArrayList
public Util(){
Log.d(TAG, "Util: Start");
if(IncomeItems==null){
IncomeItems = new ArrayList<>();
initIncomeItems();
}
}
private static void initIncomeItems() {
Log.d(TAG, "initIncomeItems: initI");
int Iid = 0
int Money= 0;
String Date = "";
String Category= "";
String Description = "";
Iid++;
IncomeItems.add(new item(Iid, 10000, "8-Jun-2019", "Salary",
"Salary"));
}
//adding item to ArrayList
public boolean addIncomeItem(item Item){
Log.d(TAG, "addIncomeItem: addI");
return IncomeItems.add(Item);
}
//getting ArrayList
public static ArrayList<item> getIncomeItems() {
Log.d(TAG, "getIncomeItems: getI");
return IncomeItems;
}
I set my ArrayList to the RecyclerView in the Main Activity
//Recycler View in Main Activity
RVAdapter IncomeAdapter = new RVAdapter(this);
Util util = new Util();
MainIncomeRV.setAdapter(IncomeAdapter);
MainIncomeRV.setLayoutManager(new GridLayoutManager(this, 1));
IncomeAdapter.notifyDataSetChanged();
IncomeAdapter.setItems(util.getIncomeItems());
In the 2nd Activity, I have a button to create a new item by getting data from the user.(I skipped some Widgets intitiation code here). At last I add the item to the ArrayList which set to the Recycler View in the Main Activity.
//Button in 2nd Activity
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" +
date_month.getSelectedItem().toString() + "-" +
date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,
Integer.parseInt(Money.getText().toString()), Date,
IncomeCategories.getSelectedItem().toString(),
Description.getText().toString());
util=new Util();
util.addIncomeItem(IncomeItem);
Toast.makeText(IncomePage.this, IncomeItem.toString(),
Toast.LENGTH_SHORT).show();
Toast.makeText(IncomePage.this,
String.valueOf(util.getIncomeItems().size()), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: addI");
}
});
}
No error occurred, but the item(IncomeItem) created in the 2nd Activity cannot be added to the Main Activity.
I expected the item will show in the Recycler view when I return to the Main Activity. Is it the problem that I use the return button to go back to the Main Activity?
Following two points should work for you:
You should use same util object which is used in MainActivity
instead of creating new in submit button under 2nd Activity, So pass util object to
2nd activity.
Also pass adapter object to 2nd Activity, so that you can call NotifyDatasetChanged()
function after adding item.
This is how it should work. First create an arrayList in your 2ndActivity.
ArrayList<Item> str = new ArrayList<Item>();
In SubmitIncomeBtn,
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" + date_month.getSelectedItem().toString() + "-" + date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,Integer.parseInt(Money.getText().toString()), Date, IncomeCategories.getSelectedItem().toString(),Description.getText().toString());
str.add(IncomeItem) // add IncomeItem to arrayList
}
});
In 2ndActivity, you need to have this code to pass arrayList to MainActivity.
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("mylist", str);
setResult(1, intent);
}
Finally in MainActivity, add this code to receive data from 2ndActivity
onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
ArrayList<Item> myList = (ArrayList<Item>) getIntent().getSerializableExtra("mylist");
}
}
}

Add values to ArrayList from different activity

I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences

Delete item from both, database and listview on clicking Delete Button

I need to delete an item permanently from ListView and then from database. I have a DatabaseHandler.java class, which has the delete function as:
// Deleting single contact, in DatabaseHandler.java class
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
Then I have a FriendList.java class, when the user's friends are displayed as an item in ListView. When I long press on an item, then I get the option of "Delete" and "Cancel" in Dialog Box. Now, when I click on delete, the item is deleted from the ListView, but, not from the database. How can I delete it from database as well?
The code for getting the option of "Delete" and "Cancel"
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
Intent i = new Intent(FriendList.this, Delete_Confirm.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
//I am sending position of listitem in putExtra below//
i.putExtra("position", position);
startActivityForResult(i,CONFIRM);
item2 = (String) arg0.getItemAtPosition(position);
//Toast.makeText(FriendList.this, "Clicked"+item2, Toast.LENGTH_SHORT).show();
int l = item2.length();
c=0;
for(int j=0; j<=l; j++){
if(item2.charAt(j) != '9' || item2.charAt(j+1) != '1'){
c++;
}
else {
//Do nothing
break;
}
num = item2.substring(c, l);
}
Toast.makeText(FriendList.this, "Clicked: "+num, Toast.LENGTH_SHORT).show();
return true;
}
});
The corresponding code for onActivityResult is as follows:
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (CONFIRM) :
if(resultCode==RESULT_OK){
int posi = data.getIntExtra("position",0);
Log.d("msg","position is " + posi);
Log.d("msg","Do we reach here?");
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
//db.deleteContact(posi);
list.remove(posi);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
break;
}}
Please suggest how can I delete it from database as well. Any help would be highly appreciated.
EDIT:
On uncommenting db.deleteContact(posi), I get the following error:
The method deleteContact(Contact) in the type DatabaseHandler is not applicable for the arguments (int)
Note that the function deleteContact has contact variable of the type Contact.
Its a compilation error.
You need to pass a Contact object to the method, not an integer.
When you delete.... Try Deleting first from database then from ListView..
example:
db.deleteContact(list.get(posi)); // this will get string
list.remove(posi);
DatabaseHandler class.......
public void deleteContact(String name){
Log.d("Name:",""+ name);
db.delete(TABLE_CONTACTS, KEY_NAME + " = ?", new String[] { name });
}
You can delete from database first then from ListView. And suggest Iterator to remove list element.
I think the problem is that position is not the corresponding id in the database. A possible solution would be to add a tag with the database id of the contact you have in this listitem. And when you remove it you get the tag with the id and delete the item from the database.
Edit (added clarification):
I would add in your listviewadapter something like:
yourcontactview.setTag(contact.getId());
in which you add to your view a tag with the database id of the corresponding contact.
Then where you delete the contact I would get the contact you want to delete with something like this:
Contact deletecontact = db.getContact(view.getTag());
db.deleteContact(deletecontact);
Of course you could change your
deleteContact(Contact contact) to a method in which you give the id instead of the contactobject.
This should hopefully work.

Error comming on maketext in toast

public void onClick(View v) {
{
if (db==null) db = new DB(AddStation.this);
if(v.getId()==R.id.ADD ) {
String code = Scode.getText().toString().trim();
String name = SName.getText().toString().trim();
String fac = SFac.getText().toString().trim();
if(name.equals("")){
Scode.setError("Invalid name");
return;
}
if (code.equals("")){ Scode.setError("Invalid email");
return;
}
if (db.addStudent(code, name, fac))
Toast.makeText(AddStation.this, "Student added", Toast.LENGTH_SHORT).show();
else if (v.getId()==R.id.See) {
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_LONG).show();
//Log.v("EditText", db.getAllStudents().toString());
}
}
}
db.close();
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_SHORT).show();
}
}
AddStation is my Fragment name. how to solve this ?
this toast is retriving database and can u guys tell me how to bring data into a dropdown box or gridview instead of a toast. thanks!
Look at the last two lines. First you called db.close();, then called db.getAllStudents(), so ARE YOU KIDDING?
But if not this caused error, then post you logcat trace
PS:check your AddStation, is it extended from Activity or its descendants? If not, extend your AddStation from Activity or its descendants.
You can display this data in List/Spinner, for this you had to add these widgets in your layout. You can populate this data as
1. ListView
ListView listView = (ListView) findViewById(R.id.mylist);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item, listRecords);
listView.setAdapter(arrayAdapter);
2. Spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, listRecords);
spinner.setAdapter(arrayAdapter);

Fatal exception caused by android.os.NetworkOnMainThreadException

As I am a beginner to Android programming, I was trying to run some tutorials, but upon running the programs( the source code is available here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ) I got an error.
The program is supposed to read in data from a website and process it, but I think there is something wrong with the networking part.
I am fully aware there have been similar questions here on SO, yet I had no clue how to solve it, perhaps anyone could give solutions which I also can understand.
Strange NetworkOnMainThreadException in Android app?
This is a questions which was asked earlier and is identical to my problem, but I had no clue what they are trying to say there, i.e. "To fix you just need to move any thing that is touching the network to its own thread." makes no sense to me whatsoever..
Can anyone please shed some light on this?
Use an AsyncTask to move your network operation off of the main/ui thread and onto a background/worker thread.
Expanding on the example from the tutorial, wrap the JSON stuff inside of an anonymous AsyncTask:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Void, Void, JSONObject>() {
protected JSONObject doInBackground(Void... args) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
return jParser.getJSONFromUrl(url);
}
protected void onPostExecute(JSONObject json) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}.execute((Void) null);
}

Categories

Resources