Populate JSON data to ListView - java

I am trying to display a retrieved data from MySQL database with the help of Volley, and populate it into a ListView.
So far as I tried every method I am unable to do it.
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
ArrayList<HashMap<String, String>> authorList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject obj = (JSONObject) response.get(i);
String username = obj.getString("username");
String email = obj.getString("email");
String password = obj.getString("password");
usernameAll += "UserName: " + username + "\n\n";
emailAll += "Email: " + email + "\n\n";
passwordAll += "Password: " + password + "\n\n";
}
As I have retrieved 'username', 'email', and 'password' I can successfully show it in TextView by myTextView.setText(usernameAll + " " + ..);. But for now I just want to print/populate 'username' in Simple ListView
HashMap<String, String> myData = new HashMap<>();
myData.put("justKey", usernameAll);
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, myData);
listView.setAdapter(adapter1);
When I take some Array and call that array it works but why myData isn't working. Can you please help me understanding the actual problem.
My next step will be to use the Custom ListView but now I am eager "how actually stuff works"
I will really appreciate if you correct my approach of solving this problem.
Thank You.
PS: I am getting this error from Android Studio 2.1.2:
Cannot resolve constructor 'ArrayAdapter(android.content.Context, int,
int, java.lang.String)'

u can't pass hashmap to the array adapter
https://developer.android.com/reference/android/widget/ArrayAdapter.html
convert it to the list as mentioned in the documentation also
//Code Getting Collection of values from HashMap
Collection<String> values = myData.values();
//Creating an ArrayList of values
ArrayList<String> listOfValues = new ArrayList<String>(values);
For details check out the link below
http://javaconceptoftheday.com/how-to-convert-hashmap-to-arraylist-in-java/

Related

How to make a Arraylist with JSON Objects in JAVA?

I want to make a Arraylist with JSON Objects .
There is a loop which gives me JSON Objects. I want to put them into a ArrayList.
Here is the Code which gives me JSON Objects. Please let me know how to put all the values ito a ArrayList
for (int i=0; i<10; i++) {
String datapointsBodyString = "{items:[{id:" + unionUptimeMetadata.getLatencyTimeseriesIds().get(i) + ", start: " + oldestTimeString + ",end: " + now + ", granularity: 1m}]}";
JSONObject datapointsBodyObject = new JSONObject((datapointsBodyString));
HttpResponse uptimeResponse = httpService.POST("url", datapointsBodyObject.toString(), unionUptimeTimeseriesHeaders);
HttpEntity uptimeResponseEntity = uptimeResponse.getEntity();
String uptimeResponseString = EntityUtils.toString(uptimeResponseEntity);
JSONObject uptimeResponsObject = new JSONObject(uptimeResponseString);
}
Thanks in advance.
It's generally worth doing a search for common programming tasks. You could just google search "java add to list" which should result in something like:
List<JSONObject> myList = new ArrayList<>();
myList.add(uptimeResponsObject);
that should be enough for you to get it working.

Android Studio Error "Cannot resolve method for method .add"

I know this question is asked a lot, but I am genuinely stumped, I have looked at other methods, and tried everything...
My coding problem is as follows, I have a public class in java, and I made a string array in the global scope. I tried to add to it using array.add("somestringhere"), but it spits out an error saying (the title)... One more thing to note is this class is inside the main class for the file. so let's see if I can show it here:
public class see_schedule_activity extends AppCompatActivity {
.
..
.
.
.
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxphp";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
try {
// I have a intent passed from teh main class
Bundle extras = getIntent().getExtras();
String[] tasks = extras.getStringArray("tasks");
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("schedule");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
activityid = c.getString("activityid");
String yesno = c.getString("yesno");
String start = c.getString("start");
String stop = c.getString("stop");
String plusminus = c.getString("plusminus");
Log.e("Hash Map", "Routine ID #" + activityid);
if (!TextUtils.isEmpty(activityid) && TextUtils.isDigitsOnly(activityid)) {
routine = hm.get(Integer.valueOf(activityid));
} else {
routine = "";
}
// TODO: Make the PHP work with a variable residentID
//TODO: only make a string if the yes is checked
//TODO: make the routine name
// Log.e(TAG, "Value for yesno:" + yesno);
if (c.getString("yesno").equals("Yes")) {
schedule = routine + " starts at " + start + " and ends at " + stop + " with plusorminus " +
plusminus + " minutes ";
tasks.add(schedule);// This lines yeilds the problem
Log.e(TAG, "" + schedule);
}
// // show the values in our logcat
// Log.e(TAG, "activityid: " + activityid
// + ", yesno: " + yesno
// + ", start: " + start
// + ", stop: " + stop
// + ", plusminus: " + plusminus);
}
Intent intent = new Intent(getApplicationContext(),see_schedule_activity.class);
intent.putExtra("tasks_filled",tasks);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
}
}
I would appreciate any help, I'm a newb to programming and android studio, and php..so yeah thanks in advance, Justin
tasks is an String array as you defined
String[] tasks = extras.getStringArray("tasks");
And Array doesn't have any add method.
You need to convert tasks to a list like following
List<String> list = Arrays.asList(tasks);
Then you can use list.add(schedule)

How to set unique ID for each Item in Android ListView?

My Code:
JSONArray jArray = new JSONArray(result);
if(jArray.length() > 0) {
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
expense_id = json_data.getInt("expense_id");
client_name = json_data.getString("client_name");
expense_type = json_data.getString("expense_type");
expense_amount = json_data.getInt("expense_amount");
listItems.add(i, expense_id + "- " + client_name + " | " + expense_type + " : Rs. " + String.valueOf(expense_amount));
}
adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listItems);
ListView list_expenses = (ListView) findViewById(R.id.list_expenses);
list_expenses.setAdapter(adapter);
registerForContextMenu(list_expenses);
list_expenses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
final int extra_expense_id = Integer.parseInt(item.split("-")[0]);
Intent intent = new Intent(HomeScreenActivity.this, ViewExpenseActivity.class);
intent.putExtra(EXTRA_EXPENSE_ID, extra_expense_id);
startActivity(intent);
}
});
}
When I use onItemClick listener, I want to send 'expense_id' to the next Activity. But how do I set individual 'expense_id' for each Item?
In my code I've added expense_id in each item and then splitting it to get the id. But this is a bad approach. Any way I can set a hidden ID attribute to each listItem?
I also tried - listItem.add(expense_id, "String object here"); so that I can get the index which would be equal to expense_id.
But this work since ArrayList has to start from index 0.
Possible Answers:
1 - User Custom Adapter: No I've already implemented ArrayAdapter properly.
2 - Use setTag, getTag? That works on entire ListView object. It doesn't work on individual items.
You could store the ids in a separate list and maintain both.
listItems.add(i, expense_id + "- " + client_name + " | " + expense_type + " : Rs. " + String.valueOf(expense_amount));
listIds.add(i,expense_id);
and within your item click listener you can get the expense id from the position variable
listIds.get(position);
You can create separate list for expense id.
ArrayList<Integer> expenseIds = new ArrayList<Integer>();
Added expenseId in list in for...loop
expenseIds.add(expense_id);
You can get expense_id int onItemClick method like below code
expenseIds.get(position);
Add a TextView to the row and set it value to be the id of the row.
Next, set visibilty=gone.
Whenever you require the id, just convert it to int.

Get all data from SQLite trough search

I am trying to get all data from my SQLite using Query LIKE statement. But I don't know how to get it.
I try to modified the Query that I use to get All the data without filtering, and its work fine.
I already try to search this problem but I still don't get it.
Here's my Search.java
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
Log.d("Reading: ", "Reading all contacts..");
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult();
ArrayList <String> allItems2 = new ArrayList<String>();
for (AllItem cn : allItems) {
allItems2.add(cn.getItem_name());
allItems2.add(cn.getAreaNAme());
allItems2.add(cn.getPriceCategory());
allItems2.add(cn.getImageCount());
allItems2.add(cn.getID());
allItems2.add(cn.getCategory_name());
allItems2.add(cn.getKids());
allItems2.add(cn.getFreeTextForKids());
allItems2.add(cn.getDescription());
allItems2.add(cn.getPromotion());
allItems2.add(cn.getPromotionFreeText());
allItems2.add(cn.getPromotionStartDate() + " - ");
allItems2.add(cn.getPromotionEndDate());
allItems2.add(cn.getYoutube());
allItems2.add(cn.getYoutubeLink());
allItems2.add(cn.getPhone());
allItems2.add(cn.getMobilePhone());
allItems2.add(cn.getReview());
allItems2.add(cn.getAddress());
allItems2.add(cn.getLatitude());
allItems2.add(cn.getLongitude());
allItems2.add(cn.getOpenDetail());
allItems2.add(cn.getFacebook());
allItems2.add(cn.getTwitter());
allItems2.add(cn.getInstagram());
allItems2.add(cn.getWebsite());
}
CustomAdapterAccommodation adapter = new CustomAdapterAccommodation(Search.this, allItems2);
listview.setAdapter(adapter);
}
I want to use the String from Intent to search the data on DATABASE.
This is my DatabaseHandler.java
// Getting All search result
public List<AllItem> getAllSearchResult() {
List<AllItem> allsearchResultList = new ArrayList<AllItem>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ALLITEM;
// If i try change like this its show nothing
// String selectQuery = "SELECT * FROM " + TABLE_ALLITEM + " WHERE " + KEY_ITEM_NAME_ALLITEM + " = '%a%'";
Log.d("Query search", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AllItem allitem = new AllItem();
allitem.setTableID(cursor.getInt(0));
allitem.setID(cursor.getString(1));
allitem.setCategory_name(cursor.getString(2));
allitem.setItem_Name(cursor.getString(3));
allitem.setDescription(cursor.getString(4));
allitem.setAddress(cursor.getString(5));
allitem.setArea (cursor.getString(6));
allitem.setAreaName (cursor.getString(7));
allitem.setLongitude (cursor.getString(8));
allitem.setLatitude (cursor.getString(9));
allitem.setOpenDetail (cursor.getString(10));
allitem.setKids (cursor.getString(11));
allitem.setFreeTextForKids (cursor.getString(12));
allitem.setCuisineID (cursor.getString(13));
allitem.setCuisineName (cursor.getString(14));
allitem.setCuisineUniqueCode (cursor.getString(15));
allitem.setBarTypeID (cursor.getString(16));
allitem.setBarTypeName (cursor.getString(17));
allitem.setBarTypeCode (cursor.getString(18));
allitem.setRoomTypeID (cursor.getString(19));
allitem.setRoomTypeName (cursor.getString(20));
allitem.setRoomTypeCode (cursor.getString(21));
allitem.setWellnessTypeID (cursor.getString(22));
allitem.setWellnessTypeName (cursor.getString(23));
allitem.setWellnessTypeCode (cursor.getString(24));
allitem.setAttractionsTypeID (cursor.getString(25));
allitem.setAttractionsTypeName (cursor.getString(26));
allitem.setAttractionsTypeCode (cursor.getString(27));
allitem.setShopsTypeID (cursor.getString(28));
allitem.setShopsTypeName (cursor.getString(29));
allitem.setShopsTypeCode (cursor.getString(30));
allitem.setAdventuresTypeID (cursor.getString(31));
allitem.setAdventuresTypeName (cursor.getString(32));
allitem.setAdventuresTypeCode (cursor.getString(33));
allitem.setRomanceTypeID (cursor.getString(34));
allitem.setRomanceTypeName (cursor.getString(35));
allitem.setRomanceTypeCode (cursor.getString(36));
allitem.setGalleriesTypeID (cursor.getString(37));
allitem.setGalleriesTypeName (cursor.getString(38));
allitem.setGalleriesTypeCode (cursor.getString(39));
allitem.setFurnitureTypeID (cursor.getString(40));
allitem.setFurnitureTypeName (cursor.getString(41));
allitem.setFurnitureTypeCode (cursor.getString(42));
allitem.setEventTypeID (cursor.getString(43));
allitem.setEventTypeName (cursor.getString(44));
allitem.setEventTypeCode (cursor.getString(45));
allitem.setPriceCategory (cursor.getString(46));
allitem.setHotelOfficialStarRating (cursor.getString(47));
allitem.setPhone (cursor.getString(48));
allitem.setMobilePhone (cursor.getString(49));
allitem.setReview (cursor.getString(50));
allitem.setPromotion (cursor.getString(51));
allitem.setPromotionFreeText (cursor.getString(52));
allitem.setPromotionStartDate (cursor.getString(53));
allitem.setPromotionEndDate (cursor.getString(54));
allitem.setActive (cursor.getString(55));
allitem.setImageCount (cursor.getString(56));
allitem.setCreatedBy (cursor.getString(57));
allitem.setCreatedDate (cursor.getString(58));
allitem.setUpdatedBy (cursor.getString(59));
allitem.setUpdatedDate (cursor.getString(60));
allitem.setFacebook (cursor.getString(61));
allitem.setTwitter (cursor.getString(62));
allitem.setInstagram (cursor.getString(63));
allitem.setWebsite (cursor.getString(64));
allitem.setYoutube (cursor.getString(65));
allitem.setYoutubeLink (cursor.getString(66));
allitem.setMember (cursor.getString(67));
allitem.setMemberStartDate (cursor.getString(68));
allitem.setMemberEndDate (cursor.getString(69));
allitem.setNew (cursor.getString(70));
allitem.setEventStartDate (cursor.getString(71));
allitem.setEventEndDate (cursor.getString(72));
// Adding food to list
allsearchResultList.add(allitem);
} while (cursor.moveToNext());
}
// return food list
return allsearchResultList;
}
Is there anyone can help me how to solved this problem?
When the user press the button search, the Text send to Search class and the Text is the key to get all the data from SQLite. Then show it in ListView.
Thanks before :D
Use LIKE not =
LIKE allows you to use wildcars:
% represents multiple characters
_ represents one character
String filter = "a";
String selectQuery = "SELECT * FROM " + TABLE_ALLITEM + " WHERE " + KEY_ITEM_NAME_ALLITEM + " LIKE '%"+filter+"%' ";

Accessing arraylist in another class

Hi i have an arraylist that i want to access from another class, i'm new to android please try to explain in a simple way
//Adding item to ArrayList
Cursor cursor2=shoppingListDB.rawQuery("SELECT * FROM " + selected_spinner + ";", null);
if (cursor2.moveToFirst()){
list.clear();
do{
String itemName = cursor2.getString(cursor2.getColumnIndex("ITEM_NAME"));
String shopList = cursor2.getString(cursor2.getColumnIndex("SHOP_LIST"));
String numbItems = cursor2.getString(cursor2.getColumnIndex("NUMB_ITEMS"));
//Adding Items to the arraylist
list.add(numbItems + " x"+ " " +itemName + " " + "#"+shopList);
}
while (cursor2.moveToNext());
//====CODE FOR SHOWING DATA AS A SIMPLE LIST ITEM=========================================
view_list = (ListView)findViewById(R.id.listItems);
ArrayAdapter <String> adapter=new ArrayAdapter<String>(CreateList.this,android.R.layout.simple_list_item_1,list);
view_list.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor2.close();
I think you should use basic OOP concept for this.
in your class you can declare the list as class instance variable and use getter method to get the list in other class.
public class abcd {
private List<String> list;
public List<String> getList() {
return list;
}
//your code which uses list
}
Hope this will help you.

Categories