How to get and set json data on recyclerView? - android

Android Question?
I get json value and set on recyclerView ,How can make condition if i select item name then only print regarding this data value like Rate, amount like this.
Example: online ordering food android app

When you want to parse JSON , first you have to study about JSON Parsing.
You can Parse JSON by Volley Library , Retrofit etc.
Site to convert JSON to POJO/Model class jsonschema2pojo
Steps to Parse JSON :
Create Pojo class according to your json.
Using Volley or Retrofit to parse the json.
After setting data on pojo send the ArrayList to Recyclerview Adapter class.
You can also use GSON , its easy to parse json and set data to pojo classes.
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<ItemObject> posts = new ArrayList<ItemObject>();
posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
recyclerView.setAdapter(adapter);
Below is the tutorial to Json Parsing using Volley Library and set to RecyclerView .
Reference : https://inducesmile.com/android/android-json-parsing-using-gson-and-recyclerview/
How can make condition if i select item name then only print regarding
this data value like Rate, amount like this.
Ans : By position you can get the values of rate, amount on that position data on Recyclerview Adapter class.
How to pass all recyclerView data to next activity and save sqlite database in android, inside onclick Listener ?
When you want to send recyclerView Data to next Activity, you have to send the pojo class object to next activity by intent.
RecyclerView Data send to next Activity :
takeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Data send to next Activity
Intent intent = new Intent(HomeActivity.this,TakeSingleScanActivity.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)cList);
intent.putExtra("BUNDLE",args);
startActivity(intent);
}
});
RecyclerView Data Receive from Last Activity :
ArrayList<LoadDataResult> inList; //Global Variable
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
inList = (ArrayList<LoadDataResult>) args.getSerializable("ARRAYLIST");
Don't forget to implements your pojo class as Serializable :
public class LoadDataResult implements Serializable{
Create a loop to store all recyclerview data on Sqlite on your Activity Class :
for(int m = 0;m<mList.get(0).getResult().size();m++) {
callDataBaseHelper(mList.get(0).getResult().get(m).getName().trim(),
mList.get(0).getResult().get(m).getSku().trim(),
mList.get(0).getResult().get(m).getUpc().trim(),
mList.get(0).getResult().get(m).getPrice().trim(),
mList.get(0).getResult().get(m).getDisplaySize().trim(),
mList.get(0).getResult().get(m).getDisplaySizeYes(),
mList.get(0).getResult().get(m).getStatus().trim());
if(m == mList.get(0).getResult().size()-1) {
setData();
getRefreshTime();
utils.showtoast("Data Load Successful");
utils.hideDialog();
}
}
call DataBaseHelper class addData method :
private void callDataBaseHelper(String name, String sku, String upc, String price, String displaySize, int displaySizeYes, String status) {
boolean insertData = databaseHelper.addData(name,sku,upc,price,displaySize,displaySizeYes,status);
// if(insertData){
// Log.e("Inserted","Inserted ");
// }else{
// Log.e("NotInserted","NotInserted ");
// }
}
Create DataBaseHelper Class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "GiftsDatabase.db";
SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null,Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
String createTable = " CREATE TABLE "+ Constants.TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, "+Constants.NAME+" TEXT, "+Constants.SKU+" TEXT ,"+Constants.UPC+" TEXT,"+Constants.PRICE+" TEXT, "+Constants.DISPLAY_SIZE+" TEXT, "+Constants.DISPLAY_SIZE_YES+" INTEGER , "+Constants.STATUS+" TEXT)";
db.execSQL(createTable);
String createTableCount = " CREATE TABLE "+ Constants.TABLE_NAME_COUNT +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, "+Constants.SKU_COUNT+" TEXT ,"+Constants.QUANTITY_COUNT+" TEXT)";
db.execSQL(createTableCount);
Log.e(TAG,"Created Database");
}catch (Exception e){
Log.e("EXCEPTION",""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS "+Constants.TABLE_NAME);
db.execSQL(" DROP TABLE IF EXISTS "+Constants.TABLE_NAME_COUNT);
onCreate(db);
}
public boolean addData(String name , String sku, String upc , String price, String displaySize, int displaySizeYes, String status){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.NAME, name );
contentValues.put(Constants.SKU, sku );
contentValues.put(Constants.UPC, upc );
contentValues.put(Constants.PRICE, price );
contentValues.put(Constants.DISPLAY_SIZE, displaySize );
contentValues.put(Constants.DISPLAY_SIZE_YES, displaySizeYes );
contentValues.put(Constants.STATUS, status );
long result = db.insert(Constants.TABLE_NAME,null,contentValues);
Log.e(TAG,""+upc+" Inserted");
if(result == -1) {
return false;
}else{
// Log.e(TAG,"value inserted");
return true;
}
}
Store Checked RecyclerView data on ArrayList in RecyclerView Adapter Class
ArrayList<YourPojoClass> data = new ArrayList<YourPojoClass>();
inside onBindViewHolder(); This is used for store data in checked rows.
holder.checkBox..setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
data.add(name.get(position).getText,address.get(position).getText)
}
});
Send data to next Activity : Create a button at bottom of the recyclerView by Your Activity , and you click on that button send data to next activity.

Related

Multiple coloums in an array list

I am trying to fetch all the columns from my sqllite database to an ArrayList.My table name is Products.I have created an ArrayList adapter name Product.I am fetching my tables value in DBHELPER class.But when I am using ArrayList add to add all the columns value in my arrayadapter I got the following error
Cannot resolve method add(java.lang.string, java.lang.string)
DBHELPER.JAVA
public ArrayList<Product> getProductdetails()
{
ArrayList<Product> array_list = new ArrayList<Product>();
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
try {
String selectQuery = "SELECT * FROM " + TABLE_PRODUCTS;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String product_name = cursor.getString(cursor.getColumnIndex("PRODUCT_NAME"));
String Quantity = cursor.getString(cursor.getColumnIndex("Quantity"));
String PROD_VAT = cursor.getString(cursor.getColumnIndex("PROD_VAT"));
array_list.add(product_name,Quantity,PROD_VAT,PROD_VAT);
// array_list.addAll(Arrays.asList(product_name,Quantity,PROD_VAT,PROD_VAT));
}
}
}catch (Exception e){
e.printStackTrace();
}
finally {
db.endTransaction();
db.close();
}
return array_list;
}
PRODUCT.JAVA
public class Product {
//private variables
String _PRODUCT_CODE;
String _PRODUCT_NAME;
String _PRODUCT_RATE;
String _PRODUCT_VAT;
// Empty constructor
public Product(){
}
// constructor
public Product(String PRODUCT_CODE, String PRODUCT_NAME, String PRODUCT_RATE,String PRODUCT_VAT){
this._PRODUCT_CODE = PRODUCT_CODE;
this._PRODUCT_NAME = PRODUCT_NAME;
this._PRODUCT_RATE = PRODUCT_RATE;
this._PRODUCT_VAT = PRODUCT_VAT;
}
public String getproductcode(){ return this._PRODUCT_CODE;}
public String getproductname(){
return this._PRODUCT_NAME;
}
public String getproductrate(){return this._PRODUCT_RATE;}
public String getproductvat(){return this._PRODUCT_VAT;}
}
You are adding data to ArrayList in wrong way. Your ArrayList is type of object (eg. your Product class), So you need to pass instance of model class.
array_list.add(new Product(code,name,rate,vat));
Your Arraylist is type of Product which is one model class , so you have to add model class in that arraylist like this :
array_list.add(new Product(product_name,Quantity,PROD_VAT,PROD_VAT));
addAll() method of java.util.ArrayList class. This method is used for adding all the elements of a list to the another list.
What you want to is fetching single record & adding it to array list, and what you where trying to code is adding a single item as collection in to array list, which is wrong.
You need to add every single model as following way,
array_list.add(new Product(product_name,Quantity,PROD_VAT,PROD_VAT));
Modify
array_list.add(product_name,Quantity,PROD_VAT,PROD_VAT);
To
array_list.add(new Product(product_name,Quantity,PROD_VAT,PROD_VAT));

Android Studio activity passing data

I have 3 activities - login activity, main page activity, profile activity. The login activity will call main page activity and main page activity will call profile activity. How can I pass the data from login activity to profile activity? Is it must pass the data from login activity to main page activity first then pass to profile activity from main page activity? Or is there any other way to pass the data? Thanks!
You can do that... or you could store the data in a persistent storage and read back whenever required.
Learn about SharedPreferences here - Saving Key-Value Sets | SharedPreferences
Saving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Retrieving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Learn about SQLite Database here - Saving Data in SQL Databases | SQLite Database
Saving data looks like:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
Retrieving data looks like:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
List itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedEntry._ID));
itemIds.add(itemId);
}
cursor.close();
There are two methods to pass values between Activities in Android:
1. Using intent:
Example:
In the Login Activity, put the following code inside the OnClickListiner:
Intent intent = new Intent(getApplicationContext(), mainActivity.class);
intent.putExtra("username", usernameVariable);
intent.putExtra("password", passwordVariable);
startActivity(intent);
Then, on the mainActivity, to receive the values use the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String u = intent.getStringExtra("username");
String p = intent.getStringExtra("password");
// note: the arguments should match the same as its in the loginActivity
}
2. Using Static Variables:
Example:
On the LoginActivity, create two static attributes. Like the following:
Public Class LoginActivity{
public static String username;
public static String password;
protected void onCreate(Bundle savedInstanceState) {
...
}
}
Then, in the mainActivity class use the following code to get these values:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
String u=LoginActivity.username;
String p=LoginActivity.password;
}
Hope it solved your problem...
There is one more way that you can use create a singleton class and store the value and use it.
public final class ProfileDataModel {
private static ProfileDataModel instance;
private String userName;
private String address;
private ProfileDataModel() {
}
/**
* Get Instance for Profile
* #return
*/
public static ProfileDataModel getInstance() {
if (instance == null){
instance = new ProfileDataModel();
}
return instance;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
// Use cases
//Set the data
ProfileDataModel.getInstance().setAddress("Data from login response");
ProfileDataModel.getInstance().setUserName("As per request/response");
//Get the data
String address = ProfileDataModel.getInstance().getAddress();
String userName = ProfileDataModel.getInstance().getUserName();

get id of selected spinner data based from database android

hi i have this spinner dropdown that displays data from my database. In my database, i have this table named area and it has this fields, aid its primary key and location which is a varchar. so far i am successful in displaying the data im my spinner. in my DBHelper this is the code that gets the data from DB
public Set<String> getAllData()
{
Set<String> set = new HashSet<String>();
String selectQuery = "SELECT * FROM " + TABLE_AREA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
db.close();
return set;
}
then in my addLocation.java here is how i use it to display the data on my spinner
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addplace);
Spinner spn = (Spinner)findViewById(R.id.areas);
Set<String> aset = db.getAllData();
List<String> aData = new ArrayList<>(aset);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
aData);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinnerAdapter);
spn.setOnItemSelectedListener(new SpinnerInfo());
}
private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
private boolean isFirst = true;
String selected;
#Override
public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
{
if (isFirst)
{
isFirst = false;
}
else
{
String selection = spinner.getItemAtPosition(selectedIndex).toString();
selected = selection;
}
Toast tempMessage =
Toast.makeText(addLocation.this,
selected,
Toast.LENGTH_SHORT);
tempMessage.show();
}
#Override
public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
}
}
the thing is i needed to get the id of the selected location not the index in the spinner but it's database id. any idea on how i can do this? thanks so much in advance!
i needed to get the id of the selected location not the index in the
spinner but it's database id. any idea on how i can do this?
Do it as using HashMap:
1. Use HashMap instead of Set with location as a key and location id as value. change getAllData() :
public Map<String, Integer> getAllData()
{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
...
if (cursor.moveToFirst()) {
do {
hashMap.put(cursor.getString(1),cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return hashMap;
}
2. Pass all keys to Spinner :
Map<String, Integer> hashMap = db.getAllData();
List<String> allLocations = new ArrayList<String>(hashMap.keySet());
3. Now In onItemSelected use selected String to get id of Selected item:
int location_id=hashMap.get(selected);

Storing primary key values in SQLite database in android using SharedPreferences

I have a form which asks values like name, gender etc. These values are stored in a table with a primary key field Id which is not entered by the user. I have to enter it with incrementing its value every time a new record is saved by using SharedPreferences. How do I do that?
This is my class file:
saveBtn = (Button) view.findViewById(R.id.save);
saveBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
String name = nameEdt.getText().toString().trim();
String trainingTypes = trainingTypesSpn.toString().trim();
String trainerProfile = trainerProfileSpn.toString().trim();
String description = descriptionEdt.toString().trim();
String plannedBudget = plannedBudgetNp.toString().trim();
String startDt = startDtEdt.toString().trim();
String endDt = endDtEdt.toString().trim();
TrainingDetailsDTO dto = new TrainingDetailsDTO();
dto.setName(name);
dto.setTrainingTypes(trainingTypes);
dto.setTrainerProfile(trainerProfile);
dto.setDescription(description);
dto.setPlannedBudget(plannedBudget);
dto.setStartDt(startDt);
dto.setEndDt(endDt);
SQLiteDatabase database = DBHandler.getInstance(mActivity).getDBObject(1);
boolean isInsert = TrainingDetailsDAO.getInstance().insert(dto, database);
if (isInsert)
{
Toast.makeText(mActivity, "Inserted Successfully", Toast.LENGTH_SHORT).show();
mActivity.popFragments();
mActivity.pushFragments(Constants.TAB_HOUSE, new HouseConstructionTrack(), false, false);
}
else
{
Toast.makeText(mActivity, "Insert Problem", Toast.LENGTH_SHORT).show();
}
mActivity.popFragments();
}
});
This is my insert method in DAO class:
public boolean insert(DTO dtoObject, SQLiteDatabase dbObject)
{
TrainingDetailsDTO dto = (TrainingDetailsDTO) dtoObject;
ContentValues cValues = new ContentValues();
cValues.put("TrainingDetailsId", "TR001");
cValues.put("name" , dto.getName());
cValues.put("trainingTypes" , dto.getTrainingTypes());
cValues.put("trainerProfile", dto.getTrainerProfile());
cValues.put("description" , dto.getDescription());
cValues.put("plannedBudget" , dto.getPlannedBudget());
cValues.put("startDt" , dto.getStartDt());
cValues.put("endDt" , dto.getEndDt());
dbObject.insert("TRAINING_DETAILS", null, cValues);
return false;
}
Here I am only able to give Id for the first record. How to generate subsequent Ids using SharedPreferences?
Extend BaseColumns in Android. It automatically has _ID field which is incremented automatically.
public static abstract class User implements BaseColumns {
public static final String TABLE_NAME = "user";
public static final String COLUMN_NAME_TOKEN = "token";
}

Android SQL query not ordering data

I have written a small android app that grabs some data and displays it in a ListView.
I want to have the list sorted in ascending order (no prob). But when I add a new item it stays at the bottom of the list even when the view/app is reloaded. It seems the only data that is being sorted is the entries that were created in the database OnCreate() method.
I'm not sure what code to provide but i'll start by showing you snippets of the DBAdapter class, then from the main app class.
Database construction query:
private static final String DATABASE_CREATE =
"create table "+ DATABASE_TABLE
+ "("
+ FIELD_ROWID+" integer primary key autoincrement, "
+ FIELD_NAME +" varchar(30) not null, " + FIELD_TELEPHONE + " varchar(20) not null, "
+ FIELD_ADDRESS + " text not null,"
+ FIELD_URL + " varchar(255) not null);";
Function to get list of data:
public Cursor getRestaurants()
{
Cursor result = null;
try{
result = db.query(DATABASE_TABLE, new String[] {FIELD_ROWID, FIELD_NAME}, null, null, null, null, FIELD_NAME+" ASC");
}
catch (Exception e)
{
Log.v("applog", e.getMessage());
}
return result;
}
Here is a snippet of the main method. Here you can see that I am calling the getRestaurants() function shown above. I'm stumped as to why the data isn't being sorted.
Any advice greatly appreciated. Thanks in advance.
public class Assignment2 extends ListActivity {
// Set up some global variables.
private static final int ADD_NEW_ID = Menu.FIRST;
private static final int CLOSE_APP_ID = ADD_NEW_ID+1;
private final DBAdapter db = new DBAdapter(this);
private static CursorAdapter curAdapter = null;
private static Cursor rawData = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
db.open(); // Open connection to restaurant db.
rawData = db.getRestaurants();
Log.v("applog", rawData.getCount()+" Restaurants loaded from DB.");
if(rawData.getCount() == 0)
{
Toast.makeText(getApplicationContext(), "No restaurants found.", Toast.LENGTH_SHORT).show();
}
try
{
/* The following two arrays are used to map DB fields to ListView items
* From a custom layout file.
*/
// Array of db fields to be used when converting cursor to ListView
String[] strFields = { "name", BaseColumns._ID };
// Array of listview id's to be used when populating the ListView
int[] intFields = { R.id.first };
curAdapter = new SimpleCursorAdapter(this, R.layout.row, rawData, strFields, intFields);
}
catch (Exception e)
{
Log.v("applog", e.getMessage());
}
// Apply the converter cursor to the current ListView
setListAdapter(curAdapter);
db.close(); // Close connection to restaurant db.
Im not sure exactly what your problem is but, it all looks good minus these lines of code I have when I get a callback from my new data insert
if(cursor!=null)cursor.requery();
adapter.notifyDataSetChanged();
Hopefully this will fix your issue.

Categories

Resources