Trouble passing ArrayList to another Activity - android

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;

Related

Passing a string from AsyncTask to onCreate or other Activities

I am trying to query JSON data on a background thread using AsyncTask and use one of the values from the query in onCreate of the same Activity. How should I do this? Should I use intents or is there a more intuitive and better way of doing it?
In my code below, I am trying to pull the youtube ID using an AsyncTask out of an online database. It works because when I log the value inside the AsyncTask, the correct youtube ID is shown. But I need to use this ID in onCreate so that I can use it to create the full youtube URL. How can I pass the youtube ID string from doInBackground to onCreate? The id is stored in the variable youtubeId
//Activity needs added to manifest.
public class DetailsActivity extends AppCompatActivity {
//LOG tag for debugging
private static final String TAG = "GalleryActivity";
String youtubeIdCode;
//Override on Create and set contentView to new activity_details layout.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
//Log for debugging so we can tell if activity started successfully.
Log.d(TAG, "onCreate: started.");
loadMovieData();
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String image = movie.getMoviePoster();
String title = movie.getTitle();
String releaseDate = movie.getDate();
String voteAverage = movie.getVoteAverage();
String plot = movie.getPlot();
ImageView poster = findViewById(R.id.details_image);
Picasso.with(this).load(image).into(poster);
TextView name = findViewById(R.id.details_title);
name.setText((getResources().getString(R.string.movie_title)) + " " + title);
TextView dateRelease = findViewById(R.id.details_release_date);
dateRelease.setText((getResources().getString(R.string.release_date)) + " " + releaseDate);
TextView averageVote = findViewById(R.id.details_voter_average);
averageVote.setText((getResources().getString(R.string.vote_average)) + " " + voteAverage);
TextView moviePlot = findViewById(R.id.details_plot);
moviePlot.setText((getResources().getString(R.string.plot)) + " " + plot);
ImageView watchTrailer = findViewById(R.id.imageView);
// watchTrailer.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl.toString()));
// Log.v("OnClick URL",trailerUrl.toString());
// startActivity(intent);
// }
// });
}
public class FetchTrailer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String YOUTUBE_ID = "id";
final String RESULTS = "results";
String youtubeId = " ";
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String id = movie.getID();
final URL trailerUrl = NetworkUtils.buildUrlTrailer(id);
Log.v("Built trailer url", trailerUrl.toString());
try {
String jsonResponse = NetworkUtils.getReponseFromHttpUrl(trailerUrl);
JSONObject moviesObject = new JSONObject(jsonResponse);
JSONArray resultsArray = moviesObject.getJSONArray(RESULTS);
for(int i = 0; i < resultsArray.length(); i ++){
JSONObject movieObject = resultsArray.getJSONObject(i);
youtubeId = movieObject.getString(YOUTUBE_ID);
Log.v("youtubeid", youtubeId);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
//Tell the new method to get the data based on the search term within the url.
private void loadMovieData() {
//If there is a network connection, fetch the data.
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
new FetchTrailer().execute();
} else {
Toast toast = Toast.makeText(this, getString(R.string.no_internet_toast), Toast.LENGTH_LONG);
toast.show();
}
}
}
Seems youtubeId is a pre-requisite for your DetailsActivity. So we would need youtubeId prior to DetailsActivity initialization.
In your previous activity from where user can be landed to DetailsActivity , before calling startActivity(intent) call your
loadMovieData()
method as is, you would have to declare method in prior activity. After that pass the youtubeId through intent to DetailsActivity, and you can retrieve value in oncreate():
Intent myIntent = new Intent(CurrentActivity.this,
NextActivity.class);
myIntent.putExtra("youtubeId", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("youtubeId"); //if it's a string you
stored.
}
You can use a Callback Listener to achieve this
public interface FetchTrailerListener {
public void onTrailerFetched(String youtubeId);
}
Make DetailsActivity to implement this. Pass this listener reference to asynctask when you are instantiating it.In this way from your postexecute notify the activity through this listener.
protected void onPostExecute( String youtubeId) {
fetchTrailerListenr.onTrailerFetched(youtubeId);
}

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

Send data to new activity from listview JSON from mysql

I use bundle before but it only return null,
how can i get the name of the student_name that populated from database using json of the clicked item and show it into new activity?
public void ListDrawer() {
final List<Map<String, String>> studentList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
String outPut = name + "-" + number;
studentList.add(createStudent("Students", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
////////////////////////////////// UPDATE LISTVIEW ITEMS ONCLICK
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do your logic for getting the student variables here
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("student ", String.valueOf(id));
startActivity(intent);
}
});
//////////////////////////////////////UPDATE
SimpleAdapter simpleAdapter = new SimpleAdapter(this, studentList,
android.R.layout.simple_list_item_1,
new String[] { "Students" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
Toast.makeText(getApplication(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
Above is mylistview and my onItemClicked function
i use json to retrieve the list of students from mysql and view it in listview and now im trying to pass data from the selected student in listview to new activity
[1]: http://i.stack.imgur.com/zc56O.jpg
To add on #brahmyadigopula comment, using POJO is way more simpler and if you are already using JSON as preferd way, you can use Googles library for transforming JSON strings in to Objects with one line of code.
https://github.com/google/gson
Then you can just transform the object into JSON String with the same library and pass it through the Intent as String and 'catch' it in the Activity as a string and transform it back to an Object and use it as you'd wish.
It would look something like this:
public class User {
private String name;
private String number;
(getters/setters)
}
And then in your adapter you would do:
User user = new Gson().fromJson(jsonMainNode, User.class);
so you can then have a cleaner code when getting the data. So when passing the data with an intent you can just transform the User object to string by doing this: String jsonString = new Gson().toJson(user); and pass it through the intent.
Hope this helps.
For your adapter, you're using "android.R.layout.simple_list_item_1" as a layout for your list items. This will give you a simple TextView as a result and this TextView will contain the whole student information (name-number) as a full String variable.
I have 3 solutions for your problem :
1- Get the text of the item TextView and use split function to get the students info as follows :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get the item full text content
String studentInfo = listView.getItemAtPosition(position).toString();
//Split using the space " "
ArrayList<String> studentInfoArray = new ArrayList<>(Arrays.asList(studentInfo.split(" ")));
//Split using the dash "-"
String lastObject = studentInfoArray.get(studentInfoArray.size() - 1);
ArrayList<String> lastObjectInfoArray = new ArrayList<>(Arrays.asList(lastObject.split("-")));
//Rearrange the student name
//Sometimes the name is composed of more than two words
String studentName = "";
for (int i = 0; i < studentInfoArray.size() - 1; i++) {
studentName += " " + studentInfoArray.get(i);
}
studentName += " " + lastObjectInfoArray.get(0);
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", studentName);
intent.putExtra("studentID", lastObjectInfoArray.get(lastObjectInfoArray.size() - 1));
startActivity(intent);
}
});
2- Create a custom layout for your ListView adapter that will contain 2 TextViews in a LinearLayout, One for the name and One for the number. Then, you can easily get each info separately like this :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get the list item subviews using IDs of the custom item layout
TextView tvStudentName = (TextView)view.findViewById(R.id.tvStudentName);
TextView tvStudentNumber = (TextView)view.findViewById(R.id.tvStudentNumber);
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", tvStudentName.getText());
intent.putExtra("studentID", tvStudentNumber.getText());
startActivity(intent);
}
});
3- Make your student list as a global variable, then just get the info directly from the array :
public class MainPage extends Activity {
//Declare studentList as a global variable
List<Map<String, String>> studentList = new ArrayList<>();
.
.
.
//Change the structure of your ListDrawer method
public void ListDrawer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
//Add the student info to a new Hashmap object
//Add the student to the array
Map<String, String> studentInfo = new HashMap<>();
studentInfo.put("student_name", name);
studentInfo.put("student_id", number);
studentList.add(i, studentInfo);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
Then, send data to Profile activity :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", studentList.get(position).get("student_name"));
intent.putExtra("studentID", studentList.get(position).get("student_id"));
startActivity(intent);
}
});
Finally, to retrieve the info sent from MainPage Activity to Profile Activity :
public class Profile extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
Log.e("EXTRA", "Student Name : " + getIntent().getExtras().getString("studentName"));
Log.e("EXTRA", "Student ID : " + getIntent().getExtras().getString("studentID"));
}
}

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..!

Android: Passing extra from one activity to another activity

I have a JSON file which is populated to an activity (Main.java).
This Activity shows 3 random images from the URL on my JSON entries.
What I wanna do is: I have 13 different entries on the my JSON, whenever I click the shown random picture it goes to another activity (ProjectDetail.java) containing the picture,title,and description depends on the item I click based on its entry on the JSON.
What do I have in is by using extra by I dont know exactly how to perform that since I'm using JSON. What should I add into my top_listener method on my Main class and what should I add into my ProjectDetail class?
Thank you.
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
ArrayList<Project> prjcts=null;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
private final static String TAG = "MediaItemAdapter";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prjcts = new ArrayList<Project>();
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
String response = webService.webGet("", params);
try
{
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
List<Project> lst= new Gson().fromJson(response, collectionType);
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
final Button project = (Button) findViewById(R.id.btn_projectslist);
final Button infos = (Button) findViewById(R.id.btn_infos);
final Button contact = (Button) findViewById(R.id.btn_contact);
project.setOnClickListener(project_listener);
infos.setOnClickListener(infos_listener);
contact.setOnClickListener(contact_listener);
ImageView image1;
ImageView image2;
ImageView image3;
try {
image1 = (ImageView)findViewById(R.id.top1);
image2 = (ImageView)findViewById(R.id.top2);
image3 = (ImageView)findViewById(R.id.top3);
} catch( ClassCastException e ) {
Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
throw e;
}
Bitmap cachedImage1 = null;
Bitmap cachedImage2 = null;
Bitmap cachedImage3 = null;
//randomize the index of image entry
int max = prjcts.size();
List<Integer> indices = new ArrayList<Integer>(max);
for(int c = 0; c < max; ++c)
{
indices.add(c);
}
int arrIndex = (int)((double)indices.size() * Math.random());
int randomIndex1 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex2 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex3 = indices.get(arrIndex);
indices.remove(arrIndex);
setImage(cachedImage1, image1, prjcts.get(randomIndex1));
setImage(cachedImage2, image2, prjcts.get(randomIndex2));
setImage(cachedImage3, image3, prjcts.get(randomIndex3));
image1.setOnClickListener(top_listener);
image2.setOnClickListener(top_listener);
image3.setOnClickListener(top_listener);
}
public void setImage(Bitmap cachedImage, final ImageView image, Project pro)
{
//Bitmap cachedImage1 = null;
try {
cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener()
{
public void imageLoaded(Bitmap imageBitmap)
{
image.setImageBitmap(imageBitmap);
//notifyDataSetChanged();
}
});
} catch (MalformedURLException e) {
Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
}
if( cachedImage != null ) {
image.setImageBitmap(cachedImage);
}
}
private OnClickListener top_listener = new OnClickListener() {
public void onClick(View v) {
Intent top = new Intent(Main.this, InfosActivity.class);
startActivity(top);
}
};
ProjectDetail.java
public class ProjectDetail extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
Button weitersagen = (Button) findViewById(R.id.btn_weitersagen);
weitersagen.setOnClickListener(this);
Button sms = (Button) findViewById(R.id.btn_sms_spenden);
sms.setOnClickListener(this);
int position = getIntent().getExtras().getInt("spendino.de.ProjectDetail.position");
Project project = ConstantData.projectsList.get(position);
try {
ImageView projectImage = (ImageView)findViewById(R.id.project_image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(project.bigImageUrl).getContent());
projectImage.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView project_title = (TextView)findViewById(R.id.txt_project_title);
project_title.setText(project.project_title);
TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
organization_title.setText(Html.fromHtml("von " +project.organization_title));
TextView project_description = (TextView)findViewById(R.id.txt_project_description);
project_description.setText(Html.fromHtml(project.project_description));
}
I also have this ConstantData.java, the index which holds my JSON properties:
public class ConstantData{
public static String project_title = "project title";
public static String organization_title = "organization title";
public static String keyword = "keyword";
public static String short_code = "short code";
public static String project_description = "description";
public static String smallImageUrl = "smallImageUrl";
public static String bigImageUrl = "bigImageUrl";
public static String price= "price";
public static String country= "country";
public static ArrayList<Project> projectsList = new ArrayList<Project>();
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
out.writeString(organization_title);
out.writeString(keyword);
out.writeString(short_code);
out.writeString(project_description);
out.writeString(smallImageUrl);
out.writeString(bigImageUrl);
out.writeString(price);
out.writeString(country);
}
public static final Parcelable.Creator<ConstantData> CREATOR
= new Parcelable.Creator<ConstantData>() {
public ConstantData createFromParcel(Parcel in) {
return new ConstantData(in);
}
public ConstantData[] newArray(int size) {
return new ConstantData[size];
}
};
private ConstantData(Parcel in) {
project_title = in.readString();
organization_title = in.readString();
keyword = in.readString();
short_code = in.readString();
project_description = in.readString();
smallImageUrl = in.readString();
bigImageUrl = in.readString();
price = in.readString();
country = in.readString();
}
}
You could make the class ConstantData serializable by extending from Parcelable and implementing a couple of methods (see the documentation). Then you could pass a constantData instance as an extra by doing
intent.putExtra("jsonData", constantDataInstance);
and retrieving it from the other activity (in it's onCreate() method) with
getIntent().getExtras().getParcelable("jsonData");
Otherwise you could just past as extra every field independently, but it would be a mess. This way is not only more easy to read and everything, but "well designed".
To pass information from one activity to another when you start the new one you do the following:
Intent top = new Intent(Main.this, InfosActivity.class);
Bundle b = new Bundle();
b.putString("key1", "value2");
b.putString("key2", "value2");
b.putString("key3", "value3");
top.putExtras(b);
startActivity(top);
Then in the newly started activity, in the onCreate() put the following:
Bundle b = getIntent().getExtras();
b.get("key1");
b.get("key2");
b.get("key3");
This will get the values from the previous activity by using the key you provided.
For more complex objects you should extend Parcelable (probably what you'll need) and then use:
b.putParcelable("Key4", yourParcelableObject);
And in your onCreate()
b.getParcelable("Key4");
I hope this helps.
Use gson to parse the json to Java. Then you can use Wagon to move the extras around with ease.
GSON:
https://github.com/google/gson
Wagon:
https://github.com/beplaya/Wagon

Categories

Resources