Put List in sharedPreferences - java

I made class Employee and I also made List<Employee> which accept object from the the class.
I put three objects in that list and I want to save them after close the app. I try to use SharedPreferences to put the list but it seem that SharedPreferences does not accept to put list in it. How can I do it?
#Override
protected void onPause() {
super.onPause();
SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
// I cant use editor to put list<Employee>
}

Shared Preferences takes only string so you can't keep an object into shared preferences. This problem comes if you want to send Employee object from one activity to another activity
This is how i solved it:
Add the following library to your project(take the latest one):
'com.google.code.gson:gson:1.7.2'
You convert the Employee object to string and store in shared preferences:
Gson gson = new Gson();
String jsonString = gson.toJson(employeeObject);
//store this string in shared preferences and next time when you come back
//get string from shared preferences and convert this back to object
Gson gson = new Gson();
Employee example = gson.fromJson(jsonString, Employee.class);
Comment below if you have doubts

This isn't exactly the answer using shared preferences but thought it may help
Serialize an object and pass it around :
I use the code below and then write a class that will have any variables rather than shared preferences that is not dependable.
public class SharedVariables {
public static <S extends Serializable> void writeObject(
final Context context, String key, S serializableObject) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.getApplicationContext().openFileOutput(key, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serializableObject);
fileOut.getFD().sync();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
}
public static <S extends Serializable> S readObject(
final Context context, String key, Class<S> serializableClass) {
ObjectInputStream objectIn = null;
try {
FileInputStream fileIn = context.getApplicationContext().openFileInput(key);
objectIn = new ObjectInputStream(fileIn);
final Object object = objectIn.readObject();
return serializableClass.cast(object);
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} catch (ClassNotFoundException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
return null;
}}
Then example class:
public class Timestamps implements Serializable {
private float timestampServer;
public float getTimestampServer() {
return timestampServer;
}
public void setTimestampServer(float timestampServer) {
this.timestampServer = timestampServer;
}
}
Then in activity:
SharedVariables.writeObject(getApplicationContext(), "Timestamps", timestampsData);

You can't store a list of objects in sharedPrefs, but you can store a Set of String:
#Override
protected void onPause() {
super.onPause();
// Your list of epmloyees
List<Employee> someList;
// The Set to store the converted objects
Set<String> objects = new HashSet<String>();
// Convert each Object into a JSON-String
for (Employee e : someList) {
objects.add(new Gson().toJson(e));
}
SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
// Store the Set of JSON-String into the sharedPrefs
editor.putStringSet("key", objects);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
// Empty list of employees
List<Employee> someList = new ArrayList<>();
// Set of JSON-Strings from the sharedPrefs
Set<String> objects = data.getStringSet("key", null);
// Convert each JSON-String into an Object of Employee
for (String s : objects) {
objects.add(new Gson().fromJson(s, Employee.class);
}
}
In order to store your custom objects as a string, you need to serialize them (for example as json) and save this string. On loading the value you need to deserialize them.
You can read this guide for advanced help on how to serialize Objects into JSON.

Related

Overwrite json file after exiting app and relaunching

I'm trying to save a single int to a file in my Android project although i cant get my write function to work.
My JSON file:
{
"user":
{
"userid":"0"
}
}
My code:
public String getJsonFile() {
String jsonLocation = "";
try {
InputStream is = getAssets().open("useriidd.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonLocation = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
return jsonLocation;
}
public void jsonRead(){
try {
JSONObject reader = new JSONObject(getJsonFile());
JSONObject sys = reader.getJSONObject("user");
userid = Integer.parseInt(sys.getString("userid"));
}
catch (final JSONException e) {
Log.e("asdasd", e.getMessage());
}
}
public void jsonWrite(){
try {
JSONObject writer = new JSONObject(getJsonFile());
JSONObject sys = writer.getJSONObject("user");
sys.put("userid", Integer.toString(userid));
Log.d("asdasd", getJsonFile());
}
catch (final JSONException e) {
Log.e("asdasd", e.getMessage());
}
}
I need the userid value to also be saved if i exit the app and relaunch it.
You should store it in Preferences, SharedPreferences or in the file on external storage (SD card). You cannot (or should not) edit the assets in run-time.
Declare on Class level
public static final String KEY = "key";
private String value = "you can place any value";
private SharedPreferences sharedPreferences;
onCreate Method
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourMainActivity.this);
sharedPreferences.edit().putString(KEY, value);
onResume Method
value = sharedPreferences.getString(KEY, "defaultValue");
You can also do this step on onPause Method
sharedPreferences.edit().putString(KEY, value);

errors when static and when not static (specific)

I know the title doesn't say much, but I have a pretty specific problem that is difficult to describe:
I'm making an android app with Android Studio, and for one activity I have a list where the values that are stored in a json file will go.
For getting these values I use another class with a get() method which returns the values in an arraylist. The problem is that the IDE says 2 contrary statements: in the activity class it says that the get() method has to be static and in the other class it says that the get() method can't be static.
This is the code:
CompanySelector.java (the activity)
public class CompanySelector extends AppCompatActivity {
ArrayList<String> companyList = CompanyStorage.get();
}
==> here it gives an error in CompanyStorage.get() and says that get() should be static.
CompanyStorage.java (the other class)
abstract class CompanyStorage extends Context {
private ArrayList<String> companyList;
protected CompanyStorage() throws JSONException {
companyList = get();
}
ArrayList<String> get() throws JSONException {
JSONObject companyData = new JSONObject();
ArrayList<String> companyList = new ArrayList<>();
// Open data.json and convert to JSONObject
String json = OpenFileAsString("data.json");
try {
companyData = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return json array as ArrayList
if (companyData.getJSONArray("companies") != null) {
for (int i=0;i<companyData.getJSONArray("companies").length();i++){
companyList.add(companyData.getJSONArray("companies").getString(i));
}
}
return companyList;
}
public String OpenFileAsString(String filename) {
try {
InputStream stream = getAssets().open( filename );
int size = stream.available();
byte[] bytes = new byte[size];
stream.read(bytes);
stream.close();
return new String( bytes );
} catch ( IOException e ) {
Log.i("GuiFormData", "IOException: " + e.getMessage() );
}
return null;
}
}
==> Here it says that if get() is static, OpenFileAsString() should also be static, but then it gives an error, because getAssets() can't be in a static method.
Does anyone know what I should do? I'm fairly new to Java and application design..
Try to put static at the get() and OpenFileAsString(String filename) methods header and use context.getAssets() instead of getAssets()

Fetching data from an API with JSON and storing two objects in a single row of an Array Adapter

I've got this code with fetches the "rate" data from an API, along with "rate", I need to get the "name". If I get "name" it often binds it below the "rate".
I need it to join on the same row of the List View, so it is like [Rate Name].
I need to get two objects of a JSON Array and bind it to the array adapter so I can display two objects in the same row of a List View so it is more user friendly.
The code below is of the AsyncTask, the code works fine but I need to add one more object and make sure it is displayed as one rate - one name and then iterating through the loop and adding more as needed in the same order.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
// the url of the web service to call
String yourServiceUrl = "eg: URL";
#Override
protected void onPreExecute() {
}
String filename = "bitData";
#Override
protected String doInBackground(String... arg0) {
try {
// create new instance of the httpConnect class
httpConnect jParser = new httpConnect();
// get json string from service url
String json = jParser.getJSONFromUrl(yourServiceUrl);
// parse returned json string into json array
JSONArray jsonArray = new JSONArray(json);
// loop through json array and add each currency to item in arrayList
//Custom Loop Initialise
for (int i = 1; i < 8; i++) {
JSONObject json_message = jsonArray.getJSONObject(i);
// The second JSONObject which needs to be added
JSONObject json_name = jsonArray.getJSONObject(i);
if (json_message != null) {
//add each currency to ArrayList as an item
items.add(json_message.getString("rate"));
String bitData = json_message.getString("rate");
String writeData = bitData + ',' +'\n';
FileOutputStream outputStream;
File file = getFileStreamPath(filename);
// first check if file exists, if not create it
if (file == null || !file.exists()) {
try {
outputStream = openFileOutput(filename, MODE_PRIVATE);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// if file already exists then append bit data to it
else if (file.exists()) {
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// below method will run when service HTTP request is complete, will then bind text in arrayList to ListView
#Override
protected void onPostExecute(String strFromDoInBg) {
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
}
}
Just Create Custom Class Messsage:
public class Item{
private String name;
private String rate;
public void Message(String n, String r){
this.name=n;
this.rate=r;
}
// create here getter and setter
}
Now in your background, you have to add name and rate in Message class
Public class MainAcitity extends Activity{
public static List<Item> items= new ArrayList<>();// define in inside the class
// this has to be down on background
Item i=new Item(json_message.getString("name"),json_message.getString("rate"));
items.add(i);
Now pass this listmessge onPostExecute :
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
Is that any helpful for you.
Follow this link.You will get my point.
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

How to convert from a List to Array ? Android

okay guys, here is the thing, I have one application consuming ODATA service, in SMP server, I'm getting this Data like this:
public class callService extends AsyncTask<Void, Void, ArrayList<String>>
{
public ArrayList<String> doInBackground(Void... params)
{
ODataConsumer c = ODataJerseyConsumer.create("http://MyUrlService:8080");
List<OEntity> listEntities = c.getEntities("MYENTITYTOCONSUME").execute().toList();
System.out.println("Size" + listEntities.size());
if (listEntities.size() > 0)
{
for (OEntity entity : listEntities)
{
zmob_kunnr.add((String) entity.getProperty("Name1").getValue()
+ " - "
+ entity.getProperty("Kunnr").getValue().toString());
}
}
return zmob_kunnr;
}
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
adapter = new ArrayAdapter<String>(ConsumoKnuur.this, android.R.layout.simple_list_item_1, result);
list.setAdapter(adapter);
}
}
Okay I got this solution from web and could implement as list, and I need to store this entity which one is a List of customers and get the two attributes from this entity and save in my database so:
Entity Customer:Custormer_ID, Customer_Name
Here is my code to call my sqlite:
public void sqlite()
{
sql_obj.open();
sql_obj.deleteAll();
for(int i=0; i < zmob_kunnr.size(); i++)
{
sql_obj.insert(zmob_kunnr.get(i).toString(), zmob_kunnr.get(i).toString() );
}
sql_obj.close();
}
And my SQLite:
private static final String TABLE_CLIENTE = "CREATE TABLE "
+ TB_CLIENTE
+ "(ID_CLIENTE INTEGER PRIMARY KEY AUTOINCREMENT, " //Id for controller my logics
+ " Kunnr TEXT , " //customer ID
+ " Name1 TEXT );"; //customer_name
public long insert(String name1, String Kunnr)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name1", Name1); //Customer_Name
initialValues.put("Kunnr", Kunnr); //Customer_ID
return database.insert(TB_CLIENTE, null, initialValues);
}
And off course my other methods, that is not important, so whats happening when I run my "for" in the sql call method, I get the size() of the list and the rows of the list and store the entire row in the one column of the database each time, so I got two different tables with the same values,
how can I change solve this problem instead of consume in list I need to consume in array ? or I need to create a method that get the list values and after a ,(coma) , create two differents objects to store these data ??
I took a long look in the internet and didn't find nothing, probably it's because i don't know yet, how so, I don't know for what I'm looking for it, I'm using the odata4j API and here is the link of the documentation, http://odata4j.org/v/0.7/javadoc/
I'm new on programming, so I'm really in trouble with this, any suggestions any helps will be truly, appreciate,
Thanks a lot and have a nice day !!!
You can add each entity to the `ArrayList' array by doing the following:
for (OEntity entity : listEntities) {
zmob_kunnr.add(entity);
}
This will allow you to access the data contained in the entity via getProperty() when inserted into the database.
The following statement is also not needed, as the for each loop runs through every element in the list, thus for (OEntity entity : listEntities) will not execute if the list is empty.
if (listEntities.size() > 0) {
...
}
If you have multiple ODataConsumers, you have two choices, depending on your requirements (if I understand you question correctly):
You can sequentially get each ODataConsumer, get the listEntities, and add it to the zmob_kunnr list, and after the list items are added to the database, clear the zmob_kunnr list, and call doInBackground with a new URL. This is what your current solution allows.
It appears to need to know which property is associated with a URL when reading the values into the DB. You can use a POJO as a holder for the entity and its list of properties. You can now add and remove properties. Note that properties will be removed in the same order they where inserted.
public class OEntityHolder {
private final OEntity entity;
private Queue<String> properties;
public OEntityHolder(OEntity entity) {
this.entity = entity;
this.properties = new LinkedBlockingQueue<>();
}
public OEntity getEntity() {
return this.entity;
}
public void addProperty(String property) {
this.properties.add(property);
}
public void removeProperty() {
this.properties.poll();
}
}
This will require a change to the list holding the entities:
ArrayList<OEntityHolder> zmob_entity_holders = new ArrayList<>();
If you would like to add all the entities from the different URLs at the same time, you will need to have access to all the URLs when doInBackground is called. Something like this:
public ArrayList<OEntityHolder> doInBackground(Void... params) {
String [][] urls = {{"http:MyUrl/ZMOB_FECODSet", "Name1", "Fecod"},
{"http:MyUrl/ZMOB_OTEILSet", "Name2", "Oteil"},
{"http:MyUrl/ZMOB_KUNNRSet", "Name3", "Kunnr"},
{"http:MyUrl/ZMOB_BAULTSet", "Name4", "Bault"}};
for (String [] urlProp:urls) {
//Here you get the list of entities from the url
List<OEntity> listEntities = ODataJerseyConsumer.create(urlProp[0]).getEntities("MYENTITYTOCONSUME").execute().toList();
for (OEntity entity:listEntities) {
OEntityHolder holder = new OEntityHolder(entity);
for (int i = 1; i < urlProp.length; i++)
holder.addProperty(urlProp[i]);
zmob_entity_holders.add(holder);
}
}
//At this point, all of the entities associated with the list of URLS will be added to the list
return zmob_entity_holders;
}
You now have ALL of the entities associated with the list of URLs in zmob_kunnr. Before you can and can insert then into the DB like so:
for (OEntityHolder holder : zmob_entity_holders) {
sql_obj.insert(holder.getEntity().getProperty(holder.removeProperty()).toString(), holder.getEntity().getProperty(holder.removeProperty()).toString());
}
If each entity has a associated name, you can store the names in a map, where the key is the URL and the value the name.
HashMap<String, String> urlEntityNames = new HashMap<>();
urlEntityNames.put("http://MyUrlService:8080", "MYENTITYTOCONSUME");
...//Add more URLs and entity names
You can then, when running through the list of entities, do a look-up in the map to find the correct name:
List<OEntity> listEntities = ODataJerseyConsumer.create(url).getEntities(urlEntityNames.get(url)).execute().toList();
I hope this helps, if I misunderstood you just correct me in the comments.
EDIT: Added list of URLs, holder and DB insert.
I guess i found a solution, but my log cat, is giving an exception to me any updtades about my 2nd doInBackgroundBault (Material),
public class callServiceCliente extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressC = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Clientes", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer ccli = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesKunnr = ccli.getEntities("ZMOB_KUNNRSet").execute().toList();
System.out.println("Size" + listEntitiesKunnr.size());
for (OEntity entityKunnr : listEntitiesKunnr) {
zmob_kunnr.add(entityKunnr);
}
return zmob_kunnr;
}
protected void onPostExecute(ArrayList<OEntity> kunnr) {
super.onPostExecute(kunnr);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int k = 0; k < zmob_kunnr.size(); k++) {
sql_obj.insertCliente(zmob_kunnr.get(k).getProperty("Kunnr").getValue().toString().toUpperCase(), zmob_kunnr.get(k).getProperty("Name1").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
clienteAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, kunnr);
listCliente.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressC.dismiss();
new callServiceMaterial().execute();
}
}
public class callServiceMaterial extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressM = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Materiais", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer cmat = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList();
System.out.println("Size" + listEntitiesBault.size());
for (OEntity entityBault : listEntitiesBault) {
zmob_bault.add(entityBault);
}
return zmob_bault;
}
protected void onPostExecute(ArrayList<OEntity> bault) {
super.onPostExecute(bault);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int b = 0; b < zmob_bault.size(); b++) {
sql_obj.insertMaterial(zmob_bault.get(b).getProperty("Matnr").getValue().toString().toUpperCase(), zmob_bault.get(b).getProperty("Maktxt").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
materialAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, bault);
listMaterial.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressM.dismiss();
new callServiceProblema().execute();
}
}
public class callServiceProblema extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressProb = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando Problemas", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer cprob = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesFecod = cprob.getEntities("ZMOB_FECODSet").execute().toList();
System.out.println("Size" + listEntitiesFecod.size());
for (OEntity entityFecod : listEntitiesFecod) {
zmob_fecod.add(entityFecod);
}
return zmob_fecod;
}
protected void onPostExecute(ArrayList<OEntity> fecod) {
super.onPostExecute(fecod);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int f = 0; f < zmob_fecod.size(); f++) {
sql_obj.insertProblema(zmob_fecod.get(f).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_fecod.get(f).getProperty("Kurztext").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
problemaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, fecod);
listProblema.setAdapter(problemaAdapter);
} catch (Exception eq) {
}
progressProb.dismiss();
new callServiceProcedencia().execute();
}
}
public class callServiceProcedencia extends AsyncTask<Void, Void, ArrayList<OEntity>> {
protected void onPreExecute() {
progressProc = ProgressDialog.show(Atualizar_Dados.this, "Aguarde...", "Atualizando base de dados", true, true);
}
public ArrayList<OEntity> doInBackground(Void... params) {
ODataConsumer c = ODataJerseyConsumer.create(URL);
List<OEntity> listEntitiesProcedencia = c.getEntities("ZMOB_OTEILSet").execute().toList();
System.out.println("Size" + listEntitiesProcedencia.size());
for (OEntity entityProcedencia : listEntitiesProcedencia) {
zmob_oteil.add(entityProcedencia);
}
return zmob_oteil;
}
protected void onPostExecute(ArrayList<OEntity> oteil) {
super.onPostExecute(oteil);
try {
sql_obj.open();
sql_obj.deleteAll();
for (int o = 0; o < zmob_oteil.size(); o++) {
sql_obj.insertCliente(zmob_oteil.get(o).getProperty("Fecod").getValue().toString().toUpperCase(), zmob_oteil.get(o).getProperty("Kurztext").getValue().toString().toUpperCase());
}
sql_obj.close();
} catch (Exception e) {
}
try {
procedenciaAdapter = new ArrayAdapter<OEntity>(Atualizar_Dados.this, android.R.layout.simple_list_item_1, oteil);
// listCliente.setAdapter(clienteAdapter);
} catch (Exception eq) {
}
progressProc.show(Atualizar_Dados.this, "Finalizado", "Base de dados atualizada", true, true).dismiss();
Toast.makeText(Atualizar_Dados.this, "Base de dados atualizada com sucesso", Toast.LENGTH_LONG).show();
}
}
Okay, so here is the solution that i find, and i couldn't insert your solution because, when i put inser.add(entity), they didn't show me the properties but if you have a better way to do what i did, i will really appreciate,
and by the way i need to query this consume by range date in the filter(). like i did here...
List listEntitiesBault = cmat.getEntities("ZMOB_BAULTSet").filter("IErsda eq '20141101'").execute().toList(); but isn't working, so i don't have any ideas why, i saw couple close solution on the internet and saw fields like .top(1) and .first(); that i didn't understand...
thanks a lot !!!

Efficient way of downloading data in Android App from MySQL

I was just wondering if my code is ok in terms of downloading. My app needs a lot of data from a database so quick download times are crucial. The download time is ok but I think it can be programmed more efficient. Can you have a look at this? This class downloads many different companies and when downloaded they are put in a HashMap corresponding to their category. When finished downloading this class return a HashMap which contains multiple Hashmaps(categories) and in these Hashmaps the downloaded data. Dont mind the actual workflow but please concentrate on the way this class downloads data. Is there a way to do this faster?
public class CompanyDAO {
private static Controller delegate;
private static String companyUrl = "http:// URL HERE";
private Map<Object, Object> companyMap = new HashMap<Object, Object>();
private Map<String, Integer> pinMap = new HashMap<String, Integer>();
public CompanyDAO (Controller _delegate, Map<String, Integer> map) {
delegate = _delegate; //reference to controller
pinMap = map;
}
public void getCompanyData(ArrayList<Object> categoriesArray) {
for (int i = 0; i < categoriesArray.size(); i++) {
Map<String, Object> categoriesInMap = new HashMap<String, Object>();
//ArrayList<Object> categoriesInMapArray = new ArrayList<Object>();
companyMap.put(categoriesArray.get(i), categoriesInMap);
}
this.downloadCompanyData();
}
private void downloadCompanyData() {
companyUrl = companyUrl + delegate.ID;
try {
new DownloadCompanyData().execute(companyUrl).get(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DownloadCompanyData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(String result) {
JSONArray companyDataArray;
try {
companyDataArray = new JSONArray(result);
for(int i=0;i<companyDataArray.length();i++){
JSONObject id = companyDataArray.getJSONObject(i);
String catName = id.getString(Controller.CAT_NAME);
if (companyMap.get(catName) != null) {
Markers marker = new Markers(new LatLng(id.getDouble("latitude"), id.getDouble("longitude")), id.getString(Controller.CAT_NAME), id.getString(Controller.ID), id.getString(Controller.SUBSCRIPTION), pinMap.get(catName), id.getString(Controller.TITLE), id.getString(Controller.COMPANY_NAME), id.getString(Controller.WWW), id.getString(Controller.STREET), id.getString(Controller.HOUSE_NUMBER), id.getString(Controller.HOUSE_ADD));
((Map<String,Object>) companyMap.get(catName)).put(id.getString(Controller.TITLE), marker.markerInformationMap);
}
}
delegate.setCompanyHashMap(companyMap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I guess you're missing the point of the AsyncTask
it's supposed to do all the work in doInBackground() and then use the onPostExecute to deliver it to the UI.
But what you're doing is doing the network operation on doInBackground and doing data parsing on onPostExecute.
Furthermore, a JSON object is a raw data that needs further parsing. You should do all the parsing on the background. For example, let's say your companyData is address, phone number, size and name. You could have a class like this (p.s. I'm writing all this without testing, there will be a little mistake here in there, but you'll get the idea):
public class CompanyData{
private String name, address, phone;
private int size;
public CompanyData(JsonObject jo){
name = jo.getString("name");
address = jo.getString("address");
phone = jo.getString("phone");
size = jo.getInt("size");
}
// put a bunch of get methods here...
// getName(), getAddress(), etc.
}
then on your 'protected Map doInBackground(String... urls) ' you complete the network operation, create the JsonArray, create a Map<String,CompanyData>, loop through the array creating CompanyData objects and placing them into the Map and return the map to your protected void onPostExecute(Map<String,CompanyData> result) and inside the post execute it's just pass this result to the UI.
happy coding.
I always doing something like this..
...
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> CompanyList;
JSONParser jParser = new JSONParser();
JSONArray Company = null;
static String url_all_company = "http://your_site/files.php";
....
private class CompanyData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Load data..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
CompanyList = new ArrayList<HashMap<String, String>>();
// Building Parameters if any.. to fetching all data, don't declare any param
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_company, "POST", param);
// Check your log cat for JSON reponse
Log.d("All Company: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Company found
// Getting Array of Company
Company = json.getJSONArray(TAG_COMPANIES);
// looping through All Company
for (int i = 0; i < Company.length(); i++) {
JSONObject json = Company.getJSONObject(i);
// Storing each json item in variable
String id = json.getString(TAG_GID);
String name = json.getString(TAG_NAME);
String jml = json.getString(TAG_EMPLOYEE);
String deskripsi = json.getString(TAG_DESKRIPSI);
String logo = json.getString(TAG_LOGO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_GID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMPLOYEE, jml);
map.put(TAG_DESKRIPSI, deskripsi);
map.put(TAG_LOGO, logo);
// adding HashList to ArrayList
CompanyList.add(map);
}
} else {
// no CompanyList found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing data ArrayList
adapter=new LazyAdapter(MainActivity.this, CompanyList);
list.setAdapter(adapter);
pDialog.dismiss();
}
}

Categories

Resources