passing arrays between classes using intents - android

i am developing a final year project where i need to retrieve details of hospitals like name ,address, location(in terms of latitude and longitude) from a server and display them on a map....connectivity has been established and i am able to retrieve the values in the from of array like address[], name[] etc..
now i need to pass these values from an activity class to map activity class...i am new to intents..can anyone please provide codes or relevant links which may be helpful in solving this problem
any help will be really appreciated....cheers :)

You can add data to an Intent using one of the putExtra routines. But serializing large amounts of data is expensive. Take a look here for alternatives.

I Suggest store that all necessary data in static list and then use that static .
public static List<String> name = new ArrayList<String>();
public static List<String> address = new ArrayList<String>();
public static List<String> latitude = new ArrayList<String>();
public static List<String> longitude = new ArrayList<String>();
name.add("your data");
address .add("your data");
latitude .add("your data");
longitude .add("your data");
then you can get all the data in any activity .

Related

Storing JSON data to local database in android

Okay so, I created an app that retrieves data from my server using JSON. Now I want to store the retrieved data on my phone's local storage/db. How do I do it? I am new in android programming.
This is the JSON that I receive from the server
{"messages":[{"id":"44","issender":0,"content":"CAT1DOG","date":"Jan 01, 1970 07:30 AM","sender":"Administrator","receiver":"User"},{"id":"57","issender":0,"content":"ttt","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"58","issender":0,"content":"s","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"82","issender":0,"content":"yeuwu","date":"Jun 30, 2016 04:59 PM","sender":"Administrator","receiver":"User"}],"success":1}
and this is my code to parse JSON
for(int i = 0; i < messages.length(); i++){
JSONObject o = messages.getJSONObject(i);
String msgid = o.getString("id");
String message = o.getString("content");
String date = o.getString("date");
String sender = o.getString("sender");
String receiver = o.getString("receiver");
String issender = o.getString("issender");
// TEMP HASHMAP FOR USER
HashMap<String, String> msgList = new HashMap<String, String>();
// ADDING EACH CHILD NOTE TO HASHMAP => VALUE
msgList.put("id", uid);
msgList.put("message", message);
msgList.put("date", date);
msgList.put("name", sender);
msgList.put("receivername", receiver);
// ADDING USER TO MSGLIST
ListOfMsg.add(msgList);
}
Thanks in advance for those who will answers. will appreciate it.
First I need to tell you that this is not the easy way out but for sure it is the correct one.
Next create a new class named Message
public class Message{
public String issender;
}
When you receive the json :
List<Message> messages= new ArrayList<>();
Gson gson = new Gson();
Message m= gson.fromJson(json.toString(),Message.class);
messages.add(m);
Please be careful that the items in the class should have the name as the items in the json you are trying to receive
Now we are done with this part:
Let us add the library for caching:
Follow this tutorial and if you need help get back to me:
https://guides.codepath.com/android/activeandroid-guide
or you could do the caching using sql old fashioned way
You can do this in two ways:
Use the new extension for json in sqite. The information you might need is available on this page https://www.sqlite.org/json1.html . Still I would suggest to do a little bit more of research on this, as it is new and I have not used it yet.
You can convert your json to string and insert it to the database.
String jsontostring = jsonObject.toString();

Android - What is the difference between data on String and on Sqlite database?

I am developing quiz app on Android. I have asked someone about storing data. All people prefer Sqlite database. I did.
But Why can't I use String data to display data, not Sqlite database?
Example for more detail:
Store in List:
List<String> questions = new ArrayList<String>();
questions.add("Question A?");
questions.add("Question B?");
questions.add("Question C?");
List<String> answers = new ArrayList<String>();
answers.add("Answer A");
answers.add("Answer B");
answers.add("Answer C");
Store in Sqlite
Question question0 = new Question("Question A?", "Answer A");
Question question1 = new Question("Question B?", "Answer B");
Question question2 = new Question("Question C?", "Answer C");
dbHelper.createQuestion(question0);
dbHelper.createQuestion(question1);
dbHelper.createQuestion(question2);
List<String> listQuestions = new ArrayList<String>();
listQuestions = dbHelper.getAllQuestions();
For you understanding you should know that a database my contain anything from a String to image, audio, Videos etc. So when you fetch data you need a cursor so in that you get data from database and use in your layout by casting Accordingly. But if you would use only String then it would not be possible to show all the data and perform operations.

Saving non-generic type objects persistently in Android without setting up a database

Basically I have an app that fetches some information from Facebook, and that info can be regularly updated. I want to save that information in the phone so that when the user does not have an internet connection he can still see the latest fetch.
The information is saved in a
ArrayList<HashMap<String, String>>
What should I use?
The amount of information to save is small. 7 entries in the HashMap and at most 15 in the ArrayList. I use this datatype because I display it in a ListView.
Again that info must be saved even is the app is closed.
Regards
you can write it to a json or xml file , and load that file when app started
I think the best way is to save it to SharedPreferences. An easy way is to convert this object to JSON String and store that String in the SharedPreferences, and then when needed, get JSON string back and convert it back to your object. The library that does it nicely is Google's gson library. If you are using Gradle, import it like this:
dependencies {
...
compile 'com.google.code.gson:gson:2.2.+'
...
}
then, you can use this simple class to convert objects to/from String
public class JsonHelper {
public static Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
public static Object getObject(String jsonString, Type classType){
return gson.fromJson(jsonString, classType);
}
public static String getJsonString(Object object){
return gson.toJson(object);
}
}
then, you can do this:
//to get JSON string from your object
ArrayList<HashMap<String, String>> yourList = ...;
String JSONString = JsonHelper.getJsonString(yourList);
//save string to shared preference
//to get your object from JSON string
//get JSON string from shared prefs
String yourJsonString = ...;
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
ArrayList<HashMap<String, String>> yourList = (ArrayList<HashMap<String, String>>)JsonHelper.getObject(yourJsonString, t);
here is some info about SharedPreferences and some info on how to use SharedPreferences, its really easy.
Then, you can add these methods to your Activity
public class YourActivity extends Activity{
public static final String KEY_PREFS = "com.your_app_name";
public static final String KEY_DATA = "your_data";
...
public static void saveDataToPrefs(String json){
getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE).edit().putString(KEY_DATA, json).commit();
}
public ArrayList<HashMap<String, String>> getDataFromPrefs(){
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
return (ArrayList<HashMap<String, String>>)JsonHelper
.getObject(getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE)
.getString(KEY_DATA, ""), t);
}
}
Please note this is not the best way to save the info in the app persistantly, as this method can produce unexpected bugs, like in case the final JSON string needs to be larger then the String object in the Android system. The best way is to have a database.
Have you looked at serialisation before? I find it very useful for this type of thing.
What is object serialization?
You can serialise out your data into an arbitrary file on the device SD card for example, then just read it back in on startup. I've used it for storing data in games, e.g. a save file.

Pass List<Double> value from one activity to other [duplicate]

This question already has answers here:
Pass ArrayList<Double> from one activity to another activity on android
(4 answers)
Closed 9 years ago.
I have a list like this,
List< Double> list_r = new ArrayList<Double>();
How can I pass this list from one activity to other ?
How can I pass this list from one activity to other ?
Then Make this list Static just like this:
public static List< Double> list_r = new ArrayList<Double>();
And Access this list in other activity like this:
private List<Double> list_my = ClassName.list_r;
Where ClassName is your Activity which consists (List< Double> list_r).
But make sure I am just showing a way of passing list. But by making List static It will consume memory even after you have finish the use of that arrayList.
You could use a double[] together with putExtra(String, double[]) and getDoubleArrayExtra(String).
Or you can use an ArrayList<Double> together with putExtra(String, Serializable) and getSerializableExtra(String) (the ArrayList part is important as it is Serializable, but the List interface is not).
You may use of bundle how to use: creating bundle and sending over to new activity or save arrayList in shared preferences: http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
intent.putExtra("list",list_r);
now on the other activity in onCreate:
getIntent().getParcelableArrayListExtra("list");
use intent.putExtra();
intent.putExtra("array_list", list_r );
Convert double to string, and put it in ArrayList.
In the Activity providing the data, use Intent#putExtra():
double double1 = 0.05;
double double2 = 0.02;
ArrayList <String []> list = new ArrayList <String[]>();
list.add (new String [] {String.valueOf(double_1),String.valueOf(double_2)});
Intent i = new Intent (this,YourTargetActivity.class);
i.putExtra("list", list);
startActivity(i);
Then to retrieve, use Intent#getSerializableExtra() and cast to ArrayList :
ArrayList <String[]> list = (ArrayList<String[]>) getIntent().getSerializableExtra("list");
double double1 = Double.parseDouble(list.get(0)[0]) ;
double double1 = Double.parseDouble(list.get(0)[1]) ;

How to retrieve data from ArrayList<ModelObject> not from ArrayList<String>?

Hi I'm still new to java data management.
I have a model object class named Computer which has 3 fields: processor, ram, hddSize.
I created a ArrayList
ArrayList<Computer> myCompList = new ArrayList<Computer>();
Computer comp1 = new Computer();
comp1.setProcessor("1.5 GHZ");
comp1.setRam("512 MB");
comp1.setHddSize("100 GB");
Computer comp2 = new Computer();
comp2.setProcessor("2.5 GHZ");
comp2.setRam("512 MB");
comp2.setHddSize("50 GB");
myCompList.add(comp1);
myCompList.add(comp2);
Now How can I retrieve data at index1 of the ArrayList above?
PS: I know how to do it if its a ArrayList< String> by convert it to String[] and then String[index].
Look at the Javadocs for ArrayList
This is where you should check for simple questions like this. The answer can be found in the "Method Summary" section.
Assuming that you have created getters and setters in your Computer class:
String processor = myCompList.get(1).getProcessor();
String ram = myCompList.get(1).getRam();
String hddSize = myCompList.get(1).getHddSize();
Can't you just go myCompList.get(0); ?
An arraylist of objects is essentially the same as an arraylist of strings. The .get() method returns the specific object at the given index. Here is the documentation for ArrayList.
myCompList.get(index) will return you data on the given index, make sure index number wouldn't be greater than array size, it will give you index out of bounds exception.

Categories

Resources