Access a varibale from MainActivity class to another class - java

I have a JSONObject in my MainActivity under a function and I want to use it outside the function and in another class, how can I do that?
I want to make this variable public, here is the code :
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
}
// System.out.println("*****JARRAY*****" + jsonMainNode.getJSONObject(0));
List<Map<String, String>> productLista = new ArrayList<Map<String, String>>();
JSONObject pro1 = jsonMainNode.getJSONObject(1);
String data = pro1.getString("name");
// System.out.println("*****JARRAY*****" + data);
System.out.println("*****JARRAY*****" + pro1);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
I want to make pro1 (which is JSONObject) public and use it outside public void and also use it in another class.
Can I do that using put or add?

try code below, it might help..
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

You will need to create the variable first outside any method like this
Static JSONObject pro1;
and then acces it simple by using
classname.pro1

you can declare that variable public.
just put
public static JSONObject pro1;
to your class declaration.
2. that is not safe because of:
1. that variable will vanish if your app will be killed and recreated by Android system.
2. you should be carefull when accessing that variable from other threads.

Related

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/

java.lang.IllegalArgumentException: Object would be serialized to `null`: Android

I have recently been setting up mobile apps to work with my meteor server. As a part of this I have to pass the meteor web app data from android. Unfortunately I have been receiving a error that tells me that the java object I am passing "would be serialized to null". How do I prevent this?
JSONObject json = new JSONObject();
try{
json.put("Foo", "1");
json.put("Blah", 0);
}catch (JSONException e){
}
Object[] object = new Object[1];
object[0] = json;
System.out.println(object + ", " + object[0] + ", " + object[0].toString());
mMeteor.call("xxx", object, new ResultListener() {
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error, String reason, String details) {
}
});
}
#Override
public void onError(String error, String reason, String details) {
}
});
Android/Meteor interface Library function
public void callWithSeed(final String methodName, final String randomSeed, final Object[] params, final ResultListener listener) {
// create a new unique ID for this request
final String callId = uniqueID();
// save a reference to the listener to be executed later
if (listener != null) {
mListeners.put(callId, listener);
}
// send the request
final Map<String, Object> data = new HashMap<String, Object>();
data.put(Protocol.Field.MESSAGE, Protocol.Message.METHOD);
data.put(Protocol.Field.METHOD, methodName);
data.put(Protocol.Field.ID, callId);
if (params != null) {
data.put(Protocol.Field.PARAMS, params);
}
if (randomSeed != null) {
data.put(Protocol.Field.RANDOM_SEED, randomSeed);
}
send(data);
}
I was having this same issue, my first error was passing a CharSequence instead a String as a parameter (your Object[]), and my other error was passing an Object[] as another parameter (I solved this by sending a String instead, like : String.valueOf(your_object_list)) Dont forget to handle this on your server side, you will receive a String instead of an Object.
Convert the JSONArray to List & JSONObject to HashMap and then pass those instead of the raw JSONObject or JSONArray.
You can write a recursive function for the conversion in case of nested JSONObject and JSONArray or can use GSON library for the conversion.
For more details about the conversion, this SO post may be helpful.

Save HashMap data into SQLite

I'm Trying to save data from Json into SQLite. For now I keep the data from Json into HashMap.
I already search it, and there's said use the ContentValues. But I still don't get it how to use it.
I try looking at this question save data to SQLite from json object using Hashmap in Android, but it doesn't help a lot.
Is there any option that I can use to save the data from HashMap into SQLite?
Here's My code.
MainHellobali.java
// Hashmap for ListView
ArrayList<HashMap<String, String>> all_itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_helloballi);
all_itemList = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new getAllItem().execute();
}
private class getAllItem extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
all_item = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < all_item.length(); i++) {
JSONObject c = all_item.getJSONObject(i);
String item_id = c.getString(TAG_ITEM_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
String item_name = c.getString(TAG_ITEM_NAME);
// tmp hashmap for single contact
HashMap<String, String> allItem = new HashMap<String, String>();
// adding each child node to HashMap key => value
allItem.put(TAG_ITEM_ID, item_id);
allItem.put(TAG_CATEGORY_NAME, category_name);
allItem.put(TAG_ITEM_NAME, item_name);
// adding contact to contact list
all_itemList.add(allItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
I have DatabasehHandler.java and AllItem.java too.
I can put it in here if its necessary.
Thanks before
** Add Edited Code **
// looping through All Contacts
for (int i = 0; i < all_item.length(); i++) {
JSONObject c = all_item.getJSONObject(i);
String item_id = c.getString(TAG_ITEM_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
String item_name = c.getString(TAG_ITEM_NAME);
DatabaseHandler databaseHandler = new DatabaseHandler(this); //error here "The Constructor DatabaseHandler(MainHellobali.getAllItem) is undefined
}
As mentioned by #birdy you can just store the JSON data as String inside your database.
In my case I've already done the same thing you are trying to achieve, in my case I've just created an abstract datasource that will be extended for any JSON object I will set in my database.
But basically you just need a method to convert a JSONObject to a ContentValues object.
public ContentValues jsonToContentValues(JSONObject json) {
ContentValues values = new ContentValues();
values.put("MY_COLUMN", json.optString("MY_JSON_VALUE"));
return values;
}
After you have your content value object all set you just need to insert the values on your database.
return database.insert("MY_TABLE_NAME", null, contentValues);
If what you need is to store JSON data - just store it as a text. Than after taking it back from database you can again parse it into map.

ArrayExceptionOut Of Bound

Updated Question from previous: I filled an array through HashMap, Iam using Asynctask for http request & after filling array put that array in dialog box. When I first run my app it gives me an empty dialog box & didn't give any error but when I re run my app it shows all array elements in dialog box perfectly. Whats the reason ?
//JsonResponse Inner Class in main class
private class JsonResponse extends AsyncTask<String, Void, String>
{
String response = "";
private ArrayList<HashMap<String, String>> prServices_resultList =
new ArrayList<HashMap<String, String>>();
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
int s=0;
for (HashMap<String, String> hashServices : prServices_resultList)
{
Db_Services[s] = hashServices.get(android_S_CName);
Db_ServicesID[s] = hashServices.get(android_S_ID);
s++;
}
}
}
protected String doInBackground(final String... args)
{
JSONParser jParser = new JSONParser();
JSONArray jArrayServices = jParser.getJSONFromUrl(url_Services);
try
{
for (int i = 0; i < jArrayServices.length(); i++)
{
JSONObject jsonElements = jArrayServices.getJSONObject(i);
String S_id = jsonElements.getString(android_S_ID);
String S_name = jsonElements.getString(android_S_NAME);
HashMap<String, String> hashServices = new HashMap<String, String>();
// adding each child node to HashMap key
hashServices.put(android_S_ID, S_id);
hashServices.put(android_S_NAME, S_name);
// adding HashList to ArrayList
prServices_resultList.add(hashServices);
}
response = "Success";
}
catch(JSONException e)
{
e.printStackTrace();
}
return response;
}
}
In my main class have have a button & when i press i execute AsyncTask:
new JsonResponse().execute;
In main class above onCreate i declare like:
static ArrayList<HashMap<String, String>> ResultList_Services =
new ArrayList<HashMap<String, String>>();
String[] Db_Services = new String[ResultList_Services.size()];
String[] Db_ServicesID = new String[ResultList_Services.size()];
You are creating an empty map here:
ResultList_Services = new ArrayList<HashMap<String, String>>();
Then trying to initialize two arrays with the size of an empty map - being zero.
// ResultList_Services.size() will be zero
String[] Db_Services = new String[ResultList_Services.size()];
String[] Db_ServicesID = new String[ResultList_Services.size()];
So when you try adding to these arrays it will throw an OutOfBoundsException
You could make these Arrays into lists, then you can dynamically add elements as needed without needing to specify a size to start with. If you then need an Array (for other Methods) you can get an array from a list using List#toArray()
As per your comment
You could just create temporary arrays to which you add all the elements and then assign this to your other arrays, something like
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
String[] tmp_dbServ = new String[prServices_resultList.size()];
String[] tmp_dbServID = new String[prServices_resultList.size()];
int s=0;
for (HashMap<String, String> hashServices : prServices_resultList)
{
tmp_dbServ[s] = hashServices.get(android_S_CName);
tmp_dbServID[s] = hashServices.get(android_S_ID);
s++;
}
Db_Services = tmp_dbServ;
Db_ServicesID = tmp_dbServID;
}
}

Passing an arraylist in array-android app

I have been referring this app to make a gallery module
https://github.com/nostra13/Android-Universal-Image-Loader
However according to the requirement in my app the images are dynamically added.So, I am fetching all the images via JSON.The image response from JSON Iam adding in the arraylist.
How should I pass "image_urls.add(folio.getString(i));" in the new class :
public class Test extends Activity{
private static String url = "http://www.xyz.com/album_pro/array_to_encode";
JSONArray folio = null;
ArrayList<String> urlList = new ArrayList<String>();
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
JSONParser jParser = new JSONParser();
{
try{
JSONObject json = jParser.getJSONFromUrl(url);
Log.v("URL",json.toString());
JSONObject seo = json.getJSONObject("SEO");
Log.v("seo",seo.toString());
JSONArray folio = seo.getJSONArray("Folio");
ArrayList<String> image_urls = new ArrayList<String>();
for(int i=0;i< folio.length();i++)
{
image_urls.add(folio.getString(i));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
How should I pass "image_urls.add(folio.getString(i));" in a non activity class named "Images"
i.e
public class Images {
public final static String[] imageUrls = new String[] {
**Required the arraylist of "Test" activity**
};
public final static String[] imageThumbUrls = new String[] {
**Required the arraylist of "Test" activity**
};
}
Make the ArrayList public and static and use it in other class as Test.urlList
Make the Images members non-final so that you can set them at runtime.
After your loop which add image urls to image_urls ArrayList, set the properties of Images class:
Images.imageUrls = image_urls.toArray();
Simple way is to make the image_urls as public static. since it contains only urls right? only small amount of data and in the Image class access that with
Test.image_urls.get(integer);

Categories

Resources