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();
Related
Here I am sending data from local data base to mysql database server but aly first row data is uploading
Can anyone help me
here i am fetching data from sqlite using model class and display in recyclerview
now i want to send all recyclerview data in ARRAY or any other way to server database
Here 6 images are fetch from sqlite also send to server without setImage in UI directly want to send to Server
Thanks in advance....!!!
Activity Code
public class FetchLocalInsuranceListActivity extends AppCompatActivity {
protected ViewDialog viewDialog;
private RecyclerView recyclerview;
RequestQueue requestQueue;
private MyCustomAdapter myCustomAdapter;
Context context;
DatabaseHelper database;
List<DataModel> datamodel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fetch_local_insurance_list);
context = this;
datamodel = new ArrayList<DataModel>();
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
database = new DatabaseHelper(context);
datamodel = database.getAllSyncData();
recyclerview = (RecyclerView) findViewById(R.id.recycler_view__local_my_insurance);
LinearLayoutManager layoutManager = new LinearLayoutManager(FetchLocalInsuranceListActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
private List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView farmer_name, tv_Tagging_Date, tv_insurance_id;
protected ImageButton editButton;
public MyViewHolder(View view) {
super(view);
farmer_name = view.findViewById(R.id.text_insured_name);
tv_Tagging_Date = view.findViewById(R.id.tv_Tagging_Date);
tv_insurance_id = view.findViewById(R.id.tv_insurance_id);
editButton = itemView.findViewById(R.id.edit_button);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_local_insurance_list, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {
final DataModel datum = moviesList.get(position);
Log.e("image", datum.getAnimal_Tail_Photo() + "");
holder.farmer_name.setText("Farmer Name : " + datum.getFarmer_name() + "");
holder.tv_Tagging_Date.setText("Tagging Date : " + datum.getTagging_date() + "");
holder.tv_insurance_id.setText("#SNV_INSURANCE_" + datum.getId() + " ");
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDataParticularRow(datum);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
private void editDataParticularRow(DataModel dataModel) {
Intent intent = new Intent(FetchLocalInsuranceListActivity.this, EditBankAndFarmerActivity.class);
intent.putExtra("BANK_ID", dataModel.getId() + "");
Log.e("id", dataModel.getId() + "");
startActivity(intent);
}
protected final void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
public void doNormalPostOperation(final int i) {
requestQueue = Volley.newRequestQueue(FetchLocalInsuranceListActivity.this);
final ProgressDialog progressDialog = new ProgressDialog(FetchLocalInsuranceListActivity.this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://thelastoffers.com/snv/webservices/test.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
database.deleteData(Integer.parseInt(datamodel.get(i).getId() + ""));
database.deleteAnimalData(Integer.parseInt(datamodel.get(i).getFarmer_id() + ""));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FetchLocalInsuranceListActivity.this, "Something went Wrong.. Please Try again..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
// params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
// REMAINING PARAMS WITH SAME datamodel.get(i) item
params.put("type", "insertOfflineData");
params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
params.put("head_image_blob", String.valueOf(datamodel.get(i).getAnimal_Tag_Photo()));
params.put("farmer_bank_hypo", datamodel.get(i).getFarmer_bank_hypo() + "");
params.put("farmer_name", datamodel.get(i).getFarmer_name() + "");
params.put("farmer_village", datamodel.get(i).getVillage() + "");
params.put("farmer_taluka", datamodel.get(i).getTaluka() + "");
params.put("farmer_district", datamodel.get(i).getDistrict() + "");
params.put("tagging_date", datamodel.get(i).getTagging_date() + "");
Log.e("Data", params + "");
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.sync_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sync:
for (int i = 0; i < datamodel.size(); i++) {
doNormalPostOperation(i);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
Database Code
public List<DataModel> getAllSyncData() {
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM FARMER_SYNC_TABLE LEFT JOIN ANIMAL_SYNC_TABLE ON farmer_id = new_insurane_id ORDER BY new_insurane_id DESC";
Cursor cursor = db.rawQuery(query, null);
Log.e("value", query + ";" + " ");
StringBuilder stringBuffer = new StringBuilder();
if (cursor.moveToFirst()) {
do {
DataModel dataModel_1 = new DataModel();
int NEW_INSURANCE_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("new_insurane_id"));
String INSURANCE_ID_1 = cursor.getString(cursor.getColumnIndexOrThrow("insurance_id"));
String INSURED_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("insured_name"));
String BANKHYPO_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("bankhypo_name"));
String FARMER_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("farmer_name"));
String VILLAGE_1 = cursor.getString(cursor.getColumnIndexOrThrow("village"));
String TALUKA_1 = cursor.getString(cursor.getColumnIndexOrThrow("taluka"));
String DISTRICT_1 = cursor.getString(cursor.getColumnIndexOrThrow("district"));
String TAGGING_DATE_1 = cursor.getString(cursor.getColumnIndexOrThrow("tagging_date"));
int NEW_ANIMAL_ID = cursor.getInt(cursor.getColumnIndexOrThrow("new_animal_id"));
int FARMER_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("farmer_id"));
String TAG_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("tag_no"));
String ANIMAL_EAR_POSITION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_ear_position"));
String ANIMAL_SPECIES_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_species"));
String ANIMAL_BREED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_breed"));
String ANIMAL_BODY_COLOR_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_body_color"));
String ANIMAL_SHAPE_RIGHT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_right"));
String ANIMAL_SHAPE_LEFT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_left"));
String ANIMAL_SWITCH_OF_TAIL_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_sitch_of_tail"));
String AGE_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("age_years"));
String ANIMAL_OTHER_MARKS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_other_marks"));
String PRAG_STATUS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("prag_status"));
String NUMBER_OF_LACTATION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("number_of_lactation"));
String CURRENT_MILK_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("current_milk"));
String SUM_INSURED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("sum_insured"));
dataModel_1.setId(NEW_INSURANCE_ID_1);
dataModel_1.setINSURANCE_ID(INSURANCE_ID_1);
dataModel_1.setFarmer_insure_name(INSURED_NAME_1);
dataModel_1.setFarmer_bank_hypo(BANKHYPO_NAME_1);
dataModel_1.setFarmer_name(FARMER_NAME_1);
dataModel_1.setVillage(VILLAGE_1);
dataModel_1.setTaluka(TALUKA_1);
dataModel_1.setDistrict(DISTRICT_1);
dataModel_1.setTagging_date(TAGGING_DATE_1);
dataModel_1.setAnimal_id(NEW_ANIMAL_ID);
dataModel_1.setFarmer_id(FARMER_ID_1);
dataModel_1.setTag_no(TAG_COLUMN_1);
dataModel_1.setEar_position(ANIMAL_EAR_POSITION_COLUMN_1);
dataModel_1.setAnimal_species(ANIMAL_SPECIES_COLUMN_1);
dataModel_1.setAnimal_breed(ANIMAL_BREED_COLUMN_1);
dataModel_1.setBody_color(ANIMAL_BODY_COLOR_COLUMN_1);
dataModel_1.setShape_right(ANIMAL_SHAPE_RIGHT_COLUMN_1);
dataModel_1.setShape_left(ANIMAL_SHAPE_LEFT_COLUMN_1);
dataModel_1.setTail_switch(ANIMAL_SWITCH_OF_TAIL_COLUMN_1);
dataModel_1.setAge(AGE_COLUMN_1);
dataModel_1.setOther_marks(ANIMAL_OTHER_MARKS_COLUMN_1);
dataModel_1.setPrag_status(PRAG_STATUS_COLUMN_1);
dataModel_1.setLactations(NUMBER_OF_LACTATION_COLUMN_1);
dataModel_1.setMilk_qty(CURRENT_MILK_COLUMN_1);
dataModel_1.setSum_insured(SUM_INSURED_COLUMN_1);
dataModel_1.setAnimal_Tag_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tag_image"))));
dataModel_1.setAnimal_Head_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("head_image"))));
dataModel_1.setAnimal_Left_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("left_side_image"))));
dataModel_1.setAnimal_Right_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("right_side_image"))));
dataModel_1.setAnimal_Tail_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tail_image"))));
dataModel_1.setAnimal_Farmer_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("farmer_image"))));
stringBuffer.append(dataModel_1);
data.add(dataModel_1);
} while (cursor.moveToNext());
}
db.close();
return data;
}
This is a simple problem. You are only using
use for loop to iterate through all items like,
for(int i=0; i<datamodel.size(); i++){
doNormalPostOperation(i)
}
and in doNormalPostOperation method
public void doNormalPostOperation(int i) {
// PREVIOUS CODE
#Override
protected Map<String, String> getParams() {
params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
// REMAINING PARAMS WITH SAME datamodel.get(i) item
}
}
which is causing that issue and only sending first item. You will need to iterate through all items to generate parameters and send to server, or else you can combine them to one json array and modify the code server side.
First you collect the Data from sqltables
/* Collecting Information */
public Cursor getAllData() {
String selectQuery = "Select * from "+TABLE_MEMBER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
public JSONObject createJsonObject(){
Cursor cursor = getAllData();
JSONObject jobj ;
JSONArray arr = new JSONArray();
cursor.moveToFIrst();
while(cursor.moveToNext()) {
jobj = new JSONObject();
jboj.put("Id", cursor.getInt("Id"));
jboj.put("Name", cursor.getString("Name"));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
}
public void postJsonToServer(){
JSONObject js = createJsonObject();
String url = "YOUR -- Post Url";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
}
You can go through this:
Get all the data which you want to send, via select query and store this data in a array list.
Using GSON library you can convert that arraylist into json data
Now you have to create an API which receive that json data and parse it and insert every record to database.
On the app end you have to hit that API and pass json data to it.
this code was working fine earlier and database have tables made back in 2017, but somehow these are not working any more, unable to create tables in database and retrieve data from it. Android studio throws no error.Stuck with this from last 1 week.
Main activity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private EditText inputName, inputEmail, inputPassword;
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword;
private Button btnSignUp,btnLogout;
//private static final String SITE_URL="http://182.19.41.106/src/okcl/";
private static final String SITE_URL="http://www.wetswd.in/android-data";
private static final String CHECK_URL = SITE_URL+"sign-up.php";
private static final String REGISTER_URL = SITE_URL+"android-process.php";
private static final String UNREGISTER_URL = SITE_URL+"android-process_unregister.php";
private static final String LOGOUT_URL = SITE_URL+"sign-up.php;// logout.php";
private static final String VERSION="1.05";
private static final String pin = "1234";//SN:added for flexibility
private DBHelper mydb ;
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mydb = new DBHelper(this);
//Add from XML Later
//MyReceiver reMyreceive = new MyReceiver();
//IntentFilter filter = new IntentFilter("BROADCAST_ACTION");
//registerReceiver(reMyreceive, filter);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password);
inputName = (EditText) findViewById(R.id.input_name);
inputPassword = (EditText) findViewById(R.id.input_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
Boolean isServiceRunning=isMyServiceRunning(MyService.class);
if(isServiceRunning)
btnSignUp.setBackgroundColor(Color.RED);
else btnSignUp.setBackgroundColor(Color.BLUE);
btnLogout = (Button) findViewById(R.id.btn_logout);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword));
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm(view);
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logOut();
if (!validateName()) {
return;
}
if (!validatePassword()) {
return;
}
String macAdd = getMAC();
String dateTime = getDateTime();
String status = "out_"+inputName.getText().toString().trim();
if (isNetworkAvailable(getApplicationContext())) {
mydb.insertContact(macAdd , dateTime , "0", "0" , status , "N",pin);//inputName.getText().toString().trim(),
logOut(macAdd, inputName.getText().toString().trim(), inputPassword.getText().toString().trim(),pin);
//stopService(); is called inside logout
} else {
mydb.insertContact(macAdd , dateTime , "0", "0" , status.toUpperCase(), "N",pin);//,inputName.getText().toString().trim(),"9999"
btnLogout.setText(R.string.btn_LogOut);// "LOGOUT");
stopService(); //without Checking
Toast.makeText(getApplicationContext(), "LOG Stopped", Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Validating form
*/
private void submitForm(View view) {
if (!validateName()) {
return;
}
if (!validatePassword()) {
return;
}
GPS_Slim gps = new GPS_Slim(MainActivity.this);
//gps.setUsrId(inputName.getText().toString().trim());
//gps.setPin(pin);
if (gps.canGetLocation()) {
double latitude = 20.37;//Near Park;
double longitude = 85.68;//Near Park
double acc=9999.0;//gps.getAccuracy();
String macAdd = getMAC();
String dateTime = getDateTime();
String status = "in_"+inputName.getText().toString().trim();
if(isNetworkAvailable(getApplicationContext())){
mydb.insertContact(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude) , status , "N",pin);//,,String.valueOf(acc)
CheckUser(macAdd ,inputName.getText().toString().trim(),inputPassword.getText().toString().trim(),pin);
}else {
mydb.insertContact(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude) , status.toUpperCase(), "N",pin);//,inputName.getText().toString().trim(),String.valueOf(acc)
Toast.makeText(getApplicationContext(), "Stored Internally", Toast.LENGTH_LONG).show();
btnLogout.setText(R.string.btn_LogOut+" #"+inputName.getText().toString().trim());
startService(); //without Checking//SN:Can I pass Pin here
Toast.makeText(getApplicationContext(), "LOG Started", Toast.LENGTH_LONG).show();
}
} else {
gps.showSettingsAlert();
}
//gps.locationManager.removeUpdates();//SN:Check if used?? GPS object is local here
//gps = null;
}
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
private boolean validatePassword() {
if (inputPassword.getText().toString().trim().isEmpty()) {
inputLayoutPassword.setError(getString(R.string.err_msg_password));
requestFocus(inputPassword);
return false;
} else {
inputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name: validateName(); break;
case R.id.input_password: validatePassword(); break;
}
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private String getMAC(){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
return wInfo.getMacAddress();
}
private String getDateTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private void register(String mac, String dateT, String lat, String lon,String pin,String usr,String ver) {
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("datetime",params[1]);
data.put("lat",params[2]);
data.put("long",params[3]);
data.put("pin",params[4]);//SN:added for Flexibility
data.put("usr",params[5]);//SN:added for Flexibility
data.put("ver",params[6]);//SN:added for Flexibility
return ruc.sendPostRequest(REGISTER_URL,data);
}
}
RegisterUser ru = new RegisterUser();
ru.execute(mac,dateT,lat,lon,pin,usr,ver);
}
private void CheckUser(String mac_id,final String user_id,String password,final String pin) {
class CheckUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Received:"+s,Toast.LENGTH_SHORT).show();
if(s.equalsIgnoreCase("Unauthorised User")){
Toast.makeText(getApplicationContext(),"Login Fail",Toast.LENGTH_LONG).show();
}else{ //Sucessfully Login
double latitude = 20.37;//Near Park;
double longitude = 85.68;//Near Park
String macAdd = getMAC();
String dateTime = getDateTime();
register(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude),pin,user_id,VERSION);
Toast.makeText(getApplicationContext(), "Login Pass", Toast.LENGTH_LONG).show();
startService();
Toast.makeText(getApplicationContext(), "LOG Started", Toast.LENGTH_LONG).show();
btnLogout.setText(btnLogout.getText().toString()+" *"+inputName.getText().toString().trim());
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("userid",params[1]);
data.put("password",params[2]);
data.put("pin",params[3]);
return ruc.sendPostRequest(CHECK_URL,data);
}
}
CheckUser ru = new CheckUser();
ru.execute(mac_id,user_id,password,pin);
}
private void logOut(String mac_id,final String user_id,String password,final String pin) {
class LogOUt extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Received:"+s,Toast.LENGTH_SHORT).show();
if(s.equalsIgnoreCase("Unauthorised User")){
Toast.makeText(getApplicationContext(),"Login Fail",Toast.LENGTH_LONG).show();
}else{ //Sucessfully Login
double latitude = 20.37;//Near Park;20.37 85.68
double longitude = 85.68;//Near Park
String macAdd = getMAC();
String dateTime = getDateTime();
register(macAdd , dateTime ,String.valueOf(latitude), String.valueOf(longitude),pin,user_id,VERSION);
Toast.makeText(getApplicationContext(), "Login Pass", Toast.LENGTH_LONG).show();
//Set Active=0 in android_data for macAdd
stopService();
HashMap<String, String> data = new HashMap<>();
data.put("macid",macAdd);
data.put("pin",pin);//SN:added for Flexibility
String result = ruc.sendPostRequest(UNREGISTER_URL,data);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "LOG Stopped", Toast.LENGTH_LONG).show();//20170821:Sn Testing
btnLogout.setText(R.string.btn_LogOut);//"LOGOUT");
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("userid",params[1]);
data.put("password",params[2]);
data.put("pin",params[3]);
return ruc.sendPostRequest(LOGOUT_URL,data);
}
}
LogOUt ru = new LogOUt();
ru.execute(mac_id,user_id, password,pin);
}
private void doUpdate(String s) {
}
// Method to start the service
public void startService() {Intent i=new Intent(getBaseContext(), MyService.class);
i.putExtra("user",inputName.getText().toString().trim());
i.putExtra("SITE_URL",SITE_URL);
i.putExtra("pin",pin);
i.putExtra("mac",getMAC());
i.putExtra("ver",VERSION);
i.putExtra("REGISTER_URL",REGISTER_URL);
startService(i);
Intent iActivity=new Intent(getBaseContext(), logOut.class);
iActivity.putExtra("user",inputName.getText().toString().trim());
startActivity(iActivity);
}
// Method to start the service
public void stopService() {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.db";
public static final String RECORD_TABLE_NAME = "Record";
public static final String RECORD_COLUMN_ID = "id";
public static final String RECORD_COLUMN_MACID = "macid";
public static final String RECORD_COLUMN_DATETIME = "datetime";
public static final String RECORD_COLUMN_LAT = "lat";
public static final String RECORD_COLUMN_LONG = "long";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Boolean tableExist=isTableExists("Record",false,db);//SN:Not Tested Code Added from https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database
if(!tableExist) {
db.execSQL("create table Record " +
"(id integer primary key, macid text,datetime text,lat text, long text , status text , uploadstatus text, pin text)");
}
//TimeLog Added by SN to KeepTime of Last Update
Boolean timeLogExist=isTableExists("timeLog",false,db);//SN:Not Tested Code Added from https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database
if(!timeLogExist) {
db.execSQL("create table timeLog " + "(id integer primary key, macid text,datetime Long,comment text)");//??SN: Long
//insertTimeLog(0L,"MSG_UPDATE","macid");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS Record");
//db.execSQL("DROP TABLE IF EXISTS timeLog");
onCreate(db);
}
public boolean insertContact (String macid, String datetime, String lat, String longi , String status, String uploadstatus,String pin) { //,String usr,String acc- removed
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//macId,dateTime, String.valueOf(getLatitude()),String.valueOf(getLongitude()),"way","N",pin,usrId,accText
contentValues.put("macid", macid);
contentValues.put("datetime", datetime);
contentValues.put("lat", lat);
contentValues.put("long", longi);
contentValues.put("status", status);
contentValues.put("uploadstatus", uploadstatus);
contentValues.put("pin", pin);
db.insert("Record", null, contentValues);
return true;
}
public boolean updateContactNotUsed (Integer id, String macid, String datetime, String lat, String longi, String status, String uploadstatus) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("macid", macid);
contentValues.put("datetime", datetime);
contentValues.put("lat", lat);
contentValues.put("long", longi);
contentValues.put("status", status);
contentValues.put("uploadstatus", uploadstatus);
db.update("Record", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery( "select * from Record where id="+id+"", null );
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
return (int) DatabaseUtils.queryNumEntries(db, RECORD_TABLE_NAME);
}
public boolean updateTimeLog ( Long datetime, String key) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("datetime", datetime);
db.update("timeLog", contentValues, "comment = ? ", new String[] { key } );
return true;
}
public boolean insertTimeLog ( Long datetime, String key,String macid) { //,String usr,String acc- removed
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("datetime", datetime);
contentValues.put("comment", key);
contentValues.put("macid", macid);
db.insert("timeLog", null, contentValues);
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("Record", "id = ? ", new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from Record", null );
res.moveToFirst();
while(!res.isAfterLast()){
array_list.add(res.getString(res.getColumnIndex(RECORD_TABLE_NAME)));
res.moveToNext();
}
res.close();
return array_list;
}
public boolean isTableExists(String tableName, boolean openDb,SQLiteDatabase mDatabase) {
if(openDb) {
if(mDatabase == null || !mDatabase.isOpen()) {
mDatabase = this.getReadableDatabase();
}
if(!mDatabase.isReadOnly()) {
mDatabase.close();
mDatabase = this.getReadableDatabase();
}
}
Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
}
logcat-https://drive.google.com/file/d/1J1vhdRpP0GOQaRoCycHXWkXi_HiKPxxE/view?usp=sharing
Try upgrading your database version to 2, as your are adding new tables to your database you need to upgrade database version.
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 2);
}
I am developing an android app, where I am using Relam as local Database. I have rest api one for all the user information and other is for news information. I have two buttons. one for showing the user information and other is for showing the news information. Now, with my code what is done, after login, I need to click the button at first for user information and news information accordingly and then I can see those images and news. but if I connection off, just after login, the data is not showing in the view. I am explaining my code in detail.Also I am having problem in image loading. How can I Make the funtionality so that user can get all the information just after login.I am reallly sorry for such a long code. It would be really helpful for me if someone tell me how can I modify my code to store all data in background thread, so that user get all information just after login.
The part of the login page where I want to start
private void loginUser(final String mEmail, final String mPassword) {
final GlobalClass globalClass = new GlobalClass();
globalClass.setEmail_info( mEmail );
setFilePath();
RequestQueue queue = Volley.newRequestQueue( LoginPage.this );
StringRequest strReq = new StringRequest( Request.Method.POST,
LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d( TAG, "Register Response: " + response.toString() );
//parse your response here
if (response.contains( "overview" )) {
showProgress( true );
globalClass.setImage_urlpath( Constants.HTTP.PHOTO_URL + mEmail);
String str = globalClass.readDatafromStorage();
Log.d("----After Login---",str);
if ( !str.contains("ACTIVATE") ) {
Log.d( "----After Login---", "After Login" );
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KEY_EMAIL, mEmail);
editor.putString(KEY_PASSWORD, mPassword);
editor.commit();
showProgress(false);
Intent loginIntent = new Intent(LoginPage.this, MainOptionPage.class);
loginIntent.putExtra(KEY_EMAIL, mEmail);
startActivity(loginIntent);
} else {
userEmail.setError(getString(R.string.error_incorrect_login));
userEmail.requestFocus();
}
}
}, new Response.ErrorListener() {
#Override
....
Here is my code for User Page
public class MyColleaguesPage extends AppCompatActivity implements ColleagueController.UserCallbackListener {
private List<MyColleagueModel> myColleagueList = new ArrayList<>();
private Realm colleagueRealm;
private RealmResults<MyColleagueModel> colleagueResult;
private List<MyColleagueModel> filteredModelList;
private RealmChangeListener realmListener;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
configViews();
}
private void configViews() {
recyclerView = this.findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
colleagueRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results = colleagueRealm.where(MyColleagueModel.class).findAll();
for (int i = 0; i < results.size(); i++) {
myColleagueList.add(results.get(i));
}
adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
//adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
Log.d( "adapter value is"+"", String.valueOf( adapter ) );
recyclerView.setAdapter(adapter);
}
//successful
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(ColleagueModel colleague) {
//adapter.addColleague(colleague);
}
#Override
public void onFetchProgress(List<ColleagueModel> colleagueList) {
}
#Override
public void onFetchComplete() {
}
#Override
public void onFetchFailed() {
}
}
Here is my controller class for my colleague page
public class ColleagueController {
private static final String TAG = ColleagueController.class.getSimpleName();
private UserCallbackListener mListener;
private ColleagueResApiManager mApiManager;
Realm myColleague_realm;
public ColleagueController() {
mApiManager = new ColleagueResApiManager();
}
public void startFetching(){
myColleague_realm = Realm.getDefaultInstance();
mApiManager.getColleagueApi().getColleague(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Log.d("-----Start Fetching---", object.optString( "name" ));
myColleague_realm.beginTransaction();
MyColleagueModel mycolleague = myColleague_realm.createObject( MyColleagueModel.class );
mycolleague.setName( object.optString( "name" ) );
.... data ) );
myColleague_realm.commitTransaction();
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
// mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
if (mListener != null) {
mListener.onFetchComplete();
}
}
});
}
public interface UserCallbackListener{
void onFetchComplete();
void onFetchFailed();
}
}
In the same way I have other page news option page where I am shoing the news data. Here is my news page.
public class NewsPage extends AppCompatActivity{
private RecyclerView recyclerView;
private NewsAdapter adapter;
private Realm newsRealm;
private List<NewsRealmModel> mNewsList;
private List<NewsRealmModel> filteredModelList;
private NewsController mController;
Constant constant;
SharedPreferences app_preferences;
int appTheme;
int themeColor;
int appColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.news_page_layout);
configViews();
}
private void configViews() {
recyclerView = this.findViewById(R.id.news_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(NewsPage.this));
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
Realm newsRealm = Realm.getDefaultInstance();
RealmResults<NewsRealmModel> temp = newsRealm.where(NewsRealmModel.class).findAll();
mNewsList = new ArrayList<>();
for (int i = 0; i < temp.size(); i++) {
mNewsList.add(temp.get(i));
}
adapter = new NewsAdapter(mNewsList,getApplicationContext());
Log.d( "adapter value is"+"", String.valueOf( adapter ) );
recyclerView.setAdapter(adapter);
}
}
And the new Controller Class
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
Realm myNews_realm;
ArrayList<String> title_list = new ArrayList<>();
GlobalClass globalClass = new GlobalClass();
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching() {
myNews_realm = Realm.getDefaultInstance();
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
Log.d("-----Start Fetching---", jsonObject.optString("title"));
if (!myNews_realm.isInTransaction()) {
myNews_realm.beginTransaction();
NewsRealmModel news = new NewsRealmModel();
....... data
}
myNews_realm.copyToRealm(news);
myNews_realm.commitTransaction();
mListener.onFetchProgressNews(news);
} else {
myNews_realm.commitTransaction();
}
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener {
void onFetchProgressNews(NewsRealmModel news);
void onFetchComplete();
void onFetchFailed();
}
}
To do your database processing on a background thread using Volley, you need to extend Request<T> and do the Realm write in parseNetworkResponse method.
public class RealmGsonObjectRequest<T, M extends RealmModel> extends Response<Void> {
...
#Override
protected Response<Void> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
T data = gson.fromJson(json, clazz);
// write the downloaded data into the Realm on bg thread
try(Realm r = Realm.getDefaultInstance()) {
M model = mapper.toModel(data);
r.executeTransaction((realm) -> {
realm.insertOrUpdate(model);
});
}
return Response.success(null,
HttpHeaderParser.parseCacheHeaders(response)
);
} // handle errors
}
You might need a RealmGsonListRequest as well.
public class RealmGsonListRequest<T, M extends RealmModel> extends Response<Void> {
...
#Override
protected Response<Void> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
List<T> data = gson.fromJson(json, new TypeToken<ArrayList<T>>() {}.getType());
// write the downloaded data into the Realm on bg thread
try(Realm r = Realm.getDefaultInstance()) {
M model = mapper.toModel(data);
r.executeTransaction((realm) -> {
realm.insertOrUpdate(model);
});
}
return Response.success(null,
HttpHeaderParser.parseCacheHeaders(response)
);
} // handle errors
}
For more information, refer to the official Volley tutorial on how to create a custom Volley request type.
How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.
I want to implement Google Forms in my application. I have to make simple survey type forms as like Google Forms, I searching it from two days but I didn't get any specific document for Google Forms implementing in Android Application.
public class Fragment_Register extends Fragment {
View mainView;
public static final MediaType FORM_DATA_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public static final String URL_FORM = "https://docs.google.com/forms/d/e/1FAIpQLSd7TT0S2pMwvRghAxAwDrJ42sWvI7uhqQBdl1WIyKRXjyWRWQ/formResponse";
public static final String NAME_KEY = "entry.2005620554";
public static final String EMAIL_KEY = "entry.1045781291";
public static final String NUMBER_KEY = "entry.1166974658";
public static final String COLLEGE_KEY="entry.75064397";
public static final String CHECK_KEY="entry.839337160";
public String Categories[]={"Category 1","Category 2","Category 3","Category 4"},category;
public String Events[]={"Event 1","Event 2","Event 3","Event 4"},event;
public String Events2[]={"Event2 1","Event2 2","Event2 3","Event2 4"};
private Context context;
private EditText editName;
private EditText editEmail;
private EditText editPhoneNumber;
private EditText editCollege;
private TextView select;
private CheckBox checkBox1,checkBox2;
private Spinner spinner;
private MultiSelectionSpinner spinner2;
private RelativeLayout layout;
ArrayAdapter<String> adapterCategoryCategory;
ArrayAdapter<String> adapterEventCategory;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView=inflater.inflate(R.layout.fragment_fragment__register,container,false);
mainView.setTag("FOUR");
context = mainView.getContext();
Button SubmitButton = (Button)mainView. findViewById(R.id.button_register);
editName = (EditText)mainView. findViewById(R.id.editText_register_name);
editEmail = (EditText)mainView. findViewById(R.id.editText_register_email);
editPhoneNumber = (EditText)mainView. findViewById(R.id.editText_register_phone);
editCollege = (EditText)mainView. findViewById(R.id.editText_register_college);
spinner=(Spinner)mainView.findViewById(R.id.spinner);
spinner2=(MultiSelectionSpinner)mainView.findViewById(R.id.multiSpinner);
select=(TextView)mainView.findViewById(R.id.textViewSelect);
adapterCategoryCategory =new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, Categories);
adapterCategoryCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterCategoryCategory);
spinner.setPrompt("Select Category");
adapterEventCategory =new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, Events);
adapterEventCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setItems(Events);
spinner2.setPrompt("Select Event");
spinner2.setSelection(0);
SubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String st=spinner2.getSelectedItemsAsString();
Toast.makeText(context, st, Toast.LENGTH_SHORT).show();
Log.e("Selected",st);
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
category=adapterView.getItemAtPosition(i).toString();
if(i==0)
{
spinner2.setItems(Events);
}
else if (i==1)
{
spinner2.setItems(Events2);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
event=adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return mainView;
}
class PostDataTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.show();
}
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String name = contactData[1];
String email = contactData[2];
String number = contactData[3];
String college = contactData[4];
String postBody = "";
try {
postBody = NAME_KEY + "=" + URLEncoder.encode(name, "UTF-8") +
"&" + EMAIL_KEY + "=" + URLEncoder.encode(email, "UTF-8") +
"&" + NUMBER_KEY + "=" + URLEncoder.encode(number, "UTF-8")+
"&" + COLLEGE_KEY + "=" + URLEncoder.encode(college, "UTF-8");
} catch (UnsupportedEncodingException ex) {
result = false;
}
try {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
} catch (IOException exception) {
result = false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result) {
progress.cancel();
final AlertDialog.Builder alert=new AlertDialog.Builder(context);
alert.setMessage(result ? "Successfully Registered!" : "There was some error in sending message. Please try again after some time.").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
editName.setText("");
editCollege.setText("");
editEmail.setText("");
editPhoneNumber.setText("");
}
});
AlertDialog alertDialog=alert.create();
alertDialog.show();
}
}
boolean validData()
{ String userName=editName.getText().toString();
String userNumber = editPhoneNumber.getText().toString();
String userEmail = editEmail.getText().toString();
String userCollege=editCollege.getText().toString();
if (userName.length()<3)
{
Toast.makeText(context, "Enter a Valid Name", Toast.LENGTH_SHORT).show();
return false;
}
if (userNumber.length()!=10||userNumber.startsWith("0")||userNumber.startsWith("1")||userNumber.startsWith("2")||userNumber.startsWith("3")||userNumber.startsWith("4")||userNumber.startsWith("5")||userNumber.startsWith("6"))
{
Toast.makeText(context, "Enter a Valid Number", Toast.LENGTH_SHORT).show();
return false;
}
if (userEmail.length()<3)
{
Toast.makeText(context, "Enter a Valid Email Address", Toast.LENGTH_SHORT).show();
return false;
}
if (userCollege.length()<3)
{
Toast.makeText(context, "Enter a Valid College Name", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
}
You can use a web view to render your google form within the application.
If for some reason you prefer not to use a web view, it is also possible to use the 'keys' in a google form(obtained via 'inspect element') to integrate the same with your application. Here is a link detailing the steps.
You can use the following in your onCreate():
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading...");
queue = Volley.newRequestQueue(getApplicationContext());
submit.setOnClickListener(view -> {
postData(edit_name.getText().toString().trim(), edit_email.getText().toString().trim(),
edit_number.getText().toString().trim(), edit_remarks.getText().toString().trim());l
});
Also create a function in the activity as follows and in my Google Forms I have 4 entries to make which are name, phone, email and remark:
public void postData(final String name, final String email, final String phone, final String remark) {
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, Constants.url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("TAG", "Response: " + response);
if (response.length() > 0) {
Snackbar.make(btn_submit, "Successfully Posted", Snackbar.LENGTH_LONG).show();
finish();
} else {
Snackbar.make(btn_submit, "Try Again", Snackbar.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Snackbar.make(btn_submit, "Error while Posting Data", Snackbar.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(Constants.nameField, name);
params.put(Constants.emailField, email);
params.put(Constants.phoneField,"+91"+phone);
params.put(Constants.remarkField, remark);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
Create a Java class Constants where you enter the url and id of the entries in forms:
public class Constants {
// Google Forms URL .. replace with yours
public static final String url = "https://docs.google.com/forms/d/e/1FAIpQLSf65J3RmZS6QBg_TrsZZFx9s0l6109Q4E6PvUjuZ9go6D9l2g/formResponse";
// Google Form's Column ID
public static final String nameField = "entry.2006520554";
public static final String phoneField = "entry.1196974658";
public static final String emailField = "entry.1054781291";
public static final String remarkField = "entry.839339060"; }
Entry ids can be found by inspecting your Google Forms. For more details refer to the this link.