I have an ArrayList called results that uses the class ItemObjects when I want to add an item in results. My problem is that I cannot manage to retrieve a specific String from an item.
The class code is:
public class ItemObjects {
private String mText1;
private String mText2;
public ItemObjects(String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
And I use the following code to add an item into the ArrayList:
ArrayList results = new ArrayList<ItemObjects>();
//THis part goes inside a for using i as increment;
ItemObjects obj = new ItemObjects(type, sender);
results.add(i , obj);
I have tried several things to retrieve the data such as:
String type = ItemObjects.getmText1();
or:
String type= results.get(i);
the first try, only retrieves the mText1 from the first item, and the second is an object and I dn't know how i should get the mText1 from it.
Any help would be appreciated :)
For adding the Value
ArrayList<ItemObjects> results = new ArrayList<ItemObjects>();
ItemObjects obj = new ItemObjects(type, sender);
results.add(obj);
For getting the Value
for (int i=0, i<result.size(); i++)
{
String type = results.get(i).mText1;
String sender= results.get(i).mText2;
Toast.makeText(this, "" + type, Toast.LENGTH_LONG).show();
Toast.makeText(this, "" + sender, Toast.LENGTH_LONG).show();
}
Change
ArrayList results = new ArrayList<ItemObjects>();
to
ArrayList<ItemObjects> results = new ArrayList<>();
Then results.get() will return ItemObjects.
Or you can simply cast your current result.get() to ItemObjects
Related
I try to get number of post from arraylist in the class into mainactivity.
But it is wrong .
Here is my code.
public static int countNotify;
public static List<Notification> bindNotifyData(JsonElement list)
{
List<Notification> results= new ArrayList<>();
JsonObject dataJsonObj = list.getAsJsonObject();
// get data api from Json array "updates"
JsonArray notifyJsonArray = dataJsonObj.get("updates").getAsJsonArray();
ArrayList<Notification> notifyList = new ArrayList<>();
countNotify=notifyJsonArray.size();
if(notifyJsonArray != null && notifyJsonArray.size() > 0) {
for(int i = 0; i < notifyJsonArray.size(); i++) {
JsonObject notifyJson = (JsonObject) notifyJsonArray.get(i);
Notification notification = new Notification();
notification.setContent(notifyJson.get("content").getAsString());
// Convert timestamp to Datetime
String timestamp= notifyJson.get("time").getAsString();
notification.setTime(ConvertTimestamp(timestamp));
results.add(notification);
// count numbers of the post in the list json array.
}
}
return results;
}
And in the MainActivity.class
final int count=BindFetchDataHelper.countNotify;
But the value of count always is 0
Try to create a instance of your class
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
and then call final int count=bindFetchDataHelper.countNotify;
I had the same issue, it should work now.
EDIT
Try like this :
public class BindFetchDataHelper {
private static int sTest;
static {
public static int countNotify=0;
}
public static int getcountNotify() {
return countNotify;
}
public static void setcountNotify(int setcountNotify) {
this.countNotify = countNotify;
}
//your others functions
}
And now to access variable or to set it :
BindFetchDataHelper bindFetchDataHelper = new BindFetchDataHelper ()
bindFetchDataHelper.setcountNotify(YOURVALUE); //set
int whatyourwant = bindFetchDataHelper.getcountNotify(); //get
I am trying to parse the response I get from my OkHttp3Connection and it always almost always returns me String with value "true" which is names[0] in this example.
Now I try to convert this string to boolean and return true/false depending on the response. Now I guess since the OkHttp3Connection takes some time it doesnt let the query to finish and returns false which is the default value.
What I was trying to say is that this function always returns false no matter what String names[0] is.
public boolean checkIfSongPurhcased(String songName){
final boolean[] songCheckResult = new boolean[1];
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.GET_SONG_PURCHASED, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String userTag) throws JSONException {
JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
JSONArray arr = data.getJSONArray(i);
JSONObject dataObj = arr.getJSONObject(0);
Iterator<String> keys = dataObj.keys();
names[i] = dataObj.getString(keys.next());
}
//names[0] is "true"
songCheckResult[0] = Boolean.parseBoolean(names[0]);
}
}
#Override
public void onError(String error, String userTag) {
System.out.println("songy" + error);
}
}
);
//always returns false
return songCheckResult[0];
How can I make it so if names[0] is "true" it would give me true.
You should pass the listener/callback.
First create callback interface like below
public interface OnQueryResultCallback{
void onQueryResult(String songName, boolean status);
}
Then pass listener/callback to your method, here is the modified method.
public void checkIfSongPurhcased(final String songName, final OnQueryResultCallback listener){
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.GET_SONG_PURCHASED, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String userTag) throws JSONException {
JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
JSONArray arr = data.getJSONArray(i);
JSONObject dataObj = arr.getJSONObject(0);
Iterator<String> keys = dataObj.keys();
names[i] = dataObj.getString(keys.next());
}
//names[0] is "true"
boolean status = Boolean.parseBoolean(names[0]);
listener.onQueryResult(songName,status);
}
}
#Override
public void onError(String error, String userTag) {
System.out.println("songy" + error);
listener.onQueryResult(songName,false);
}
}
);
}
Then call checkIfSongPurhcased like below
checkIfSongPurhcased("songName", new OnQueryResultCallback(){
public void onQueryResult(String songName, boolean status){
if(status){
// do something on success
}else{
// do something on failure
}
}
});
Try to use getBoolean() rather than getString().
For Eg: names[i] = dataObj.getBoolean(keys.next());
I am new in android development i want to insert call log details in MySQL database. so, from android side i am getting an arrayList and i have converted that list into string[] array but i am not able to insert this array in database here i am insert the whole data with HashMap<String,Array>. but hashsmap is not able to take array arguement as string[] array. plz help to sort out this problem thanks in advance
here is java code..
public class MainActivity extends AppCompatActivity {
ArrayList<String> arrayList;
String phNum,callType,samay,callDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView animalList=(ListView)findViewById(R.id.listView);
arrayList = new ArrayList<String>();
getCallDetails();
// Create The Adapter with passing ArrayList as 3rd parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayList);
// Set The Adapter
animalList.setAdapter(arrayAdapter);
}
private void getCallDetails() {
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
/* Query the CallLog Content Provider */
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
null, null, strOrder);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
while (managedCursor.moveToNext()) {
phNum = managedCursor.getString(number);
String callTypeCode = managedCursor.getString(type);
String strcallDate = managedCursor.getString(date);
Date callDate = new Date(Long.valueOf(strcallDate));
samay = callDate.toString();
callDuration = managedCursor.getString(duration);
callType = null;
int callcode = Integer.parseInt(callTypeCode);
switch (callcode) {
case CallLog.Calls.OUTGOING_TYPE:
callType = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
callType = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
callType = "Missed";
break;
}
arrayList.add(phNum);
arrayList.add(callDuration);
arrayList.add(callType);
arrayList.add(samay);
}
managedCursor.close();
/*String[] array = new String[arrayList.size()];
array = arrayList.toArray(array);
for(String s : array)
{Log.d("TAG",s);}*/
final String[] data = arrayList.toArray(new String[arrayList.size()]);
final java.sql.Array sqlArray = Connection.createArrayOf("VARCHAR", data);
class getCallDetails extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HashMap<String, Array> param = new HashMap<String, Array>();
param.put(Connect.KEY_ARRAY, sqlArray );
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Connect.URL_ADD, param);
return res;
}
}
getCallDetails idata = new getCallDetails();
idata.execute();
}
}
here i have tried to convert string[] array into java.sql array but Connection.createArrayOf() shows error of non-static method can not be referenced from a static context.
First create a POJO class to store the data,
private class ContactData {
String phNum;
String callDuration;
String callType;
String samay;
public ContactData(String phNum, String callDuration, String callType, String samay) {
this.phNum = phNum;
this.callDuration = callDuration;
this.callType = callType;
this.samay = samay;
}
// getters and setters
}
Create a List before the while loop and insert data into this inside the loop,
List<ContactData> items = new ArrayList<String>();
while (managedCursor.moveToNext()) {
...
items.add(new ContactData(phNum, callDuration, callType, samay));
}
Use GSON library to convert ArrayList to JSON.
String listOfItems = new Gson().toJson(items);
Post this data to server. See here how to do this.
I have a json parse like this
public class SecondFragment extends Fragment implements OnClickListener {
// URL to get contacts JSON
private static String contestUrl = "http://api.apps.com/contest";
// JSON Node names
private static final String TAG_ITEM_ID = "id";
private static final String TAG_URL = "url";
private static final String TAG_START_DATE = "start_date";
private static final String TAG_END_DATE = "end_date";
// contacts JSONArray
JSONArray foods = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> foodslist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
foodslist = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts 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(contestUrl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
String start_date = (String)contact.get(TAG_ITEM_ID);
// adding contact to contact list
foodslist.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
}
I have two function, onCreate and GetContacts. In the end of onCreate it call GetContacts and call this json.
My question is, how can I got the Hashmap value on GetContacts so I can use it on onCreate
So far, I got this to get the value of Hashmap
String start_date = (String)contact.get(TAG_ITEM_ID);
But, its only works on GetContacts.
Anyone can help me?
Thanks Before
There are couple of ways:
Way-1:
Create instance variable (class-level) of HashMap contact and then you can use it anywhere within class inclusing onCreate and getContacts method.
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
private static Map<String, String> contact = new HashMap<String, String>();
public void onCreate() {
//populate contact object as per your logic
getContacts();
}
private void getContacts() {
//Use contact object directly which was pre-populby onCreate method.
}
}
Way-2:
Pass map to the getContacts() method:
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
public void onCreate() {
final Map<String, String> contact = new HashMap<String, String>();
//populate contact object as per your logic.
getContacts(contact);
}
private void getContacts(Map<String, String> contact) {
//Use contact object which is passed as argument.
}
}
On other side, please use cameCasing while naming Java methods or variables. GetContacts is not right, make it getContacts.
For email and address fields, using TAG_START_DATE and TAG_END_DATE is no fun. :-)
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
To answer about #3 below, variable s is not accessible in NotInner class:
package com.test;
public class Test {
static String s = "";
}
class NotInner {
public static void main(String[] args) {
System.out.println(s); //Compilation error: s cannot be resolved to a variable
}
}
You have
List<Map<String,String>> foodslist = ...;
which is filled in the loop.
To get at individual values, iterate:
for( Map<String,String> item: foodslist ){
String id = item.get(TAG_ITEM_ID);
String name = item.get(TAG_URL);
String email = item.get(TAG_START_DATE);
String address = item.get(TAG_END_DATE);
}
Or you write a method for the class where you keep foodslist:
String getAttr( int i, String tag ){
return foodslist.get(i).get(tag);
}
and you can call
String id = xxx.getAttr( i, TAG_ITEM_ID );
So return the data ...
public List<Map<String, String>> getContacts() {
if (foodslist != null && foodslist.isEmpty()) {
return foodslist;
}
foodslist = new ArrayList<Map<String, String>>();
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
// adding contact to contact list
foodslist.add(contact);
}
return foodslist;
}
Though I'm not sure why that variable is called foodslist if it's supposed to contain contacts.
I'm new in coding and I have a problem to understand something. I follow the example form Parse.com Doc and wrote this.
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
int object_value = Integer.parseInt(obiect);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
I understand this like:
I send query to server
get obiect with "lxFzCTeOcl" id
if there is no exception I create String object which takes string
form "value" column.
convert String to int
My question is: How can I use object_value for example to make a chart or put it into a table?
Here we will add the array list to your code and start to store an object inside the array every time we call the getData method in your class.
private ArrayList<Integer> dataArray;
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(obiect);
if(dataArray==null)
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
And here I'm just adding a simple example of how to create a simple pie chart using our array list (note that I used the lib AChartEngine http://www.achartengine.org/):
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private GraphicalView createPieChart(ArrayList<Integer> data){
GraphicalView chartView;
CategorySeries series = new CategorySeries("PIE");
for (int i = 0; i < VALUES.length; i++) {
series.add(i, data.get(i));
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(series.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
chartView = ChartFactory.getPieChartView(this, series, new DefaultRenderer());
chartView.repaint();
return chartView;
}
Now you can add this GraphicalView to your view.
The returned object is much like a map, with key/value pairs. In your example, the key is "value", which makes it a little confusing, but it would be like this if you wanted all fields:
for (Field field : myInstance.getClass().getDeclaredFields()) {
String name = field.getName();
value = field.get(myInstance).toString();
map.put(name, value);
}