I am trying to create JSON data store into ArrayList and load on ListView. Now I have successfully stored my JSON data into ArrayList. But the problem is I have maintaining multiple column listview. I need to List out my first array on first column.
Below I have tried something, multiple columns with array. But exactly I dont know how to do that. Please help me, I am new developer for Android.
// I need to add my array into first column
private ArrayList<String> myarray = new ArrayList<String>();
//JSON string data's I have loaded
myarray.add(jsondata);
//LISTVIEW WATCHLIST
ListView listView=(ListView)findViewById(R.id.listView1);
list=new ArrayList<HashMap<String,String>>();
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, "Minchu");
temp.put(SECOND_COLUMN, "USA");
temp.put(THIRD_COLUMN, "City");
temp.put(FOURTH_COLUMN, "Ranks");
list.add(temp);
.
.
.
.
ListViewAdapters adapter=new ListViewAdapters(this,list);
listView.setAdapter(adapter);
NOTE : Above HashMap to putted manual data. I need to load first array first columns, second array second columns.
You need to create model for your json object see below code.
import java.io.Serializable;
public class PersonDetailsItem implements Serializable {
public int id;
private String intEducationEN, intVillageID;
public PersonDetailsItem(int id, String name, String phoneNo, String email) {
// TODO Auto-generated constructor stub
this.id = id;
this.strNameEN = name;
this.strEmailid = email;
}
public String getIntVillageID() {
return intVillageID;
}
public void setIntVillageID(String intVillageID) {
this.intVillageID = intVillageID;
}
public String getIntEducationEN() {
return intEducationEN;
}
public void setIntEducationEN(String intEducationEN) {
this.intEducationEN = intEducationEN;
}
public PersonDetailsItem() {
// TODO Auto-generated constructor stub
}
Then set the value for the model form parsing json received string.
private void parseJson(String rs) {
private ArrayList<PersonDetailsItem> listData = new ArrayList<PersonDetailsItem>();;
// TODO Auto-generated method stub
listData = new ArrayList<PersonDetailsItem>();
spinerPersonData = new ArrayList<SpinerItem>();
try {
JSONObject obj = new JSONObject(rs);
JSONArray jArray = obj.getJSONArray("Table");
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.optJSONObject(i);
String intEducationEN = c.getString("intEducationEN");
String intVillageID = c.getString("intVillageID");
PersonDetailsItem personItem = new PersonDetailsItem();
personItem.setIntEducationEN(intEducationEN);
personItem.setIntVillageID(intVillageID);
listData.add(personItem);
}
} catch (JSONException e) { // TODO Auto-generated catch block
e.printStackTrace();
Log.v("perosnJson Error", e.toString());
}
}
set to listadapter
CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.id.listView1, listData);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
enter code here
You can check link for more detail https://github.com/yagneshshinde101/mysamaj/blob/master/MySamaj/src/com/example/mysamajmain/MainActivity.java
Related
I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance
You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;
I am parsing several Json links, and trying to add all output to one List. However the list always gets overwritten instead to only include the results from one of the links:
public class GetShopifyJsonData extends GetRawData {
private String LOG_TAG = GetShopifyJsonData.class.getSimpleName();
private List<Product> mProduct;
private Uri mDestination;
public GetShopifyJsonData(int page) {
super(null);
createUri(page);
mProduct = new ArrayList<Product>();
}
public void execute(){
super.setRawUrl(mDestination.toString());
DownloadShopifyData downloadShopifyData = new DownloadShopifyData();
Log.v(LOG_TAG, "Built URI = " + mDestination.toString());
downloadShopifyData.execute(mDestination.toString());
}
public boolean createUri(int page) {
final String SHOPIFY_BASE_URL = "";
final String SHOPIFY_PAGE_PARAM = "page";
mDestination = Uri.parse(SHOPIFY_BASE_URL).buildUpon()
.appendQueryParameter(SHOPIFY_PAGE_PARAM, String.valueOf(page)).build();
return mDestination != null;
}
public void processResults() {
if(getDownloadStatus() != DownloadStatus.OK){
Log.e(LOG_TAG, "Error Downloading Raw Data");
return;
}
final String SH_PRODUCTS = "products";
final String SH_TYPE = "product_type";
final String SH_VARIANTS = "variants";
final String SH_TITLE = "title";
final String SH_PRICE = "price";
final String SH_GRAMS = "grams";
try {
JSONObject jsonData = new JSONObject(getData());
JSONArray productsArray = jsonData.getJSONArray(SH_PRODUCTS);
for (int i=0; i<productsArray.length(); i++ ) {
JSONObject jsonProduct = productsArray.getJSONObject(i);
String productType =jsonProduct.getString(SH_TYPE);
String title = jsonProduct.getString(SH_TITLE);
JSONArray variantsArray = jsonProduct.getJSONArray(SH_VARIANTS);
JSONObject variantProduct = variantsArray.getJSONObject(0);
String variantTitle = variantProduct.getString(SH_TITLE);
double price = variantProduct.getDouble(SH_PRICE);
int grams = variantProduct.getInt(SH_GRAMS);
if (productType.equals("Keyboard") || productType.equals("Computer")) {
Product productObject = new Product(title, price, grams, productType, variantTitle);
this.mProduct.add(productObject);
}
}
for(Product singleProduct : mProduct){
Log.v(LOG_TAG, singleProduct.toString());
Log.v(LOG_TAG, String.valueOf(mProduct.size()));
}
} catch (JSONException jsone) {
jsone.printStackTrace();
Log.e(LOG_TAG, "Error Processing JSON data");
}
}
}
And the call from MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i=1; i<6; i++) {
GetShopifyJsonData jsonData = new GetShopifyJsonData(i);
jsonData.execute();
}
}
What do I need to change to get the products to add to each other in a single list?
You are overwriting jsonData each time you iterate through this loop, without storing the results of each previous loop elsewhere.
for (int i=1; i<6; i++) {
GetShopifyJsonData jsonData = new GetShopifyJsonData(i); // throws out results of previous iteration and creates a new List each time
jsonData.execute();
}
You should keep a List outside of this loop that you can add all of your results to after each iteration:
ArrayList<Product> allProducts = new ArrayList<Product>();
for (int i=1; i<6; i++) {
GetShopifyJsonData jsonData = new GetShopifyJsonData(i);
jsonData.execute();
allProducts.addAll(jsonData.getProducts()) // add a method that gets all of the products from each iteration
}
EDIT:
Since you are using threads to collect the JSON data, you can use a List of GetShopifyJsonData objects to maintain references to those threads;
ArrayList<GetShopifyJsonData> allJSONData = new ArrayList<GetShopifyJsonData>();
for (int i=1; i<6; i++) {
allJSONData.add(new GetShopifyJsonData(i));
allJSONData.get(i).execute(); // executes each task as discrete instances
}
From there you can check the status of the threads, and retrieve the JSON data from the list as they complete. Below is a not-very-good example, for illustration's sake:
ArrayList<Product> allProducts = new ArrayList<Product>();
for (int i=1; i<6; i++) {
while(!allJSONData.get(i).isComplete()){ // add a method that checks if a task has been completed
//this is a busy wait, don't do this!
}
allProducts.addAll(jsonData.get(i).getProducts()) // add a method that gets all of the products from each iteration
}
Now, I'm not an android expert, but a quick skim over the docs for AsyncTask shows me that onPostExecute(Result) and getStatus() would probably be useful. If I'm correct, I expect you could actually add the JSON data to a List inside of onPostExecute() and skip using an ArrayList<GetShopifyJsonData> altogether by passing the master list into execute(); something along the lines of:
ArrayList<Product> allProducts = new ArrayList<Product>();
for (int i=1; i<6; i++) {
GetShopifyJsonData jsonData = new GetShopifyJsonData(i);
jsonData.execute(allProducts); // pass the reference to your list in execute()
}
// in your AsyncTask class:
private ArrayList<Product> products; // private List instance
execute(ArrayList<Product> allProducts){
products = allProducts;
// do other logic
...
}
onPostExecute(List<Product> dataFromJSON){
products.addAll(dataFromJSON); // add the results to the instance variable, which also updates the master list
}
This is an oversimplification, though. You would have to make sure that threads don't try to add to the List at the same time, because bad things can potentially happen if they are allowed to do so. The documentation says that onPostExecute() runs on the UI thread, but I don't know what that means.
Each GetShopifyJsonData has its own List<Product> and you need to aggregate those by either having a single GetShopifyJsonData instance request all the products or by having your MainActivity aggregate them as the requests complete. This approach implements the latter.
Add a callback interface to GetShopifyJsonData and require an instance of it as a parameter in the constructor. I only included the changes in the code below. Everything else is the same.
public class GetShopifyJsonData extends GetRawData {
public interface OnResultsReadyListener {
void onResultsReady(List<Product> products);
}
private OnResultsReadyListener mResultsListener;
public GetShopifyJsonData(int page, OnResultsReadyListener resultsListener) {
super(null);
createUri(page);
mProduct = new ArrayList<Product>();
mResultsListener = resultsListener;
}
public void processResults() {
// Add this to the end of the method
if(mResultsListener != null) {
mResultsListener.onResultsReady(mProduct);
}
}
}
And then update MainActivity to implement this new interface and add results to its list as requests complete.
public class MainActivity extends Activity
implements GetShopifyJsonData.OnResultsReadyListener {
private List<Product> allproducts;
#Override
void onResultsReady(List<Product> products) {
// allProducts contains products for all requests that have completed so far
allProducts.addAll(products);
Log.v(LOG_TAG, allProducts.size() + " total products downloaded.");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allProducts = new ArrayList<>();
for (int i=1; i<6; i++) {
GetShopifyJsonData jsonData = new GetShopifyJsonData(i, this);
jsonData.execute();
}
}
}
I am new to Hive UDTF. I have a requirement where I have to pass string values as Paratmeter in UDTF and the returning Column should be a ArrayList.
I have written the following Code:
public StructObjectInspector initialize(ObjectInspector[] arg0)
throws UDFArgumentException {
ArrayList<String> fieldNames = new ArrayList<String>();
ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
fieldNames.add("col1");
stringOI = (PrimitiveObjectInspector) arg0[0];
listOi=(ListObjectInspector) arg0[0];
fieldOIs.add(listOi.getListElementObjectInspector());
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
}
#Override
public void process(Object[] record) throws HiveException {
// TODO Auto-generated method stub
String document = (String) stringOI.getPrimitiveJavaObject(record[0]);
if (document == null) {
return;
}
firstColumn=(String) stringOI.getPrimitiveJavaObject(record[0]);
secondColumn=(String) stringOI.getPrimitiveJavaObject(record[1]);
if(outputMapper.containsKey(firstColumn))
{
ArrayList<String> tempList=new ArrayList<String>();
tempList=outputMapper.get(firstColumn);
tempList.add(secondColumn);
outputMapper.put(firstColumn,tempList);
}
else
{
childVendorList=new ArrayList<String>();
childVendorList.add(secondColumn);
outputMapper.put(firstColumn,childVendorList);
}
forward(outputMapper.get(firstColumn));
}
}
And I am getting the following Exception:
java.lang.ClassCastException: org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyStringObjectInspector cannot be cast to org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector
Can Anyone Help???
listOi=(ListObjectInspector) arg0[0];
fieldOIs.add(listOi.getListElementObjectInspector());
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
This arg0[0] is a primitive object inspector. With listOi.getListElementObjectInspector(), just get a similar PrimitiveObjectInspector(like String,Integer is not a List). It should
fieldOIs.add(ObjectInspectorFactory.getStandardListObjectInspector(stringOI ))
This will specific the output column with List of type of stringOI.
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 got following code and there is this error (I tried to keep the code as short as possible, ignore the getColumnCount etc. functions just the constructor):
The following code is used to make a JTable in Swing by an SQLite statement, I need the booleans for checkboxes (Yes I know I have to edit/add an function, but I wanted to keep the code as small as possible).
Code:
package view;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
import controller.Database;
class Test extends AbstractTableModel {
Database db = new Database();
ResultSet rs;
private String[] columnNames = {"Vorname", "Nachname", "E-Mail", "Anrede", "Jahrgang", "Ablösung", "Scheibe", "Waffe", "Gruppe", "Verpflegung", "Aktiv"};
Object[][] data;
public Test(){
int result = 0;
try {
rs = db.stat.executeQuery("select count(*) as schuetzencount from schuetze;");
result = Integer.parseInt(rs.getString("schuetzencount"));
data = new String[result][11];
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs = db.stat.executeQuery("select * from schuetze as s join waffe as w on w.Waffe_ID = s.Waffe_ID join gruppe as g on g.Gruppe_ID = s.Gruppe_ID join anrede as a on a.Anrede_ID = s.Anrede_ID join verpflegung as v on v.Verpflegung_ID = s.Verpflegung_ID;");
int counter = 0;
while(rs.next()){
data[counter][1] = rs.getString("Schuetze_Nachname");
data[counter][0] = rs.getString("Schuetze_Vorname");
data[counter][4] = rs.getString("Schuetze_Jahrgang");
data[counter][2] = rs.getString("Schuetze_Email");
data[counter][5] = rs.getString("Schuetze_Abloesung");
data[counter][6] = rs.getString("Schuetze_Scheibe");
data[counter][7] = rs.getString("Waffe_Name");
data[counter][8] = rs.getString("Gruppe_Name");
data[counter][3] = rs.getString("Anrede_Name");
data[counter][9] = rs.getString("Verpflegung_Name");
data[counter][10] = true;
counter++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
public static void main(String[] args) {
Test t = new Test();
}
}
Error:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at view.Test.<init>(Test.java:43)
at view.Test.main(Test.java:72)
If I'll do
Object[][] data = {{"Test", "Test","Test","Test","Test","Test","Test","Test","Test","Test",true}}
it works, but that's not what I need. Then I tried to do a Object[] and fill the Booleans in and then add the Object[] into the data[][] but this also didn't work.
I hope someone can help me, thanks.
Greetz.
You have Array of Strings and try to put Boolean there in line
data[counter][10] = true;
That is not allowed.
When You do
Object[][] data = {{"Test", "Test","Test","Test","Test","Test","Test","Test","Test","Test",true}}
Java creates for you array of Objects
Like:
Object[][] o = new Object[1][6];
o[0][2] = true; // it works
Your array expects a String as dataType, on the other hand are you trying to put a boolean into it.
data[counter][10] = true;
a simple solution to this is using a string "true"instead of the primitive booleantype (or parse it to string)
data[counter][10] = "true";
You cannot insert a boolean value to an array of String. That is the problem :
data = new String[result][11];
data[counter][10] = true;
At least insert it as a String and parse it when neccessary.
You have defined data as matrix of Objects, but instantiated it as matrix of String.
That's why, at runtime, you have this type mismatch exception.
Either instantiate it like:
Object[][] o = new Object[1][6];
or
replace boolean value with string:
data[counter][10] = "true";
The problem is here:
data = new String[result][11];
You declare the array of String and you do this
data[counter][10] = true;
You have two options:
declare data as
new Object[result][11];
put string instead of boolean
data[counter][10] = Boolean.TRUE.toString();