move to multiple activities according to JSON data - android

I have a some JSON Data -
{
"ActivityOrder":[
{
"Position":3,
"ActivityName":"Activity1"
},
{
"Position":5,
"ActivityName":"Activity2"
},
{
"Position":2,
"ActivityName":"Activity3"
},
{
"Position":1,
"ActivityName":"Activity4"
},
{
"Position":4,
"ActivityName":"Activity5"
}
]
}
According to above JSON data, call Intent from Single Activity or class. I mean First call Position1 activity (Activity4), then position2 (Activity3) and so on.
Note:- In JSON Data, Activity Position can be changed from backend.

As soon as you get your activity name , create the class like this :
Class activity= Class.forName("yourActivityName");
And then create the intent :
Intent intent = new Intent(this, activity);

Create pojo model class:
public class MyPojo {
String ActivityName;
int Position;
public MyPojo(String activityName, int position) {
ActivityName = activityName;
Position = position;
}
public int getPosition() {
return Position;
}
public void setPosition(int position) {
Position = position;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
}
Now parse json to Model:
List<MyPojo> MyPojoList=new ArrayList<>();
try {
JSONObject jObj = new JSONObject("your json response");
JSONArray jArr = jObj.getJSONArray("ActivityOrder");
for (int i=0; i < jArr.length(); i++) {
JSONObject obj = jArr.getJSONObject(i);
String Position = jObj.getString("Position");
String ActivityName = jObj.getString("ActivityName");
MyPojoList.add(new MyPojo(ActivityName,Position));
}
}
catch(JSONException ex) {
ex.printStackTrace();
}
Now sort array :
Collections.sort(MyPojoList, new Comparator<MyPojo>(){
public int compare(MyPojo obj1, MyPojo obj2) {
return Integer.valueOf(obj1.getPosition()).compareTo(Integer.valueOf(obj2.getPosition()));
}
});
Finally, start the activity with position one by one:
Intent intent=new Intent();
intent.setComponent(new ComponentName(getApplicationContext(), MyPojoList.get(position).getActivityName()));
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}

Related

How can intent or pass data through on click image in (slider Layout) android

I am a new application developer I try intent or pass data through on click image in (slider Layout) from first activity to the second activity. I try to intent (name) to second activity.
I now have a different set of images now, each one having its own name.if user clicking on the first image will intent or pass data of first image only.Also if user clicking on the five image will intent data of five image only.Like that what I want to do.
Please if anyone knows the answer help me.
import com.smarteist.autoimageslider.SliderLayout;
import com.smarteist.autoimageslider.SliderView;
public class SlidShowMain extends AppCompatActivity {
SliderLayout sliderLayout;
private List<SlidShowListData> list_dataList;
private JsonArrayRequest request;
private RequestQueue requestQueue;
private static final String HI ="http://=========/S.php";
TextView textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_show_new);
sliderLayout = (SliderLayout) findViewById(R.id.imageSlider);
sliderLayout.setIndicatorAnimation(SliderLayout.Animations.WORM);
list_dataList=new ArrayList<>();
sliderLayout.setScrollTimeInSec(1);
textView5 =(TextView)findViewById(R.id.textView5);
SliderView sliderView = new SliderView(this);
setSliderViews();
}
private void setSliderViews() {
request = new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
SlidShowListData listData = new SlidShowListData listData = new SlidShowListData(jsonObject.getString("imageurl"),jsonObject.getString("name"),jsonObject.getString("id"));
String name = jsonObject.getString("id");
textView5.append(name + ", " +"\n\n");
list_dataList.add(listData);
} catch (JSONException e) {
e.printStackTrace();
}
}
setupdata(list_dataList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void setupdata(List<SlidShowListData> list_dataList) {
for (int i = 0; i <= 4; i++) {
final SlidShowListData ld = list_dataList.get(i);
SliderView view = new SliderView(getBaseContext());
view.setImageUrl(ld.getImageurl());
view.setImageUrl(ld.getname());
view.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
final int finalI = i;
sliderLayout.addSliderView(view);
view.setOnSliderClickListener(new SliderView.OnSliderClickListener() {
#Override
public void onSliderClick(SliderView sliderView) {
Toast.makeText(SlidShowMain.this, "" + (sliderLayout.getCurrentPagePosition() + 1), Toast.LENGTH_SHORT).show();
}
});
}
}
}
public class SlidShowListData {
private String imageurl;
private String name;
private String id;
public SlidShowListData(String imageurl,String name,String id) {
this.imageurl = imageurl;
this.name = name;
this.id = id;
}
public String getImageurl() {
return imageurl;
}
public String getname() {
return name;
}
public String getId() {
return id;
}
}
implementation 'com.github.smarteist:autoimageslider:1.1.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
<?php
$con=mysqli_connect("localhost","=====","=====","show");
$sql="SELECT * FROM slhow";
$result=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_assoc($result)){
$data[]=$row;
}
header('Content-Type:Application/json');
echo json_encode($data);
?>
I have tried to write it as follows:
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,HomeActivity.class);
intent.putExtra("id",======.=======()); // here problem
context.startActivity(intent);
I don't know what I should write or how on the second line into (====) to send an ID.must send the Id of image that user just clicks, not all ids of images
Anyone know solution , please help me
Use this code for sending data from FirstActivity:
val intent = Intent(this#FirstActivity, SecondActivity::class.java)
intent.putExtra("imagename", imageid)
startActivity(intent)
And this for delivering date in SecondActivity:
var imageid = intent.getStringExtra("imagename")

finding in an array if specific fileds exists or not

This is my api
{}JSON
[]products
{}0
product-name : "Fiting"
product-id : "1"
product-description : "Door"
product-image : "https://image/logo.jpg"
product-categoryid : "2"
category-name : "Furniture"
{}1
product-name : "Bathroom"
product-id : "2"
product-description : "Services"
product-image : "https://image/logo.jpg"
product-categoryid : "1"
category-name : "Plumber"
subcategory-id : "1"
subcategory-name : "Bathroom"
subCategoryDetailModelClass.setSubCategoryId(productObject.getInt("subcategory-id"));
subCategoryDetailModelClass.setSubCategoryName(productObject.getString("subcategory-name"));
i cannot add subcategory-id,subcategory-name in my arraylist since it is not available at 0th position.....so how to check condition that if in api subcategory-id,subcategory-name is not available add other items in the list
StringRequest stringRequest = new StringRequest(Request.Method.GET,URLs.productURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("zsded", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("products");
//now looping through all the elements of the json array
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryDetailModelClass subCategoryDetailModelClass = new SubCategoryDetailModelClass();
// if(productObject.getInt("subcategory-id"))
subCategoryDetailModelClass.setProduct_name(productObject.getString("product-name"));
subCategoryDetailModelClass.setProduct_id(productObject.getInt("product-id"));
subCategoryDetailModelClass.setProduct_desc(productObject.getString("product-description"));
subCategoryDetailModelClass.setProduct_imgURL(productObject.getString("product-image"));
subCategoryDetailModelClass.setProduct_CategoryId(productObject.getInt("product-categoryid"));
subCategoryDetailModelClass.setProduct_Category_Name(productObject.getString("category-name"));
subCategoryDetailModelClass.setSubCategoryId(productObject.getInt("subcategory-id"));
subCategoryDetailModelClass.setSubCategoryName(productObject.getString("subcategory-name"));
subCategoryListDetailModelClassArray.add(subCategoryDetailModelClass);
Log.d("subcatdetail", String.valueOf(subCategoryDetailModelClass));
}
Use this class
public class JSONHelper {
public static String getString(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
return json.getString(tag);
}
return "";
}
public static int getInt(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
if(json.get(tag) instanceof String) {
if(json.getString(tag).equalsIgnoreCase("None")) {
return -1;
}
if(!json.getString(tag).equals("")) {
return Integer.parseInt(json.getString(tag));
} else {
return -1;
}
}
return json.getInt(tag);
}
return -1;
}
public static boolean getBoolean(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
Object value = json.get(tag);
if(value instanceof String) {
return PrimitiveHelper.StringToBoolean((String) value);
} else if (value instanceof Integer) {
return PrimitiveHelper.IntegerToBoolean((int)value);
}
return json.getBoolean(tag);
}
return false;
}
public static Boolean getBooleanBoxed(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
Object value = json.get(tag);
if(value instanceof String) {
return PrimitiveHelper.StringToBooleanBoxed((String) value);
} else if (value instanceof Integer) {
return PrimitiveHelper.IntegerToBooleanBoxed((int) value);
}
return json.getBoolean(tag);
}
return null;//false;
}
private static boolean mJSONValueAvailable(JSONObject json, String tag) {
return json.has(tag) && !json.isNull(tag);
}
// private static Boolean mJSONValueAvailableBoxed(JSONObject json, String tag) {
// return json.has(tag) && !json.isNull(tag);//
// }
public static JSONArray sortJsonArray(JSONArray array, String sort) {
final String sortKey = sort;
//Logger.d("sortJSONArray by::: " + sortKey);
List<JSONObject> jsons = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
try {
String lid = lhs.getString(sortKey);
String rid = rhs.getString(sortKey);
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONArray(jsons);
}
}
Call this as follows
subCategoryDetailModelClass.setProduct_name(JSONHelper.getString(productObject, "product-name"));
subCategoryDetailModelClass.setProduct_id(JSONHelper.getInt(productObject,"product-id"));
subCategoryDetailModelClass.setProduct_desc(JSONHelper.getString(productObject, "product-description"));
subCategoryDetailModelClass.setProduct_imgURL(JSONHelper.getString(productObject, "product-image"));
subCategoryDetailModelClass.setProduct_CategoryId(JSONHelper.getInt(productObject,"product-categoryid"));
subCategoryDetailModelClass.setProduct_Category_Name(JSONHelper.getString(productObject, "category-name"));
subCategoryDetailModelClass.setSubCategoryId(JSONHelper.getInt(productObject, "subcategory-id"));
subCategoryDetailModelClass.setSubCategoryName(JSONHelper.getString(productObject,"subcategory-name"));
subCategoryListDetailModelClassArray.add(subCategoryDetailModelClass);
Use Opt methods, For e.g.
optInt(String name, int fallback)
Returns the value mapped by name if it exists and is an int or can be
coerced to an int, or fallback otherwise.
There are optMethods for mostly primitive datatypes, check here

How to pass json data in another activity [duplicate]

This question already has answers here:
Passing JSONObject into another activity
(7 answers)
Closed 6 years ago.
public class MainActivity extends **strong text**
AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> companyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
companyList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_row_xml);
new GetCompany().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", venue);
startActivity(i);
}
});
}
private class GetCompany extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected JSONObject doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:6060/api/v1/company/getInfo?limit=10&page=1";
JSONArray company = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + company);
if (company != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray company = new JSONArray(jsonStr);
// System.out.println("Reached");
// looping through All Contacts
for (int i = 0; i < company.length(); i++) {
//System.out.println("Reached1");
JSONObject c = company.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("companyName");
// Walking Details in Json object
JSONObject walkingDetails=c.getJSONObject("walkingdetails");
String date = walkingDetails.getString("walkingdate");
String venue = walkingDetails.getString("venu");
// tmp hash map for single contact
HashMap<String, String> companyy = new HashMap<>();
// adding each child node to HashMap key => value
companyy.put("id",id);
companyy.put("date", date);
companyy.put("companyname", name);
companyy.put("venue", venue);
// adding contact to contact list
companyList.add(companyy);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
/* #Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, companyList,
R.layout.list_row, new String[]{"date","companyname","venue"}, new int[]{ R.id.date, R.id.companyname, venue});
lv.setAdapter(adapter);*/
}
}
second acivity:
public class SingleView extends AppCompatActivity {
EditText txtVenue;
// String[] Venue;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_view);
Intent i = getIntent();
position = i.getExtras().getInt("positi`enter code here`on");
txtVenue = (EditText) findViewById(R.id.Venue);
}
}
You can not pass directly JSONObject to another activity. But you can convert json to string and pass it. Then in SecondActivity you can convert it to json again.
Start SecondActivity codes in FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("data", json.toString());
startActivity(intent);
Then get this data from SecondActivity:
String data = getIntent().getStringExtra("data");
try {
JSONObject json = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
Good luck.
You can achieve by creating your own class by extending the JSONObject and implementing Serializable interface. So that you can pass through the intent.
You have 2 options:
1. Convert json to string and pass as string.
2. Make model class for json , make it parcelable. Pass this object to next activity.
HashMaps do not preserve ordering.
Better use a model class, it would also be easy to retrieve data.
public class CompanyData {
public String id;
public String date;
public String name;
public String venue;
}
then change arraylist,
ArrayList<CompanyData> companyList;
then store values,
CompanyData companyy = new CompanyData();
companyy.id = id;
companyy.date = date;
companyy.name = name;
companyy.venue = venue;
companyList.add(companyy);
then implement onitemclicklistener,
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", data.venue);
startActivity(i);
}
});
***To get position simply send position value inside onItemClickListener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("position", position);
startActivity(i);
}
});
You can also send all data of a specific position by
CompanyData data = companyList.get(position);
i.putExtra("data", data); //this will pass all data of clicked row

When clicked on grid view how to send arralist(position) to another actvity

In this method I am receiving the ArrayList
OkHttpHandler handler = new OkHttpHandler(MainActivity.this,new OkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
Toast.makeText(MainActivity.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
GridViewAdapter adapter = new GridViewAdapter(getApplicationContext(), R.layout.grid_item_layout, result);
what I want is to send this arraylist to another activity in the gridiview. When the user clicks on the image in gridview, I want to send this image in ArrayList to next activity. How to do that>
this is the grid view
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("OnImageButton", "Clicked");
Intent intnt =new Intent(mcontext, SingleViewActivity.class);
//intnt.putExtra("Contact_list", item);
mcontext.startActivity(intnt) ; //This line raises error
Toast.makeText(mcontext, "intent",
Toast.LENGTH_LONG).show();
}
});
I tried parcable, but it didn't work because I only want to send the data to another activity, I don't to start a new activity
this is what I tried
Listitem = new ArrayList<Listitem>();
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
// String id ="2";
String id= c.getString("ID");
String url = c.getString("URL");
Log.d("Id: ", id);
int intid = 0;
Student student = new Student(c.getString("ID"),
"hhe",
c.getString("URL")
);
Intent intent = new Intent(mContext,SingleViewActivity.class);
// Passing data as a parecelable object to StudentViewActivity
intent.putExtra("student",student);
// Opening the activity
mContext.startActivity(intent);
In this method, I am passing ArrayList to another activity
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println(peoples.length());
Listitem = new ArrayList<Listitem>();
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id= c.getString("ID");
String url = c.getString("URL");
Log.d("Id: ", id);
int intid = 0;
try {
intid = Integer.parseInt(id.toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
DatabaseHandler db = new DatabaseHandler(mContext);
Log.d("Insert: ", "Inserting ..");
db.addObjects(new Objects(intid,"Image1", url, "IMAGES", "Funny"));
Listitem.add(new Listitem(id,url));
Log.e("d", "ppppp");
System.out.println(Listitem);
}
if (mListener != null)
mListener.myMethod(Listitem);
Please refer to my following sample code for sending an arraylist to another activity, then you can use its logic to your app. Hope this helps!
First of all, you need a class that implements Parcelable
public class Person implements Parcelable {
int id;
String name;
int age;
Person (Parcel in){
this.id = in.readInt();
this.name = in.readString();
this.age = in.readInt();
}
Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
dest.writeInt(this.age);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Then in MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Person> personArrayList = new ArrayList<>();
personArrayList.add(new Person(1, "Person A", 20));
personArrayList.add(new Person(2, "Person B", 30));
personArrayList.add(new Person(3, "Person C", 40));
Intent intent = new Intent(this,PersonsActivity.class);
intent.putExtra("Person_List", personArrayList);
startActivity(intent);
}
}
The PersonsActivity:
public class PersonsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persons);
Bundle bundle = getIntent().getExtras();
ArrayList<Person> personArrayList = bundle.getParcelableArrayList("Person_List");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Person person : personArrayList) {
Log.i("PersonsActivity", String.valueOf(person.id) + " | " + person.name + " | " + String.valueOf(person.age));
}
}
}
}
You will get the following logcat:
11-23 15:40:37.107 4051-4051/? I/PersonsActivity: 1 | Person A | 20
11-23 15:40:37.107 4051-4051/? I/PersonsActivity: 2 | Person B | 30
11-23 15:40:37.107 4051-4051/? I/PersonsActivity: 3 | Person C | 40
You can do this using following way
You can set position of a grid item(here image) you click as a tag to imageview and then you can get the json object or single object from array list using above position and can send to another activity.
holder.imageView.SetTag(position)
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get your imageview here by using v.findviewbyid and get tag tag
//Like this
//ImageView iv=(ImageView)v.findviewbyid(id of layout you mention to bind holder.imageView)
//Integer mPosition=(Integer)iv.getTag();
//Then fetch that single object by using mPosition from your list and pass it
//JSONObject item = peoples.getJSONObject(mPosition);
Log.d("OnImageButton", "Clicked");
Intent intnt =new Intent(mcontext, SingleViewActivity.class);
//intnt.putExtra("Contact_list", item);
mcontext.startActivity(intnt) ; //This line raises error
Toast.makeText(mcontext, "intent",
Toast.LENGTH_LONG).show();
}
});
//Make constant class and add all data in this arraylist:
//e.g : Constant.arrylist.add(<collection>);
public class Constant{
public static ArrayList<collection>() arrylist = new ArrayList<collection>()
}
//Pass arraylist data
Intent intent = new Intent(this,YourActivity.class);
intent.putInt("position", arrylist.get(position));
startActivity(intent);
//Get position in another activity
Bundle bundle = getIntent().getExtras();
int position = bundle.getInt("position",0);
//Now get Particular data
//e.g
String url = Constant.arrylist.get(position).<url(collection)>;
//And so on..!

Trouble passing ArrayList to another Activity

Good evening , I'm having trouble passing a ListView an Activity to another. The Activity code that passes to the other is the following called FiltrarImoveis.class :
for (int i = 0; i < jsonArray.length(); i++) {
Imovel imv = new Imovel();
JSONObject child = jsonArray.getJSONObject(i);
String finalidade=child.getString("finalidadeImovel");
String tipo = child.getString("tipoImovel");
String genero = child.getString("generoImovel");
String descricao = child.getString("descricaoImovel");
String responsavel = child.getString("responsavelImovel");
String telefoneResponsavel = child.getString("telefoneResponsavel");
String situacaoImovel = child.getString("situacaoImovel");
String valor = child.getString("valor");
imv.setFinalidade(finalidade);
imv.setTipo(tipo);
imv.setGenero(genero);
imv.setDescricao(descricao);
imv.setResponsavel(responsavel);
imv.setTelefoneResponsavel(telefoneResponsavel);
imv.setSituacao(situacaoImovel);
imv.setValor(valor);
listaImovel.add(imv);
}
} catch (JSONException e) {
e.printStackTrace();
}
//showParsedJSON.setText(output);
carregar(listaImovel);
}
}
}
public void carregar(ArrayList<Imovel> listaImovel){
Intent intent = new Intent(this,DetalhesImoveis.class);
intent.putExtra("lista",listaImovel);
startActivity(intent);
}
The class that inherits from the ListView is the following , call DetalhesImoveis.class :
private ListView lvImoveis;
ArrayList<Imovel> listaImoveis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalhes_imoveis);
listaImoveis = (ArrayList<Imovel>) getIntent().getSerializableExtra("lista");
lvImoveis = (ListView)findViewById(R.id.lvImoveis);
try {
ArrayAdapter<Imovel> adpImovel = new ArrayAdapter<Imovel>(DetalhesImoveis.this, android.R.layout.simple_list_item_1, listaImoveis);
lvImoveis.setAdapter(adpImovel);
//Log.v("LISTAiMOVEIS", "ELEMENTOS DA LISTA: " +listaImoveis.get(0).getDescricao().toString() );
}catch(Exception e){
Log.v("logs","ERROR CAUSED BY THE EXCEPTION LIST: "+e.toString());
}
}
We should not use putExtra()for ArrayList instead of that use putStringArrayListExtra() eg: public void carregar(ArrayList<Imovel> listaImovel){
Intent intent = new Intent(this,DetalhesImoveis.class);
intent.putStringArrayListExtra("lista",listaImovel);
and in DetalhesImoveis.class get the Arraylist like:listaImoveis = getIntent().getStringArrayListExtra("lista");
u can :
getIntent().putParcelableArrayListExtra(listaImovel)
Imovel need to implment Parcelable
u can look sth about Parcelable;
or :
AActvt Put list int application or a static var ;
BActvt get list from application or a static var;

Categories

Resources