My getter returns a wrong value - java

I'm programming an Android application and I got a little problem. I'm trying get a value from the Class A in the Class B but it doesn't return the correct value.
Here's my code to better understand (Sorry for my poor english)!
Class A
package com.androidhive.androidlistview;
//import
public class AndroidListViewActivity extends ListActivity {
int day;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
//prints 1 When I click on the first list item, 2 When I click on the second, ...
startActivity(i);
// sending data to new activity
i.putExtra("product", product);
}
});
}
public int getDay() {
return day;
}
}
Class B
package com.androidhive.androidlistview;
//import
#SuppressLint({ "NewApi", "HandlerLeak" })
public class SingleListItem extends Activity {
AndroidListViewActivity alva = new AndroidListViewActivity();
int day;
String url;
String code;
//others variables
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Graphic
new NetworkOperation().execute();
}
class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Document doc;
try {
day = alva.getDay();
System.out.println(day);
//prints 0
url = "http://www.planetehockey.com/calendrier.php?saison=45&div=9&club=&journee=" + day + "&jour=&mois=&page=0";
doc = Jsoup.connect(url).get();
//Récupère le texte d'une balise ayant bg_tableau pour class
Elements getId = doc.getElementsByClass("bg_tableau");
code = getId.text();
code = code + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
//other code
}
};
}
Thank's a lot for all your answers it helped me a lot:
How I solved the problem:
Class A
i.putExtra("product", product);
startActivity(i);
and:
Class B
int day = Integer.parseInt(i.getStringExtra("product").replaceAll("[^\\d.]", ""));

In your Class A, you're trying to bundle components AFTER the activity has been called.
put the call function like this..
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
i.putExtra("product", product);
startActivity(i);
The passes the parameter in a bundle to the called activity.
HTH!

There are two simple solutions for your problem,
1. Pass day values in intent to SingleListItem
Or
2. Make day as a Static member and use it with class Name like,
public static int day; and access it `AndroidListViewActivity.day`
and remove public int getDay() method from AndroidListViewActivity as in both activity it refers a different object of AndroidListViewActivity .

Try doing i.putExtra("product", product); before startActivity(i);

In your Activity A you have written the getter method but not setter method to set the value of day in your code. Just write the setter method also and set the value of day.
public void setDay(int p_day)
{
day=p_day;
}
Make the variable day as static. After setting the day value try to get it in activity B.
I hope this will help you.

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");
}
}
}

Passing ArrayList<Object> in Android Studio w/ Lastfm API

I am trying to pass an ArrayList of type Album to another activity in Android Studio.
The problem is that the Lastfm API I am using does not implement Parcelable.
I tried making my own Album class and extending their Album class but I got the error
"there is no default constructor available in 'de.umass.lastfm.Album'
Quiz.java - intent.getParcel... not working as Album is not Parcelable
public class Quiz extends AppCompatActivity {
private static TextView tv_quiz;
private static EditText et_quiz;
private ArrayList<Album> albums;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent = getIntent();
albums = intent.getParcelableArrayListExtra(MainActivity.ALBUMS_LIST);
}
}
The calling portion of my MainActivity.java.
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(ALBUMS_LIST, allAlbums);
intent.putExtra(DIFFICULTY, difficulty);
startActivity(intent);
Is there any way I can get around this?
Thanks anyway
I took a look at the api you linked, and Album looks extremely difficult to parcel. I would say that you might be better off simply re-loading the list in the next Activity (rather than trying to pass the list).
The only way to "construct" a new Album instance is through the getInfo() static factory method. You could create a new class AlbumWrapper that is parcelable, send a list of AlbumWrapper through the Intent, and then use getInfo() on the other side to re-fetch the albums.
public class AlbumWrapper implements Parcelable {
// insert CREATOR here
public final String artist;
public final String mbid;
public AlbumWrapper(Album a) {
this.artist = a.getArtist();
this.mbid = a.getMbid();
}
private AlbumWrapper(Parcel in) {
this.artist = in.readString();
this.mbid = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(artist);
dest.writeString(mbid);
}
#Override
public int describeContents() {
return 0;
}
}
You can put your list of Albums in the intent like this:
ArrayList<AlbumWrapper> wrappers = new ArrayList<>();
for (Album album : albums) {
AlbumWrapper wrapper = new AlbumWrapper(album);
wrappers.add(wrapper);
}
intent.putParcelableArrayListExtra("ALBUM_WRAPPERS", wrappers);
And then in your next activity you can do something like:
List<AlbumWrapper> wrappers = getIntent().getParcelableArrayListExtra("ALBUM_WRAPPERS");
List<Album> albums = new ArrayList<>();
for (AlbumWrapper wrapper : wrappers) {
Album album = Album.getInfo(wrapper.artist, wrapper.mbid, YOUR_API_KEY);
albums.add(album);
}
Here is the solution
open activity using this code
Bundle bundle = new Bundle();
bundle.putSerializable("data", allAlbums);
bundle.putString(DIFFICULTY", difficulty);
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(bundle);
startActivity(intent);
get intent data
albums = (ArrayList<Album>) getIntent().getExtras().getSerializable("data");
updated Album Class
public class Album implements java.io.Serializable {
//your code
}

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

Assigned a ArrayList in AsyncTask, but the change discard afterwords

I'm writing a simple program to request a JOSN request of a list of earthquakes to display for users. I use Asynctask to put the request in the background thread and use an ArrayList Adaptor to display the relevant information. I declare an empty ArrayList and then extract the JOSN request and put them in a temporary list and then assign the temporary list to the empty ArrayList.
I use a debugger tool to see that in the updateEarthquakeList method. I set the break point in the updateEarthquakeList method. this.earthquak and earthquakes both have 10 elements. Pics are as follow:
But when I set the break point after task.execute(USGS_REQUEST_URL) in the onCreate method, I got this:
As the pics shown after execute the AsyncTask the ArrayList is empty. But inside the AsyncTask The array was actually updated. (To do a little experiment I create an int haha as 0 and change it to 1 in the Asynctask, but it changed back to 0 afterwards)
How is this happen and how do I supposted to make it right?
public class EarthquakeActivity extends AppCompatActivity {
public static final String LOG_TAG = EarthquakeActivity.class.getName();
ArrayList<Earthquake> earthquak = new ArrayList<Earthquake>();
int haha = 0;
private static final String USGS_REQUEST_URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
EarthquakeAsyncTask task = new EarthquakeAsyncTask();
task.execute(USGS_REQUEST_URL);
// Create a fake list of earthquake locations.
// Find a reference to the {#link ListView} in the layout
ListView earthquakeListView = (ListView) findViewById(R.id.list);
// Create a new {#link ArrayAdapter} of earthquakes
EarthquakeAdapter adapter = new EarthquakeAdapter(this, earthquak);
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
earthquakeListView.setAdapter(adapter);
//OPEN a web page of a specific when textview is clicked.
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW, earthquak.get(position).getUrl());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
}
private void updateEarthquakeList(ArrayList<Earthquake> earthquake) {
this.earthquak = earthquake;
haha = 1;
}
private class EarthquakeAsyncTask extends AsyncTask<String, Void, ArrayList<Earthquake>> {
#Override
protected ArrayList<Earthquake> doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
ArrayList<Earthquake> earthquakes = QueryUtils.fetchEarthquakeData(urls[0]);
return earthquakes;
}
#Override
protected void onPostExecute(ArrayList<Earthquake> earthquakes) {
updateEarthquakeList(earthquakes);
}
}

Cannot make a static reference to the non-static method in onitemclicklistener on custom listview adapter fetching data from sqlite database

Application Structure first:
//This class has a listview which will be populated from custom adapter
public class Transactions_show extends Activity implements OnItemClickListener
//This class is custom adapter which returns custom view for each row to be populated in above listview using sqlite database
public class CustomAdapter extends BaseAdapter
//Here all is working fine
//Now
//setting onitemclicklistener on each item of listview
public class Transactions_show extends ListActivity implements
OnItemClickListener {
List<Transactions> all_transactions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_transactions);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
all_transactions = db.get_all_transactions();
size_of_transaction = all_transactions.size();
ListView all_transactions_list = (ListView) findViewById(R.id.all_transaction_show_list);
CustomAdapter adapter = new CustomAdapter(this, all_transactions);
all_transactions_list.setAdapter(adapter);
try {
all_transactions_list.setOnItemClickListener(this);
} catch (NullPointerException e) {
Log.e("null pointer exception at item click", e.getMessage());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Transactions single_transaction = new Transactions();
single_transaction = all_transactions.get(position);
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Intent.putExtra("phone_number", p_n);
startActivity(intent);
/*
* Toast toast = Toast.makeText(getApplicationContext(), "Item " +
* (position + 1) + ": " +single_transaction.get_phone_number() ,
* Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM |
* Gravity.CENTER_HORIZONTAL, 0, 0); toast.show();
*/
}
}
error is occuring here
Intent.putExtra("phone_number", p_n);
Which is : Cannot make a static reference to the non-static method putExtra(String, int) from the type Intent
Finding and trying on stack overflow for days and following google developers , decided to make a bundle as given in Passing a Bundle on startActivity()?
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Transactions single_transaction = new Transactions();
single_transaction = all_transactions.get(position);
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Bundle extras = intent.getExtras();
try {
extras.putInt("phone_number", p_n);
} catch (NullPointerException e) {
Log.e("Null exception at putint", e.getMessage());
}
Intent.putExtra("phone_number", p_n);
startActivity(intent);
}
Error removed but when application runs but crashes at extras.puInt ,although next activity starts well if don't pass this bundle.
So thought about taking complete custom view row and extract field of phone number
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(this, transacee_summary.class);
TextView textv = (TextView) findViewById(R.id.phone_number_show);
int p_n = Integer.parseInt( textv.getText().toString());
Intent.putExtra("phone_number", p_n);
startActivity(intent);
}
now error comes again same.
What goes around comes around!
It should probably be:
intent.putExtra("phone_number", p_n);
intent (the instance), not Intent (the class), since putExtra is indeed an instance method.
Problem is with this piece of code:
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Intent.putExtra("phone_number", p_n);
You need to replace Class Intent refrence with Object Intent refrence as putExtra is not a static method it is an instance method
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
intent.putExtra("phone_number", p_n); // see starts with small i
Hope this helps.

Categories

Resources