how to display array data in json object if the json data is like below. I want to display array data of Ingredient and step. This is the full API Address that I want to fetch the data https://masak-apa-tomorisakura.vercel.app/api/recipe/resep-nasi-bakar-ayam
I've tried several ways but I can't find how to implement it properly.
this is my json model.
#SerializedName("ingredient")
#Expose
Ingredient ingredient = null;
public Ingredient getIngredient() {
return ingredient;
}
public void setIngredient(Ingredient ingredient) {
this.ingredient = ingredient;
}
This is the code I use to display the data
public void LoadData() {
Call<ResultsResponse> call = Config.getInstance().getApi().results(kunci);
call.enqueue(new Callback<ResultsResponse>() {
#Override
public void onResponse(Call<ResultsResponse> call, Response<ResultsResponse> response) {
shimmerFrameLayout.startShimmer();
detailJudul.setText(response.body().getResults().getTitle());
detailWaktu.setText(response.body().getResults().getTimes());
detailKesulitan.setText(response.body().getResults().getDificulty());
detailPorsi.setText(response.body().getResults().getServings());
detailDeskripsi.setText(response.body().getResults().getIngredient());
detailAuthor.setText(response.body().getResults().getAuthor().getUser());
Glide.with(DetailResepActivity.this)
.load(response.body().getResults().getThumb())
.apply(new RequestOptions().override(400, 400))
.into(detailGambar);
//Intent Baca Resep di browser
llVisitWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = ("https://www.masakapahariini.com/resep/" + kunci);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
shimmerFrameLayout.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<ResultsResponse> call, Throwable t) {
Log.d("Hasil", t.getMessage());
}
});
//Intent kembali ke MainActivity
RelativeLayout ivBack=findViewById(R.id.back);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), MainActivity.class);
startActivity(i);
}
});
}
This is the error that android studio shows
Thanks, I hope someone gives an example project that displays array data in a json object like my problem above.
UPDATE
Thanks Gralls, I can display the array data by creating a new string and implementing
String ingredient= response.body().getResults().getIngredient().toString();
detailDeskripsi.setText(ingredient);
it into the previously created string. Then how to make the data ingredient can be in the form of a list?
I don't have an example project but ingredients is array of strings. So instead of having
#SerializedName("ingredient")
#Expose
Ingredient ingredient = null;
you should parse array into some sort of the list
#SerializedName("ingredient")
List<String> ingredient = null;
I hope that this will help :)
Related
I'm using SharedPreferences to store a list of fragments of my android, however it gave me thousands lines of error which make non-sense:
2021-12-07 17:09:13.228 14833-14833/? E/AndroidRuntime: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:1058)
at .......
(just small parts of error messages)
I tried to store a list of strings it works fine, but if I switch to an object with list of fragments it fails.
Here is my object.java:
public class CardList {
ArrayList<Card> list; //Card is my fragments
public CardList(ArrayList<Card> list) {
this.list = list;
}
public void updateList(Card c) {
list.add(c);
}
public int getListSize() {
return list.size();
}
}
here is my MainActivity.java, the new intent here was just to test if I can get my data back when I'm back to MainActivity
public class MainActivity extends AppCompatActivity {
public static final String WEATHER_PREFS = "weatherPrefs";
public CardList cardList;
public ArrayList<Card> cards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = new ArrayList<>();
cardList = new CardList(cards);
SharedPreferences setting = getSharedPreferences(WEATHER_PREFS,MODE_PRIVATE);
Gson gson = new Gson();
String savedList = setting.getString("cardList","");
if (!savedList.equals("")) {
cardList = gson.fromJson(savedList,CardList.class);
}
Button btn= findViewById(R.id.switchActtivity);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
Gson gson = new Gson();
String savedInstanceString = gson.toJson(cardList);
SharedPreferences setting = getSharedPreferences(WEATHER_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor = setting.edit();
editor.putString("cardList",savedInstanceString);
editor.apply();
startActivity(intent);
}
});
Button increase = findViewById(R.id.increase);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardList.updateList(Card.newInstance("hello","world"));
Log.i("Array List Size After Click",String.valueOf(cardList.getListSize()));
}
});
}
}
Can someone teach me how to store custom object with an arraylist attribute in Android? Thanks in advance!
Fragments aren't serializable, meaning they can't be broken down into pure data ie JSON, much less deserializable.
Looking at your code there is no good way to just make it work either.
You need to follow separation of concerns, Fragments are glorified views. They shouldn't be holding information to any great extent, so they shouldn't be passed around as if they did.
What you could do is have a CardModel that contains all information needed for a Card Fragment.
The CardModel can contain simple data that you would find in JSON like Integer,String, etc...
A List<CardModel> can be deserialized from JSON. And then when you're in the MainActivity you could create as many Card Fragments as needed to represent the List<CardModel> with a simple list.size()
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 1 year ago.
I'm making an application, where I have a central recyclerview where items that the user will type are listed, below 2 buttons, one for adding items and the other for finishing. The problem I am having is that when the user finishes the task and clicks on finish I want to get all the data that was listed on his screen that is inside a List and store it in firebase, but I am not able to get this data in shape array, it always returns the object reference.
Searching the internet I found how to use the .toString in the array, but it returns me the same thing.
Here is the example of the return I am receiving.
return
the code of my object
public class ListItem {
private float measure;
public ListItem(float measure) {
this.measure = measure;
}
public float getMeasure() {
return measure;
}
public void setMeasure(float measure) {
this.measure = measure;
}
}
the code of my button add
private View.OnClickListener addItem = new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogForm();
mAdapter.notifyItemInserted(listItems.size());
}
};
void DialogForm() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
final View customLayout = getLayoutInflater().inflate(R.layout.layout_dialog, null);
alert.setView(customLayout);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText measure = customLayout.findViewById(R.id.edit_measure);
String response = measure.getText().toString();
if (response.isEmpty() || response.equals("0")) {
Toast.makeText(MainActivity.this, "A medida não pode ser vazia",
Toast.LENGTH_SHORT).show();
} else {
listItems.add(new ListItem(Float.parseFloat(response)));
btnFinish.setEnabled(true);
btnFinish.setBackgroundResource(R.drawable.bg_button_enabled);
}
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
the code of my button finish, when I'm listing
private View.OnClickListener finishListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0; i<listItems.size(); i++){
Log.d("teste", listItems.get(i).toString());
}
}
};
toString() will always return the hash of the object if not override as it is an inherited method from java.lang.Object and not specific to your object
If you want toString to return the measure variable then add the following to your ListItem class
#Override
public String toString() {
return Integer.toString(measure);
}
In order to add more entries to the method, just add another + myData but perhaps ensure there is some sort of divider to make it moire readable - such as + " || " + or something
Good luck with the project
I'm trying to save two values from an activity (where the user can put in two different values, one String value and one integer value) in the listview from another activity. In the first activity, it shows a list with a course and the amount of points for that course in one listview, like this:
Course: English
Points: 4
Now, the problem is, everytime I want to put in another value using the add_course_actitivty, it overwrites the previous value. I've looked at different solutions, like with sharedpreferences (Add items to listview from other activity), but this uses only one value and if I try to work with sharedpreferences, it overwrites the other value in the sharedpreferences, but I want users to add multiple courses and corresponding points. Also on restart, it deletes the values in the listview (I read to prevent this you need to store it in sharedpreferences, but this doesn't work the way I need it to be)
KeuzeActivity.class (shows the listview):
public class KeuzeActivity extends AppCompatActivity {
private FloatingActionButton fab_add;
private String student_naam;
private ListView keuze_list;
boolean wantDelete;
private ArrayAdapter adapter;
private String vak;
private int ec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keuze);
// setting title
student_naam = getIntent().getStringExtra("student");
setTitle("Keuzevakken en projecten van " + student_naam);
//initialzing elements
fab_add = (FloatingActionButton)findViewById(R.id.fab_add);
keuze_list = (ListView) findViewById(R.id.keuze_list);
//initializing list
final ArrayList<Course> courseItems = new ArrayList<Course>();
adapter = new ArrayAdapter<Course>(this, android.R.layout.simple_list_item_1, courseItems);
keuze_list.setAdapter(adapter);
// checks if intent has required values, put it in listview
if (getIntent().hasExtra("vak") && getIntent().hasExtra("ec")) {
vak = getIntent().getStringExtra("vak");
ec = getIntent().getIntExtra("ec", ec);
courseItems.add(new Course(vak, ec));
adapter.notifyDataSetChanged();
}
// make fab go to other activity
fab_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(KeuzeActivity.this, add_course_activity.class));
}
});
// long press deletes item
keuze_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
showDeleteDialog();
if (wantDelete) {
courseItems.remove(position);
adapter.notifyDataSetChanged();
}
return true;
}
});
}
private void showDeleteDialog() {
AlertDialog.Builder infobuilder = new AlertDialog.Builder(this);
infobuilder.setCancelable(false);
infobuilder.setTitle("Vak/project verwijderen");
infobuilder.setMessage("Weet je zeker dat je het vak of project wilt verwijderen?");
final TextView text = new TextView(this);
// action when pressed OK
infobuilder.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
wantDelete = true;
dialog.cancel();
}
});
infobuilder.setNegativeButton("Nee", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
wantDelete = false;
dialog.cancel();
}
});
infobuilder.show();
}
}
add_course_activity.class (let's users input course and points)
public class add_course_activity extends AppCompatActivity {
private EditText course_edit;
private EditText ec_edit;
private Button save_btn;
private String student_name;
private int ec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
setTitle("Voeg vak of project toe");
final Context context = getApplicationContext();
// initializing elements
course_edit = (EditText) findViewById(R.id.edit_vak);
ec_edit = (EditText) findViewById(R.id.edit_ec);
save_btn = (Button) findViewById(R.id.save_button);
// action on savebutton
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (course_edit.getText().toString().trim().length() > 0 && ec_edit.getText().toString().trim().length() > 0 ) {
ec = Integer.parseInt(ec_edit.getText().toString());
Intent goBack = new Intent(add_course_activity.this, KeuzeActivity.class);
goBack.putExtra("vak", course_edit.getText().toString());
goBack.putExtra("ec", ec);
goBack.putExtra("student", PreferenceManager.getDefaultSharedPreferences(context).getString("student_name", student_name));
startActivity(goBack);
}
else {
Toast.makeText(context, "Voer juiste informatie in!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Course.java class (getters and setters + with toString method)
public class Course {
private String vak;
private int ec;
public Course(String vak, int ec) {
this.vak = vak;
this.ec = ec;
}
public String getVak() {
return vak;
}
public void setVak(String vak) {
this.vak = vak;
}
public int getEc() {
return ec;
}
public void setEc(int ec) {
this.ec = ec;
}
#Override
public String toString() {
return ("Vak: " + vak + "\n" + "Punten: " + ec);
}
}
Note that my code isn't clean or done, but to get further I need to fix this problem.
You have several way to do it. As other replies have suggested you can use an SQLLite database and add data to a course table and retrieve data from it.
If you find Db approach to complicated/heavy
You could also use SharedPreferences what you need to do is figure a way to store a string that represent a list of course. It is not the best way to approach it but it will work.
Lets say you choose to serialize your Course object with "vac-ec"
Then you just store a serialized list of course. Example "vac1-ec1,vac2-ec2"
When you need to add a course you juste grab the previous string split it to list, append the new course to the list and re-serialize the list to a string to encode it.
Other solution could be to use Realm.
You should used SQLiteDatabase and create a table with valid attributes and insert your new values into them
Okay, now things are clearer. As answered by #Dwijraj, when storing what potentially will be a large set of data, for maximum control it is best to use SQLite.
You can read more about the different Saving Data methods here:
https://developer.android.com/training/basics/data-storage/index.html
SharedPreferences are best used to store small amounts of information, like storing the settings of an application. [Mute] for example. Or a highscore in case of a game.
A Database is a better option when it comes to storing large pieces of data that you will potentially manipulate.
Your data structure can be something like this, Courses table containing Unique_ID , Course Name, Course Level, Course summary.
A table for English for example which will contain
Exams, Scores, Duration.
There are a lot of things you can do.
Try by storing the records in SQLite, and get it when you want to show.
By this, You can have a track of all added items. And you can show the items you want.
I have created two class one is LoginSignupActivity.java and another is ProfileActivity.java
LoginSignUpActivity.java---
public class LoginSignupActivity extends AppCompatActivity {
** static string id; **
public void getUserDetailsFromFB() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(final JSONObject object, GraphResponse response) {
try{
** id=response.getJSONObject().getString("id");**
}
catch (JSONException e) {
//If anything goes wrong
Log.e("my",e.toString());
}
})
}
}
}
ProfileActivity.java ---
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ImageView imageView = (ImageView) findViewById(R.id.dp);
if(imageView!=null){
** String fbid = (new LoginSignupActivity).getUserDetailsFromFB().id; **
if(fbid!=null){
Glide.with(this).load("http://graph.facebook.com/1615242245409408/picture?type=large").into(imageView);
//Glide.with(this).load("http://graph.facebook.com/" + "1675239799409652" + "/picture?type=large").into(imageView);
Log.d("mayank", LoginSignupActivity.id);
}
else{
Log.d("mayank","null facebook id");
}
}
else {
Log.d("mayank","null image view");
}
}
}
When I access id inside ProfileActivity.java
it shows null value.
I want to access that value that is obtained inside LoginSignupActivity.java.
Please help.
Thanks
Try to make id public and I think you should get it throw LoginSignUpActivity.id
If the login is for one time only I recommand you to use SharedPreference.
do as:
public static String id="NA";
Use String instead of string.
Android Studio "cannot resolve symbol String"
List item
you will get NA if id is not received by your line of code:
id=response.getJSONObject().getString("id");
As you told in comment, you should use the value of id after getting it only
id=response.getJSONObject().getString("id");
I thing you should only start the ProfileActivity.java just after getting id valueas below:
id=response.getJSONObject().getString("id");
Intent intent=new Intent(LoginSignupActivity.this,ProfileActivity.class);
startActivity(intent);
Thanks
I have a ListView of contacts and each contact is a Java object with a bunch of information associated with it. Some of that info is shown in the ListView, but the rest is meant for the DetailView. I'm trying to write a method that will take me to a DetailView for any contact I click on, but I also need to take the object with me. I store all of the contacts in an ArrayList in my MainActivity.java
My questions: Do I need to take the contact object with me or is there actually some way to access my ArrayList in another Activity?
If I can/have to take it with me, how would I do so, since the putExtra() methods don't take objects as arguments.
The beginning of my MainActivity looks like this:
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
ListView list;
I have a very basic onClickListener right now but don't know what to put into it:
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, DetailView.class);
intent.putExtra("contact", i);
startActivity(intent);
}
I feel like my initial definition of the MainActivity class doesn't correspond to the onItemClick method or something, which is why it doesn't execute and take me to another screen.
Intent intent = new Intent(ActivityA.this, DetailView.class);
intent.putExtra("extra_name","extra");
startActivity(intent);
Then in the other Activity :
/*onCreate*/
Object extra = getIntent().getExtra().get("extra_name");
I would recommend to pass an ID of some sort pointing to the description, passing complex data structure with intents is not recommended
Simply, use Intent.putExtra() to pass the information and getIntent().getExtras() to receive the information.
// call a new intent
myIntent = new Intent(ActivityA.this, ActivityB.class);
// put an extra (like this following string)
String userid = "User A";
myIntent.putExtra("TAG_CONTACT_ID", userid);
startActivity(myIntent);
// receive the info in your onCreate method in ActivityB
Bundle extras = getIntent().getExtras();
if(extras != null) {
String newUserID = extras.getString("TAG_CONTACT_ID");
}
See this short example for more information.
If you want to pass an Integer, you can do it as the following: myIntent.putExtra("value", i); and take it with: int myValue = extras.getInt("value");.
Hope this help.
Try something like this:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Contact c = (Contact)contacts.get(position);
Intent i = new Intent();
i.putExtras("contact", c);
i.setClass(this, Activity2.class);
startActivity(i);
}
Create java object with parcelable
Check the below code to create parcelable object in Android.
public class ObjFeedImages implements Parcelable {
public int image_id;
public boolean like_status = false;
public String image_url = null;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {
String.valueOf(image_id),
String.valueOf(like_status),
image_url, });
}
public ObjFeedImages(Parcel in) {
String[] data = new String[3];
int i = 0;
in.readStringArray(data);
image_id = Integer.parseInt(data[i++]);//
like_status = Boolean.parseBoolean(data[i++]);
image_url = data[i++];
}
public static final Parcelable.Creator<ObjFeedImages> CREATOR = new Parcelable.Creator<ObjFeedImages>() {
#Override
public ObjFeedImages createFromParcel(Parcel source) {
try {
return new ObjFeedImages(source);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
public ObjFeedImages[] newArray(int size) {
try {
return new ObjFeedImages[size];
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
}
After creating some list of such object say
ObjFeedImages object = new ObjFeedImages();
object.image_id = 1;
object.like_status = true;
object.image_url="http://some image url";
Intent intent = new Intent(/*Your Intent Info*/);
intent.putExtras("key_name",object);
startActivity(intent);
Here is the complete description.
To retrive object in other activity you have to write below code.
ObjFeedImages objectOnOtherActivity = (ObjFeedImages)getIntent().getParcelableExtra("key_name");
So ready to enjoy code.
Happy coding....