I am working on application, that exists Sqlite Database. What I have done to implement the search on sqlite database using list, I have implemented the like query and I came to know; The searchview is not searching data from sqlite...
Here is my Sqlite File....
public List<GetSetClientsDetail> SearchClientsData() {
String[] columns = {
fname,
route,
cnic,
lname,
contact
};
String sortOrder = fname + " ASC";
List<GetSetClientsDetail> clientlist = new ArrayList<GetSetClientsDetail>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
table_poducts_records,
new String[] { fname, route, cnic, lname, contact},
fname + " LIKE '%" + fname + "%'",
null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
GetSetClientsDetail clientsDetail = new GetSetClientsDetail();
clientsDetail.setFNAME(cursor.getString(cursor.getColumnIndex(fname)));
clientsDetail.setROUTE(cursor.getString(cursor.getColumnIndex(route)));
clientsDetail.setCNIC(cursor.getString(cursor.getColumnIndex(cnic)));
clientsDetail.setLNAME(cursor.getString(cursor.getColumnIndex(lname)));
clientsDetail.setCONTACT(cursor.getString(cursor.getColumnIndex(contact)));
clientlist.add(clientsDetail);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return clientlist;
}
Here is my viewpage class of search where I have implemented search..
public class Clients extends Fragment {
RecyclerView recyclerViewClients;
Button btnAll;
SearchView searchViewclient;
ClientRecyclerAdapter clientRecyclerAdapter;
List<GetSetClientsDetail> listclients;
DatabaseHelper databaseHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.clients, container, false);
btnAll=view.findViewById(R.id.searchallclients);
recyclerViewClients=view.findViewById(R.id.recyclerviewallclients);
searchViewclient=view.findViewById(R.id.searchclient);
listclients = new ArrayList<>();
clientRecyclerAdapter = new ClientRecyclerAdapter(listclients,recyclerViewClients);
recyclerViewClients.setItemAnimator(new DefaultItemAnimator());
recyclerViewClients.setItemAnimator(new DefaultItemAnimator()); //multi copy paste!
recyclerViewClients.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerViewClients.setHasFixedSize(true);
recyclerViewClients.setAdapter(clientRecyclerAdapter);
databaseHelper = new DatabaseHelper(getActivity());
searchViewclient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SearchSQliteClientData();
}
});
btnAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getClientFromSqlite();
}
});
return view;
}
#SuppressLint("StaticFieldLeak")
private void SearchSQliteClientData() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listclients.clear();
listclients.addAll(databaseHelper.SearchClientsData());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
clientRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
#SuppressLint("StaticFieldLeak")
private void getClientFromSqlite() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listclients.clear();
listclients.addAll(databaseHelper.getAllClientsData());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
clientRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
What I want to do is As I press A on searchview; It brings all data related to a or If I press a letter It bring that data in the list I have Implemented..
As an example
change public List<GetSetClientsDetail> SearchClientsData()
to
public List<GetSetClientsDetail> SearchClientsData(String mysearchstring)
this allows the search argument to be passed to the method from the caller
Then change :-
Cursor cursor = db.query(
table_poducts_records,
new String[] { fname, route, cnic, lname, contact},
fname + " LIKE '%" + fname + "%'",
null, null, null, null, null);
to
String[] whereargs = new String[]{"%" + mysearchstring + "%"}; //<<<<<<<<<< ADDED
Cursor cursor = db.query(
table_poducts_records,
new String[] { fname, route, cnic, lname, contact},
fname + " LIKE ?", //<<<<<<<<<< CHANGED
whereargs, //<<<<<<<<<< ADDED
null, null, null); //<<<<<<<<<< 3 nulls instead of 4 (as whereargs has replaced first null)
this uses the search argument passed to the method in the LIKE clause protecting against SQL Injection
As a test try :-
listclients.addAll(databaseHelper.SearchClientsData("A")); //<<<<<<<<<< look for all with A anywhere in the fname column
Working example
The following is a working example based upon the code in the question but simplified for convenience.
The core change is two fold as, the above code is in the database helper DatabaseHelper.java as per :-
That is the SearchClientData method is :-
public List<GetSetClientsDetail> SearchClientsData(String mysearchstring) {
String[] columns = {
fname, route, cnic, lname, contact
};
String sortOrder = fname + " ASC";
List<GetSetClientsDetail> clientlist = new ArrayList<GetSetClientsDetail>();
SQLiteDatabase db = this.getReadableDatabase();
String[] whereargs = new String[]{"%" + mysearchstring + "%"}; //<<<<<<<<<< ADDED
Cursor cursor = db.query(
table_poducts_records,
new String[]{fname, route, cnic, lname, contact},
fname + " LIKE ?",
whereargs,
null, null, sortOrder, null
);
if (cursor.moveToFirst()) {
do {
GetSetClientsDetail clientsDetail = new GetSetClientsDetail();
clientsDetail.setFNAME(cursor.getString(cursor.getColumnIndex(fname)));
clientsDetail.setROUTE(cursor.getString(cursor.getColumnIndex(route)));
clientsDetail.setCNIC(cursor.getString(cursor.getColumnIndex(cnic)));
clientsDetail.setLNAME(cursor.getString(cursor.getColumnIndex(lname)));
clientsDetail.setCONTACT(cursor.getString(cursor.getColumnIndex(contact)));
clientlist.add(clientsDetail);
} while (cursor.moveToNext());
}
cursor.close();
return clientlist;
}
public List<GetSetClientsDetail> getAllClientsData() {
return SearchClientsData("");
}
Note the freebie getAllClientsData which just uses the SearchClientData method passing "", which will select all rows.
The other core change is that instead of relying upon the SearchView's OnClickListener which may well get called due to the Views other Listener's stealing the focus-ability.
The SearchView's setOnQueryTextListener has been utilised. This allows the text to be passed to the SearchClientsData.
For convenience this example utilises an ArrayAdapter and the stock Simple_List_Item1 layout and does the work on the main thread and of activity.
The Activity code used was :-
public class MainActivity extends AppCompatActivity {
ListView listviewClients;
Button btnAll;
ArrayAdapter mSCA;
SearchView searchViewclient;
List<GetSetClientsDetail> listclients;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAll=this.findViewById(R.id.searchallclients);
listviewClients=this.findViewById(R.id.clients);
searchViewclient=this.findViewById(R.id.searchclient);
databaseHelper = new DatabaseHelper(this);
addSomeData();
manageListView("");
searchViewclient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manageListView("zzz");
}
});
searchViewclient.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
manageListView(newText);
return false;
}
});
btnAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manageListView("");
}
});
}
private void manageListView(String searchArgument) {
listclients = databaseHelper.SearchClientsData(searchArgument);
if (mSCA == null) {
mSCA = new ArrayAdapter(this,android.R.layout.simple_list_item_1,listclients);
listviewClients.setAdapter(mSCA);
} else {
mSCA.clear();
mSCA.addAll(listclients);
mSCA.notifyDataSetChanged();
}
}
private void addSomeData() {
databaseHelper.add("Albert","001","123456789","Smith","someone");
databaseHelper.add("Freda","001","123456789","Jones","someone");
databaseHelper.add("Mike","002","0987654321","Allenby","him");
}
/*
private void SearchSQliteClientData() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listclients.clear();
listclients.addAll(databaseHelper.SearchClientsData());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
clientRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
private void getClientFromSqlite() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listclients.clear();
listclients.addAll(databaseHelper.getAllClientsData());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
clientRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
*/
}
The addSomeData method does as it says adds some testing data. The commented out code is original but unused code.
Result
When first run (not really the 1st, rather after a number of runs BUT freshly started, hence plenty of data) :-
Typing a or A and all the Mike's disappear
and so on, the list is instantly adjusted according to the text entered in the search field. Clicking the ALL button re-displays all.
I've been looking around everywhere in trying to find out why my code was causing an issue. I have a GridView that has an ArrayAdapter which pulls photos down with an AsyncTask. I can see the items being updated but when I try to update the adapter the GridView doesn't seem to update with the new view.
This is the relevant code that does the work...
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
//String id = object.getString("id");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
if(gridViewAdapter != null){
gridViewAdapter.clear();
gridViewAdapter.addAll(list);
gridViewAdapter.notifyDataSetChanged();
gridView.invalidateViews();
} else {
gridViewAdapter = new GridViewAdapter(getActivity(), R.layout.gridview_item, list);
gridView.setAdapter(gridViewAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
I would really appreciate any help if possible. Trying to get the app out before new years :).
Maybe If you could tell me why this happens so It won't cause an issue again and other will see.
EDIT: Added a bit more code which has it refreshing after I click the button twice.
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
pictureAdapter = new PictureAdapter(getActivity(), list);
gridView.setAdapter(pictureAdapter);
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list);
gridView.invalidate();
progressDialog.dismiss();
}
}
Adapter:
public class PictureAdapter extends BaseAdapter {
private ArrayList<ImageItem> items;
private Context context;
private TextView titleText;
private ImageView itemImage;
public PictureAdapter(Context context, ArrayList<ImageItem> items){
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.gridview_item, parent, false);
titleText = (TextView) v.findViewById(R.id.text);
itemImage = (ImageView)v.findViewById(R.id.image);
titleText.setText(items.get(position).getTitle());
Picasso.with(context).load(items.get(position).getUrl()).fit().into(itemImage);
return v;
}
public void updateItemList(ArrayList<ImageItem> newItemList){
this.items = newItemList;
notifyDataSetChanged();
}
}
Try the below lines in post execute
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list,gridView);
progressDialog.dismiss();
}
Now in your updateItemList
public void updateItemList(ArrayList<ImageItem> newItemList,GridView gridView){
this.items = newItemList;
gridView.setAdapter(null);
gridView.invalidateViews();
gridView.deferNotifyDataSetChanged();
gridView.setAdapter(list);
}
Why you are calling Volley request from AsyncTask as Volley perform request on NetworkThread.
Remove AsyncTask and directly call Volley.
Just try this. Hope it helps.
private ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
progressDialog.show();
fetchJsonResponse(url);
}
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
pictureAdapter.notifyDataSetChanged();
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
I use Retrofit library for getting and parsing JSON from server.
All methods I run in MainActivity when Application is starting. And I have trouble when I check is Object(parsed from JSON) already exist in Data Base or not. Application is not responsing. What can I do?
here is MainActivity:
public class MainActivity extends FragmentActivity implements MYFragmentListener, OnBackPressedListener {
public static String FRAGMENT_INSTANCE_NAME = "";
public static String PACKAGE_NAME;
private DrawerLayout mDrawerLayout;
DrawerAdapter listAdapter;
private Level level;
private String drawerlist[];
public static DrawerLayout drawer_layout;
private ListView mDrawerList;
private int EXPAND_GROUP;
private int SELECTED_CHILD;
private int LANGUAGE_POSITION;
int height;
public AsanaPOJO [] asanasPOJO;
private List<String> listDataHeader;
private List<String> listData;
private HashMap<String, List<String>> listDataChild;
private ExpandableListView expListView;
private ExpandableListView.LayoutParams expParam;
private LinearLayout expListLay;
private List<String> language;
private FragmentTransaction fTrans;
private FragmentManager fm;
private mainFragmentPh main_fragment_ph;
private StepOnePh step_one_ph;
private StepTwoPh step_two_ph;
private ProgramsVideoPh program_video_ph;
private ProgramOnePh program_one_ph;
private ProgramsPh programs_ph;
private AsanaOnePh asana_one_ph;
private AsanasPh asanas_ph;
private Finish2Ph finish2_ph;
private mainFragmentTb main_fragment_tb;
private ProgramAddTb program_add_tb;
private ProgramsVideoTb programs_video_tb;
private ProgramOneTb program_one_tb;
private ProgramsTb programs_tb;
private AsanaOneTb asana_one_tb;
private AsanasTb asanas_tb;
private Finish2Tb finish2_tb;
private AsanaInfoTb asana_info_tb;
Fragment fragment;
private Finish finish;
private add add_d;
boolean drawer_st;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PACKAGE_NAME = getApplicationContext().getPackageName();
LANGUAGE_POSITION=-1;
language = new ArrayList();
final MYDBHelperFromApi DBHelperAPI = new MYDBHelperFromApi(this);
MYapi myapi = (MYapi) new Builder().setLogLevel(LogLevel.FULL).setEndpoint(MYurl.BASE_URL).build().create(MYapi.class);
myapi.getLanguages(new Callback<HashMap<String, String>>() {
public void success(HashMap<String, String> hashMap, Response response) {
language.addAll(hashMap.values());
Log.d("LOGS", hashMap.toString() + " " + response.toString());
DBHelperAPI.addLanguages(hashMap);
}
public void failure(RetrofitError error) {
Log.d("LOGS", "FUUUUUUUUUUUU");
}
});
myapi.getLevelList(new Callback<List<AsanaLevel>>() {
public void success(List<AsanaLevel> asanaLevels, Response response) {
for (AsanaLevel a : asanaLevels) {
Log.d("LEVELASANA LOGS", BuildConfig.FLAVOR + a.toString());
}
DBHelperAPI.addAsanaLevel(asanaLevels);
}
public void failure(RetrofitError error) {
}
});
myapi.getTypeList(new Callback<List<AsanaType>>() {
public void success(List<AsanaType> asanaTypes, Response response) {
for (AsanaType a : asanaTypes) {
Log.d("TYPEASANA LOGS", BuildConfig.FLAVOR + a.toString());
}
DBHelperAPI.addAsanaType(asanaTypes);
}
public void failure(RetrofitError error) {
}
});
myapi.getProgramGoalList(new Callback<List<ProgramGoal>>() {
public void success(List<ProgramGoal> programGoals, Response response) {
for (ProgramGoal a : programGoals) {
Log.d("GOALPROGRAM LOGS", BuildConfig.FLAVOR + a.toString());
}
DBHelperAPI.addProgramGoal(programGoals);
}
public void failure(RetrofitError error) {
}
});
myapi.getProgramLevelList(new Callback<List<ProgramLevel>>() {
public void success(List<ProgramLevel> programLevels, Response response) {
for (ProgramLevel a : programLevels) {
Log.d("LevelPROGRAM LOGS", BuildConfig.FLAVOR + a.toString());
}
DBHelperAPI.addProgramLevel(programLevels);
}
public void failure(RetrofitError error) {
}
});
myapi.getAsanas(new Callback<Asanas>() {
public void success(Asanas asanas,
Response response) {
DBHelperAPI.addAsanas(asanas);
List<Integer> listDB = DBHelperAPI.getAsanasIds();
DBHelperAPI.checkForDeletedAsanas(asanas, listDB);
for (AsanaPOJO a : asanas.getAsanas()) {
Log.d("AsanaPROGRAM LOGS", BuildConfig.FLAVOR + a.getName());
}
}
public void failure(RetrofitError error) {
Log.d("FAILURE", "Failure");
}
});
myapi.getPrograms(new Callback<Programs>() {
#Override
public void success(Programs programs, Response response) {
DBHelperAPI.addPrograms(programs);
for (ProgramPOJO p : programs.getPrograms()) {
Log.d("PROGRAMs LOGS", BuildConfig.FLAVOR + p.getName());
}
}
#Override
public void failure(RetrofitError error) {
}
});
expListLay =(LinearLayout) findViewById(R.id.expListlay);
..................
}
and methods from DBhelper:
public void addPrograms(Programs programs){
open();
ContentValues values = new ContentValues();
for (ProgramPOJO p : programs.getPrograms()) {
values.put(KEY_ID,p.getId());
values.put(KEY_DURATION,p.getDuration());
values.put(KEY_MAX_AGE,p.getMax_age());
values.put(KEY_MIN_AGE,p.getMin_age());
values.put(KEY_ISPAID,p.checkBool(p.getIs_paid()));
values.put(KEY_IS_QUICK_RECEIPT,p.checkBool(p.getIs_quick_receipt()));
values.put(KEY_BACKGROUND_SOUND_ID,p.getBackground_sound_id());
values.put(KEY_IMGLARGE,p.getImgLarge());
values.put(KEY_IMGTHUMB,p.getImgThumb());
values.put(KEY_NAME,p.getName());
values.put(KEY_GOAL_ID,p.getGoal_id());
values.put(KEY_LEVEL_ID,p.getLevel_id());
values.put(KEY_OLDPK,p.getOld_pk());
if (checkById(TABLE_PROGRAMS, KEY_ID, p.getId())) {
Log.d("LOGSPROGRAMOnly", " allready exist");
} else {
this.dbase.insert(TABLE_PROGRAMS, null, values);
Log.d("LOGSPROGRAMOnly", p.getName() + " added");
}
for (Poses poses :p.getPoses()){
ContentValues valuesForPose = new ContentValues();
valuesForPose.put(KEY_ID,poses.getId());
valuesForPose.put(KEY_POSITION,poses.getPosition());
valuesForPose.put(KEY_DURATION,poses.getDuration());
valuesForPose.put(KEY_VOICE,poses.getVoice());
valuesForPose.put(KEY_ASANA_ID,poses.getAsana_id());
valuesForPose.put(KEY_OLDPK,poses.getOld_pk());
if (checkById(TABLE_POSES, KEY_ID, poses.getId())) {
Log.d("LOGSPose", " allready exist");
} else {
this.dbase.insert(TABLE_POSES, null, valuesForPose);
Log.d("LOGSPose", p.getName() + " added");
}
ContentValues valuesForPoseProgram = new ContentValues();
valuesForPoseProgram.put(KEY_PROGRAM_ID, p.getId());
valuesForPoseProgram.put(KEY_POSE_ID, poses.getId());
if (checkPoseById(p.getId(), poses.getId())) {
Log.d("LOGSPROGRAMPose", " allready exist");
} else {
this.dbase.insert(TABLE_POSES_PROGRAMS, null, valuesForPoseProgram);
Log.d("LOGSPROGRAMPose", p.getName() + " added");
}
}
}
}
public void addAsanas(Asanas asanas) {
open();
ContentValues values = new ContentValues();
for (AsanaPOJO a : asanas.getAsanas()) {
values.put(KEY_ID, Integer.valueOf(a.getId()));
values.put(KEY_NAME, a.getName());
values.put(KEY_IMGLARGE, a.getImgLarge());
values.put(KEY_IMGTHUMB, a.getImgThumb());
values.put(KEY_LEVELID, Integer.valueOf(a.getLevel_id()));
values.put(KEY_TYPEID, Integer.valueOf(a.getType_id()));
values.put(KEY_AUDIO, a.getAudio());
values.put(KEY_TITLEAUDIO, a.getTitle_audio());
values.put(KEY_DURATION, Integer.valueOf(a.getDuration()));
values.put(KEY_SHORTDESC, a.getShortDesc());
values.put(KEY_FULLDESC, a.getFullDesc());
values.put(KEY_PHOTO, a.getPhoto());
values.put(KEY_SANSKRITNAME, a.getSanskrit_name());
values.put(KEY_SANSKRITAUDIOTITLE, a.getSanskrit_audio_title());
values.put(KEY_BREATHINGVIDEO, a.getBreathing_video());
values.put(KEY_ISBREATHING, Integer.valueOf(a.checkBool(a.getIs_breathing())));
values.put(KEY_ISPAID, Integer.valueOf(a.checkBool(a.getIs_paid())));
values.put(KEY_OLDIDENTIFIER, a.getName());
values.put(KEY_OLDPK, a.getName());
values.put(KEY_VIDEO, a.getVideo());
if (checkById(TABLE_ASANAS, KEY_ID, a.getId())) {
Log.d("LOGSASANA", " allready exist");
} else {
this.dbase.insert(TABLE_ASANAS, null, values);
Log.d("LOGSASANA", a.getName() + " added");
}
}
close();
}
public boolean checkById(String TableName, String dbfield, int id){
Cursor cursor = this.dbase.rawQuery("SELECT * FROM " + TableName + " WHERE " + dbfield + " = " + id , null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
what you have done is calling endpoint async-ly and processing the heavy db operation in main thread.
You can do all these stuff in background thread using single AsyncTask.
Change your async retrofit endpoints to synchronous like:
void getPrograms(Callback<Programs>);
to
Programs myapi.getPrograms();
and a single async task like:
public class MyHeavyTask extends AsyncTask<Void, Void, Void> {
private final MYDBHelperFromApi DBHelperAPI;
private final MYapi myapi;
public MyHeavyTask(MYDBHelperFromApi DBHelperAPI, MYapi myapi) {
this.DBHelperAPI = DBHelperAPI;
this.myapi = myapi;
}
#Override
protected Void doInBackground(Void... params) {
HashMap<String, String> hashMap = myapi.getLanguages();
boolean valid = hashMap != null;// do other validation catch exceptions if needed
//Do response validation
//Add to your database
if (valid)
DBHelperAPI.addLanguages(hashMap);
//similarly
List<AsanaLevel> asanaLevels = myapi.getLevelList();
DBHelperAPI.addAsanaLevel(asanaLevels);
List<AsanaType> asanaTypes = myapi.getTypeList();
DBHelperAPI.addAsanaType(asanaTypes);
List<ProgramGoal> programGoals = myapi.getProgramGoalList();
DBHelperAPI.addProgramGoal(programGoals);
//Similarly others
return null;
}
}
Now execute the task in onCreate method like:
new MyHeavyTask(DBHelperAPI,myapi).execute();
I try to create offline SQLite database for my send job module in android application. but the database in not created in DDMS .Tell me where I am wrong in the given code below.
Fregmentsendjob.java
public class FragmentSendJob extends Fragment implements OnClickListener {
// this Fragment will be called from MainActivity
private Button submit,cancel;
private EditText ename,mobno,picktime,unit,street,suburb,destination,fare,city;
private Spinner state,group;
private ViewGroup vgroup ;
String name,pass;
String status_key;
private Typeface ftype;
private static MyDialog dialog1;
Bitmap bitmap1, bitmap2,bitmap3;
Bitmap[] bitmap;
String[] driver_details;
private byte imageInByte1[],imageInByte2[],imageInByte3[] ;
private Context mContext;
public String advertisement_count;
private String mename,mmobno,mpicktime,munit,mstreet,msuburb,mstate, msendjob,mcity,mdestination,mfare,mgroup,login_token;
// private String sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate, ssendjob,scity,sdestination,sfare,sgroup,login_token;
private static FragmentDialog dialog;
//private SendJobDataBase db;
private PasswordDB db;
static final int DIALOG_ID = 0;
private SharedPreferences pref1,pref;
String latitude,longitude;
public String job_id;
public FragmentSendJob(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.sendjob_fragment, container, false);
pref1=this.getActivity().getSharedPreferences("LocDetails", getActivity().MODE_WORLD_READABLE);
pref=this.getActivity().getSharedPreferences("Driver", getActivity().MODE_WORLD_READABLE);
login_token=pref.getString("login_token","login_token");
latitude = pref1.getString("latitude","latitude");
longitude = pref1.getString("longitude","longitude");
ename = (EditText) rootView.findViewById(R.id.ename);
mobno = (EditText) rootView.findViewById(R.id.mobno);
picktime = (EditText) rootView.findViewById(R.id.picktime);
unit = (EditText) rootView.findViewById(R.id.unit);
street = (EditText) rootView.findViewById(R.id.street);
suburb = (EditText) rootView.findViewById(R.id.suburb);
destination = (EditText) rootView.findViewById(R.id.destination);
state = (Spinner) rootView.findViewById(R.id.state);
fare=(EditText) rootView.findViewById(R.id.fare);
group = (Spinner) rootView.findViewById(R.id.group);
city = (EditText) rootView.findViewById(R.id.city);
vgroup = (ViewGroup) rootView.findViewById(R.id.rel);
submit = (Button) rootView.findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new SendJob().execute();
/* Intent intent =new Intent(getActivity(),GetCurrentLocation.class);
startActivity(intent);
System.out.println(">>>>>>>>>>>>>>>>>"+latitude+"***********");
System.out.println(">>>>>>>>>>>>"+longitude+"***********");*/
}
});
cancel = (Button) rootView.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = 0, count = vgroup.getChildCount(); i < count; ++i) {
View view = vgroup.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
}
}
});
String[] mystate= new String[]{"New South Wales","Victoria","Queensland","Northern Territory","Western Australia","South Australia"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.listrow, mystate);
state.setAdapter(adapter);
state.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) {
// TODO Auto-generated method stub
mcity = state.getSelectedItem().toString();
String s1=arg0.getItemAtPosition(pos).toString();
if(s1.equals("New South Wales"))
city.setText("Sydney");
else if(s1.equals("Victoria"))
city.setText("Melbourne");
else if(s1.equals("Queensland"))
city.setText("Brisbane");
else if(s1.equals("Northern Territory"))
city.setText("Darwin");
else if(s1.equals("Western Australia"))
city.setText("Perth");
else if(s1.equals("South Australia"))
city.setText("Adelaide");
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
String[] mygroups= new String[]{"My Group","My Secondary group","Everyone"};
ArrayAdapter<String> adapters = new ArrayAdapter<String>(this.getActivity(),
R.layout.listrow, mygroups);
group.setAdapter(adapters);
group.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
msendjob = group.getItemAtPosition(pos).toString();
//gender.setText(setgender);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return rootView;
}
private class SendJob extends AsyncTask<String, String, String[]> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
#Override
protected String[] doInBackground(final String... params)
{
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
HttpClient httpclient = new DefaultHttpClient();
try
{
System.out.print("***** login token *****"+login_token);
JSONObject job= new JSONObject();
mename = ename.getText().toString();
mmobno = mobno.getText().toString();
mpicktime = picktime.getText().toString();
munit = unit.getText().toString();
mstreet = street.getText().toString();
msuburb = suburb.getText().toString();
mstate = state.getSelectedItem().toString();
mcity = city.getText().toString();
mdestination = destination.getText().toString();
mgroup = group.getSelectedItem().toString();
mfare = fare.getText().toString();
mename.replace("" ,"%20");
mmobno.replace("" ,"%20");
mpicktime.replace("" ,"%20");
munit.replace("" ,"%20");
mstreet.replace("" ,"%20");
mstate.replace("" ,"%20");
msuburb.replace("" ,"%20");
mcity.replace("" ,"%20");
mdestination.replace("" ,"%20");
mgroup.replace("" ,"%20");
mfare.replace("" ,"%20");
job.put("name",mename);
job.put("mobile_no",mmobno);
job.put("pickup_time",mpicktime);
job.put("unit_no",munit);
job.put("street_name",mstreet);
job.put("state",mstate);
job.put("suburb",msuburb);
job.put("city",mcity);
job.put("destination",mdestination);
job.put("group",mgroup);
job.put("fare",mfare);
job.put("latitude",latitude);
job.put("longitude",longitude);
job.put("status_key","2");
job.put("method","send_job");
job.put("login_token",login_token);
StringEntity se = new StringEntity(job.toString());
HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String data = EntityUtils.toString(response.getEntity());
Log.i("response", data);
System.out.println("response "+data);
String call;
call = data;
System.out.println("print me............."+call);
JSONObject jo = new JSONObject(data);
Log.d("response", jo.toString(4));
/*JSONObject jobId= jo.getJSONObject("id");
job_id=jobId.getString("id");*/
if(jo.getString("err-code").equals("0"))
{
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Alert!!!");
alert.setMessage(jo.getString("message"));
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
pDialog.dismiss();
dialog.dismiss();
/* Intent intent =new Intent(getActivity(),HandleData.class);
intent.putExtra("pickupsuburb", ssuburb);
intent.putExtra("destination", sdestination);
startActivity(intent);*/
}
});
getActivity().runOnUiThread(new Runnable() {
public void run() {
alert.show();
}
});
}
else
{
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Alert !");
alert.setMessage(jo.getString("message"));
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
pDialog.dismiss();
alert.show();
}
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
return params;
}
#Override
protected void onPostExecute(String[] result)
{
super.onPostExecute(result);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
**SendJobDatabase.java**
public class SendJobDataBase
{
private static final String DATABASE_NAME = "SENDJOB.db";
private static final int DATABASE_VERSION = 2;
static final String TABLE_NAME = "jobsend";
private static final String KEY_ID = "id";
private static Context context;
static SQLiteDatabase db;
private final ArrayList<member> user = new ArrayList<member>();
OpenHelper helper;
private SQLiteStatement insertStmt;
//creation of string value and insert that string value into table name
private static final String INSERT = "insert into " + TABLE_NAME + " (mename,mmobno,mpicktime,munit,mstreet,msuburb,mstate,mcity,mdestination,mfare,mgroup) values (?,?,?,?,?,?,?,?,?,?,?)";
// private static final String INSERT = "insert into " + TABLE_NAME + " (sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate,scity,sdestination,sfare,sgroup) values (?,?,?,?,?,?,?,?,?,?,?)";
protected static final String enternpw = null;
public SendJobDataBase(Context context) {
SendJobDataBase.context = context;
OpenHelper openHelper = new OpenHelper(SendJobDataBase.context);
SendJobDataBase.db = openHelper.getWritableDatabase();
this.insertStmt = SendJobDataBase.db.compileStatement(INSERT);
}
//public long insert(String sename,String smobno,String spicktime,String sunit,String sstreet,String ssuburb,String sstate,String scity,String sdestination,String sfare,String sgroup) {
public long insert(String mename,String mmobno,String mpicktime,String munit,String mstreet,String msuburb,String mstate,String mcity,String mdestination,String mfare,String mgroup) {
this.insertStmt.bindString(1, mename);
this.insertStmt.bindString(2, mmobno);
this.insertStmt.bindString(3, mpicktime);
this.insertStmt.bindString(4, munit);
this.insertStmt.bindString(5, mstreet);
this.insertStmt.bindString(6, msuburb);
this.insertStmt.bindString(7, mstate);
this.insertStmt.bindString(8, mcity);
this.insertStmt.bindString(9, mdestination);
this.insertStmt.bindString(10, mfare);
this.insertStmt.bindString(11, mgroup);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
//create a function and apply cursor activity to perform on function
List<String[]> list = new ArrayList<String[]>();
//Cursor cursor = db.query(TABLE_NAME, new String[] { "id","sename","smobno","spicktime","sunit","sstreet","ssuburb","sstate","scity","sdestination","sfare","sgroup" }, null, null, null, null, "sename asc");
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","mename","mmobno","mpicktime","munit","mstreet","msuburb","mstate","mcity","mdestination","mfare","mgroup" }, null, null, null, null, "sename asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5),
cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public ArrayList<member> getMembersList() {
ArrayList<member> user = new ArrayList<member>();
String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%One%'" ;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
user.add(contact);
} while (cursor.moveToNext());
}
}
cursor.close();
return user;
}
public ArrayList<member> getMembersList2() {
ArrayList<member> user = new ArrayList<member>();
String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%Two%'" ;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
user.add(contact);
} while (cursor.moveToNext());
}
}
cursor.close();
return user;
}
public void delete(int rowId) {
db.delete(TABLE_NAME, null, null);
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, sename TEXT, smobno TEXT,spicktime TEXT,spickaddr TEXT, sfair TEXT,ssendjob TEXT)");
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, mename TEXT, mmobno TEXT,mpicktime TEXT,mpickaddr TEXT, mfair TEXT,msendjob TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public Cursor rawQuery(String selectQuery ,Object object) {
// TODO Auto-generated method stub
return null;
}
public static SendJobDataBase getDBAdapterInstance(FragmentGroups viewPassword) {
// TODO Auto-generated method stub
return null;
}
public Object getenternpw() {
// TODO Auto-generated method stub
return null;
}
public static Cursor getSinlgeEntry() {
// TODO Auto-generated method stub
Cursor cur =db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
// colName1+"='"+name+"'" -> wherclause
System.out.println("Record count are "+cur.getCount());
return cur;
}
static public void close() {
// TODO Auto-generated method stub
}
/* public SendJobDataBase open() throws SQLException {
// TODO Auto-generated method stub
db = helper.getWritableDatabase();
return this;
} */
public SendJobDataBase getWritableDatabase() {
// TODO Auto-generated method stub
return null;
}
public void Delete_Contact(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
public ArrayList<member> Get_Contacts() {
try {
user.clear();
// Select All Query
String selectQuery = "SELECT * FROM jobsend";
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
member contact = new member();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
// contact.setPhoneNumber(cursor.getString(2));
// contact.setEmail(cursor.getString(3));
// Adding contact to list
user.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return user;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return user;
}
}
implementation 'com.intuit.sdp:sdp-android:1.0.4'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.android.support:recyclerview-v7:28.0.0'
activity_main.xml
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recyclerviiew_main"
android:layout_height="match_parent"/>
raw_innerview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:paddingLeft="1dp"
android:orientation="vertical"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:background="#color/colorAccent"
android:id="#+id/txt_Title"
android:layout_width="#dimen/_100sdp"
android:gravity="center"
android:layout_height="#dimen/_100sdp"
android:layout_marginTop="4dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
tools:text="More" />
</LinearLayout>
</LinearLayout>
raw_mailn_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:paddingLeft="1dp"
android:orientation="vertical"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
tools:text="Name" />
<TextView
android:id="#+id/txt_Title1"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
tools:text="More" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recyclerview_inner"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.app.playstorerecyclerviewdemo.model.InnerData;
import com.app.playstorerecyclerviewdemo.model.MainResponse;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
List arry_favorite =new ArrayList();
List arry_song =new ArrayList();
List arry_mostview=new ArrayList();
List arry_name =new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arry_favorite.add("1");
arry_favorite.add("2");
arry_favorite.add("3");
arry_favorite.add("4");
arry_song.add("1");
arry_song.add("2");
arry_song.add("3");
arry_song.add("4");
arry_song.add("5");
arry_song.add("6");
arry_song.add("7");
arry_mostview.add("1");
arry_mostview.add("5");
arry_mostview.add("6");
arry_name.add("Songs");
arry_name.add("Mostviews");
arry_name.add("Favourits");
InnerData datum=new InnerData();
MainResponse example=new MainResponse();
example.setStatus("true");
example.setMessage("Data is Display");
datum.setName("Title");
datum.setStatusMore("More");
datum.setFavorites(arry_favorite);
datum.setSongs(arry_song);
datum.setMostviewes(arry_mostview);
example.setData(datum);
Log.e("JSONS",new Gson().toJson(datum.toString()));
if(example.getStatus().equalsIgnoreCase("true"))
{
RecyclerView recyclerview=findViewById(R.id.recyclerviiew_main);
Toast.makeText(this, example.getMessage(), Toast.LENGTH_SHORT).show();
MainViewAdapter adapter = new MainViewAdapter(MainActivity.this, datum);
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
recyclerview.setLayoutManager(gridLayoutManager);
recyclerview.setAdapter(adapter);
}
else {
Toast.makeText(this, example.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
MainViewAdapter.java
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.app.playstorerecyclerviewdemo.model.InnerData;
public class MainViewAdapter extends RecyclerView.Adapter<MainViewAdapter.ViewHolder> {
public Context context;
public InnerData arraylist;
public MainViewAdapter(MainActivity listdata, InnerData arraylist)
{
this.context = listdata;
this.arraylist = arraylist;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.raw_mailn_view, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
if(arraylist.getName() !=null)
{
holder.txt_Title.setText(arraylist.getName());
}
if(arraylist.getStatusMore() !=null)
{
holder.txt_Title1.setText(arraylist.getStatusMore());
}
InnerViewAdapter adapter = new InnerViewAdapter((MainActivity) context, arraylist);
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
holder.recyclerview_inner.setLayoutManager(gridLayoutManager);
holder.recyclerview_inner.setAdapter(adapter);
}
#Override
public int getItemCount() {
return 10;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_Title,txt_Title1;
RecyclerView recyclerview_inner;
public ViewHolder(View itemView) {
super(itemView);
txt_Title = itemView.findViewById(R.id.txt_Title);
txt_Title1 = itemView.findViewById(R.id.txt_Title1);
recyclerview_inner=itemView.findViewById(R.id.recyclerview_inner);
}
}
}
InnerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.app.playstorerecyclerviewdemo.model.InnerData;
class InnerViewAdapter extends RecyclerView.Adapter<InnerViewAdapter.ViewHolder>
{
public Context context;
public InnerData arraylist;
public InnerViewAdapter(MainActivity listdata, InnerData arraylist)
{
this.context = listdata;
this.arraylist = arraylist;
}
#Override
public InnerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.raw_innerview, parent, false);
InnerViewAdapter.ViewHolder viewHolder = new InnerViewAdapter.ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(final InnerViewAdapter.ViewHolder holder, final int position)
{
if(arraylist.getSongs() !=null)
{
holder.txt_Title.setText(arraylist.getName());
holder.txt_Title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, ""+position, Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public int getItemCount() {
return 3;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_Title;
public ViewHolder(View itemView) {
super(itemView);
txt_Title = itemView.findViewById(R.id.txt_Title);
}
}
}
MainResponse.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MainResponse {
#SerializedName("status")
#Expose
private String status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
public InnerData data = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public InnerData getData() {
return data;
}
public void setData(InnerData data) {
this.data = data;
}
}
InnerData.java
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class InnerData {
#SerializedName("name")
#Expose
private String name;
#SerializedName("status_more")
#Expose
private String statusMore;
#SerializedName("songs")
#Expose
private List<Integer> songs = null;
#SerializedName("favorites")
#Expose
private List<Integer> favorites = null;
#SerializedName("mostviewes")
#Expose
private List<Integer> mostviewes = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatusMore() {
return statusMore;
}
public void setStatusMore(String statusMore) {
this.statusMore = statusMore;
}
public List<Integer> getSongs() {
return songs;
}
public void setSongs(List<Integer> songs) {
this.songs = songs;
}
public List<Integer> getFavorites() {
return favorites;
}
public void setFavorites(List<Integer> favorites) {
this.favorites = favorites;
}
public List<Integer> getMostviewes() {
return mostviewes;
}
public void setMostviewes(List<Integer> mostviewes) {
this.mostviewes = mostviewes;
}
}
Utility.scheduleJob(this, startLatitude, startLongitude, latitude, longitude);
#SuppressLint("NewApi")
#RequiresApi(api = Build.VERSION_CODES.M)
public static void scheduleJob(Context context, double startLatitude, double startLongitude, double latitude, Double longitude) {
ComponentName serviceComponent = new ComponentName(context, CalculateKmService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(10 * 1000); // wait at least 10 sec
builder.setOverrideDeadline(5 * 1000); // maximum delay
//builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
//builder.setRequiresDeviceIdle(true); // device should be idle
//builder.setRequiresCharging(false); // we don't care if the device is charging or not
jobScheduler = (JobScheduler) getContext().getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
Log.d("TAG", "scheduleJob:....... " + startLatitude + "....." + latitude);
Log.d("TAG", "scheduleJob:.......... " + startLongitude + "....." + longitude);
// startLatitude=23.072018;
// startLongitude=72.542134;
try {
// GoogleMatrixRequest.calculateKm(context, startLatitude, startLongitude, latitude, longitude);
if(FastSave.getInstance().getString(Constant.END_LAT_1).equals(""))
{
try
{
Log.d("TAG", "scheduleJob: from start");
GoogleMatrixRequest.calculateKm(context, startLatitude, startLongitude, latitude, longitude);
} catch (Exception e) {
e.printStackTrace();
}
}else{
double last_lat = Double.parseDouble(FastSave.getInstance().getString(Constant.END_LAT_1));
double last_lon = Double.parseDouble(FastSave.getInstance().getString(Constant.END_LON_1));
try {
Log.d("TAG", "scheduleJob: from next"+last_lat+"..."+last_lon+"///to.."+latitude+"..."+longitude);
GoogleMatrixRequest.calculateKm(context, last_lat, last_lon, latitude, longitude);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Utility.stopScheduleJob(this);
public static void stopScheduleJob(Context context) {
// Toast.makeText(context, "cancel job", Toast.LENGTH_SHORT).show();
if (jobScheduler != null)
{
jobScheduler.cancelAll();
FastSave.getInstance().saveString(Constant.END_LAT_1, "");
FastSave.getInstance().saveString(Constant.END_LON_1, "");
}
}
public class CalculateKmService extends JobService {
#Override
public boolean onStartJob(JobParameters jobParameters) {
// Toast.makeText(this, "schecdule", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onStartJob: working");
Utility.scheduleJob(getBaseContext(), DashboardActivity.startLatitude,DashboardActivity.startLongitude,DashboardActivity.latitude,DashboardActivity.longitude);
return false;
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
Utility.stopScheduleJob(getBaseContext());
return false;
}
}
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.sine.provider", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
#Multipart
#POST("add")
Call<AddResponse> doAdd(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("document_type", RequestBody.create(MediaType.parse("text/plain"), "insurance"));
multipart.add(Utility.prepareFilePart(InsurenceActivity.this, "document_file", picturePath));