How to Send All Data From SQLite to Server in Android - android

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.

Related

android recyclerview load more item upon scrolling using volley

Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.
Here is my code.
private void populateRecycleView() {
if (Utility.checkNetworkConnection(this)) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Searching...");
progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
String firstName = jsonObject.getString("fName");
String secondName = jsonObject.getString("sName");
String email = jsonObject.getString("emailid");
String password = jsonObject.getString("pass");
String mobile = jsonObject.getString("mobile");
String bloodRt = jsonObject.getString("blood");
String age = jsonObject.getString("age");
String gender = jsonObject.getString("gender");
String country = jsonObject.getString("country");
String location = jsonObject.getString("location");
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String profilePicFIleName = jsonObject.getString("picname");
String profilePicURL = jsonObject.getString("pic");
Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
country, location, latitude, longitude, profilePicFIleName, profilePicURL);
donorsList.add(donor);
count++;
}
donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(donorsAdapter);
donorsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", bloodGroup);
return params;
}
};
NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
} else {
Utility.checkNetworkConnectionFound(this);
}
}
And this is my RecyclerView adapter...
public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {
private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;
public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
this.context = context;
this.donorList = donorList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
final Donor donor = donorList.get(position);
String displayName = donor.getFirstName() + " " + donor.getSecondName();
holder.tvDisplayName.setText(displayName);
holder.tvEmailID.setText(donor.getEmail());
String userProfileURL = donor.getProfilePicURL();
if (!userProfileURL.equals("")) {
Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
into(holder.ivProfilePic);
} else {
holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
}
bloodGroup = donor.getBloodGroup();
if (bloodGroup.equals("A+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
else if (bloodGroup.equals("A-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
else if (bloodGroup.equals("B+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
else if (bloodGroup.equals("B-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
else if (bloodGroup.equals("O+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
else if (bloodGroup.equals("O-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
else if (bloodGroup.equals("AB+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
else if (bloodGroup.equals("AB-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);
if(Utility.isNetworkEnabled){
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayDonorDetails.class);
intent.putExtra("donor", donor);
context.startActivity(intent);
}
});
}else {
Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
if(donorList != null){
return donorList.size();
}else {
return 0;
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
TextView tvDisplayName;
TextView tvEmailID;
ConstraintLayout constraintLayout;
public CustomViewHolder(View itemView) {
super(itemView);
ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
}
}
}
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.
Hope it helps.
EDIT
First create an emptyList:
List<Donor> subElements = new ArrayList<>();
and pass it to your adapter:
donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
Now you can create a method like this (you can call in onClick event for example):
private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;
public void showMoreDonors(){
if(donarsList.size() > Last_postion+50){
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));
for(Donor a : tempList){
subElements.add(a);
}
Last_postion += DONORS_NUM_TOSHOW;
donorsAdapter.notifyDataSetChanged();
}else{
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
for(Donor a : tempList){
subElements.add(a);
}
donorsAdapter.notifyDataSetChanged();
}
}
Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.
Finally, I sort this out. I have got an awesome tutorial from this blog.
http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.
I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.

ArrayList is displaying null in method Te()

public class MainActivity extends AppCompatActivity {
// Button senddata;
//private final String url = "http://19.168.1.58:9090/data/db";
public static final String KEY_EMAIL = "email";
EditText email1;
String emailString;
String _id, _name, _pass, _email;
TextView displayjsonText;
DataRecieveJson dr;
ArrayList<agentPojo> list;
agentPojo agentdetails;
synck sy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1 = (EditText) findViewById(R.id.email);
displayjsonText = (TextView) findViewById(R.id.displayView);
}
public void checkdata(View view){
emailString= email1.getText().toString();
dr = new DataRecieveJson(this, emailString);
dr.RecieveData();
dr.te();
}
}
public class DataRecieveJson {
Context mcontext;
String jresponse;
public String _id = "";
String _name;
String _pass = "" ;
String _email = "";
String mail;
JSONObject obj;
ArrayList<agentPojo> list;
// ArrayList<agentPojo> nlist;
agentPojo agent;
public DataRecieveJson(Context mcontext,String mail) {
this.mcontext = mcontext;
this.mail = mail;
}
public void RecieveData() {
RequestQueue queue = Volley.newRequestQueue(mcontext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url.jurl + mail, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parsejson(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse: ", error.toString());
Toast.makeText(mcontext, error.toString(), Toast.LENGTH_LONG).show();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
queue.add(jsonObjectRequest);
}
public void parsejson(JSONObject response) {
list= new ArrayList<agentPojo>();
agent = new agentPojo();
try {
JSONArray ag1 = response.getJSONArray("agentD");
for (int i = 0; i < ag1.length(); i++) {
JSONObject ag = ag1.getJSONObject(i);
// _id = ag.getString("id");
// _name = ag.getString("name");
// _pass = ag.getString("password");
// _email = ag.getString("email");
agent.setId(ag.getString("id"));
agent.setName(ag.getString("name"));
agent.setPass(ag.getString("password"));
agent.setEmail(ag.getString("email"));
list.add(agent);
Log.d("parsejson: ", String.valueOf(list));
// Log.d("parsejson: ", "Hello");
agentPojo po;
String id = null, email = null;
for (int j = 0; j < list.size() ; j++) {
po = list.get(j);
id = po.getId();
email = po.getEmail();
}
Log.d("RecieveDataInside: ", id + "," + email);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Pj:Id ", String.valueOf(list));
}
public void te() {
Log.d("test:Id ", String.valueOf(list));
}
}
Logs:
09-17 07:24:52.689 21681-21681/com.example.pawar.sendtoservlet D/test:Id: null
09-17 07:24:53.061 21681-21681/com.example.pawar.sendtoservlet D/parsejson:: [com.example.pawar.sendtoservlet.agentPojo#536b7f1c]
09-17 07:24:53.061 21681-21681/com.example.pawar.sendtoservlet D/RecieveDataInside:: 1,ram21#gmail.com
09-17 07:24:53.061 21681-21681/com.example.pawar.sendtoservlet D/Pj:Id: [com.example.pawar.sendtoservlet.agentPojo#536b7f1c]
ArrayList is displaying null in method Te().
The ArrayList hasn't been initialized up to the point where you have your log message, which is why the ArrayList is null.
After tracking through your methods, I can see that you only initialize the list in parsejson(), and parsejson() is only called in the onResponse() from your new JsonObjectRequest() in ReceiveData().
This must mean that onResponse() isn't being called, which is why parsejson() isn't being run and list is null.
I would advise you to do what a comment mentioned, which is to use more log statements to help you investigate why your onResponse() isn't being invoked.
Try initializing globally
ArrayList list = new ArrayList();

How to manage position in recycler view when scroll after notifydatasetchanged

Here is my code, I have to call method getServerResponse() for first time to get store in arraylist and when I scrolls down I have to call method getServerResponseScroll(). I got result and notify adapter but after scrolling down and up data changes position or may be not visible or get changed. I had created custom adapter for chat. Please help me how to sort out this kind of problem.
public class ChatDetailActivity extends AppCompatActivity {
String macAddress;
RecyclerView recyclerView;
Activity context;
ChatAdapter adapter;
EditText etText;
DatabaseAdapter db;
NetClient nc;
EditText edtSend;
Button btnSend;
DataPref mDataPref;
static int page = 0;
SwipeRefreshLayout mSwipeRefreshLayout;
JSONArray chatDetailListJsonArray;
String toId, channelId, toProfilePic, deviceToken, deviceOsType;
static ArrayList<ChatDetailModel> chatDetailModels = new ArrayList<ChatDetailModel>();
// User mchatUSer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_detail);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
edtSend = (EditText) findViewById(R.id.edtSend);
btnSend = (Button) findViewById(R.id.btnSend);
db = new DatabaseAdapter(this);
mDataPref = DataPref.getInstance(this);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
macAddress = wInfo.getMacAddress();
etText = (EditText) findViewById(R.id.etText);
toId = getIntent().getStringExtra("toId");
channelId = getIntent().getStringExtra("channelId");
toProfilePic = getIntent().getStringExtra("toProfilePic");
deviceToken = getIntent().getStringExtra("deviceToken");
deviceOsType = getIntent().getStringExtra("deviceOsType");
getServerResponse(this);
connectionForSend();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
void getServerResponse(final Context context){
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
/*
if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
if(page==0) {
GetChat.getInstance(context).deleteAllTableData("tbl_chat_detail", channelId);
}
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
} catch (JSONException e) {
e.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
// DatabaseAdapter.deleteDatabase(context);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page",page+"");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void getServerResponseScroll(final Context context) {
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
// chatDetailModels.clear();
ArrayList<ChatDetailModel> chatDetailModels1 = new ArrayList<ChatDetailModel>();
chatDetailModels1 = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
chatDetailModels.clear();
chatDetailModels.addAll(chatDetailModels1);
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
// DatabaseAdapter.deleteDatabase(context);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page", page + "");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void implemantation() {
RecyclerView.LayoutManager manager = new LinearLayoutManager(this.getApplicationContext());
recyclerView.setLayoutManager(manager);
adapter = new ChatAdapter(this.getApplicationContext(), chatDetailModels);
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(chatDetailModels.size() - 1);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(ChatDetailActivity.this, ProfilesDetailActivity.class);
// i.putExtra("profileId",ChatlistModel.get(position).getId());
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
page++;
getServerResponseScroll(ChatDetailActivity.this);
}
});
}
// Adapter for chat
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private ArrayList<ChatDetailModel> chatDetailModels;
private Context context;
public ChatAdapter(Context context, ArrayList<ChatDetailModel> chatDetailModels) {
this.context = context;
this.chatDetailModels = chatDetailModels;
}
#Override
public ChatAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_lsit_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (chatDetailModels.get(position).getFrom_username().equalsIgnoreCase(mDataPref.getUsername())) {
viewHolder.messageTextRight.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatLeftLayout.setVisibility(View.GONE);
if (mDataPref.getProfilePicFullUrl().equals("null") || mDataPref.getProfilePicFullUrl().equals("")) {
viewHolder.fromImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(mDataPref.getProfilePicFullUrl()).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.fromImageView);
}
} else {
viewHolder.messageTextLeft.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatRightLayout.setVisibility(View.GONE);
if (toProfilePic.equals("null") || toProfilePic.equals("")) {
viewHolder.toImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(toProfilePic).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.toImageView);
}
}
}
#Override
public int getItemCount() {
return chatDetailModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout chatLeftLayout;
private ImageView toImageView;
private TextView messageTextLeft;
private LinearLayout chatRightLayout;
private TextView messageTextRight;
private ImageView fromImageView;
public ViewHolder(View view) {
super(view);
chatLeftLayout = (LinearLayout) view.findViewById(R.id.chatLeftLayout);
toImageView = (ImageView) view.findViewById(R.id.toImageView);
messageTextLeft = (TextView) view.findViewById(R.id.message_text_left);
chatRightLayout = (LinearLayout) view.findViewById(R.id.chatRightLayout);
messageTextRight = (TextView) view.findViewById(R.id.message_text_right);
fromImageView = (ImageView) view.findViewById(R.id.fromImageView);
}
}
}
}
From onSaveInstanceState documentation:
Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.
* RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.
To get current state of recyclerview:
private Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
to restore saved instance:
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

How to load GridView images with AsyncTask?

I have, below the following fragment that populates a gridview with Bitmaps from URLs. The problem is that I know it's very 'heavy' work and done on the UI Thread so it's slowing the fragment down when loading the grid.
I've read that an AsyncTask is needed to carry out the 'heavy' work in the background but I can't find anything that seems to fit with what I want.
public class HomeFragment extends Fragment {
protected static final String TAG = null;
public HomeFragment(){}
GridView gridView;
private GridViewAdapter gridAdapter;
private SQLiteHandler db;
private SwipeRefreshLayout swipeLayout;
private ProgressDialog pDialog;
GPSTracker gps;
String uid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new SQLiteHandler(getActivity());
gridAdapter = new GridViewAdapter(getActivity(), R.layout.grid_item_layout, getData());
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(true);
uid="1";
String email = db.getFromTable(getActivity(), "email", SQLiteHandler.TABLE_LOGIN, "WHERE _id="+uid);
String from_age = db.getFromTable(getActivity(), "from_age", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String to_age = db.getFromTable(getActivity(), "to_age", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String distance = db.getFromTable(getActivity(), "distance", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String unit = db.getFromTable(getActivity(), "unit", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String men = db.getFromTable(getActivity(), "men", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String women = db.getFromTable(getActivity(), "women", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
fetchUsers(email, from_age, to_age, distance, unit, men, women);
final View rootView = inflater.inflate(R.layout.fragment_home, container, false);
//getActivity().getActionBar().setTitle(R.string.home);
gridView = (GridView) rootView.findViewById(R.id.gridView);
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
ImageView imageView = (ImageView) v.findViewById(R.id.image);
//Create intent
Intent intent = new Intent(getActivity(), DetailsActivity.class);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("uid", item.getUid());
startActivity(intent);
}
});
swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
//my update process
Fragment currentFragment = getFragmentManager().findFragmentByTag("0");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
});
return rootView;
}
// Prepare some dummy data for gridview
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
Cursor cursor = db.getAllRows("*", SQLiteHandler.TABLE_USERS, "");
//Query local DB to initialize settings screen
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
String uid = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_UID));
String name = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_NAME));
String dob = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_DOB));
//String gender = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_GENDER));
String photourl = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_PHOTOURL));
//String distance = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_DISTANCE));
String[] birthdayArr = dob.split("-");
int age = getAge(Integer.parseInt(birthdayArr[0]), Integer.parseInt(birthdayArr[1]), Integer.parseInt(birthdayArr[2]));
Bitmap bitmap = getBitmapFromURL(photourl);
imageItems.add(new ImageItem(bitmap, name+" - " + age, uid));
}
return imageItems;
}
public static Bitmap getBitmapFromURL(String src) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
public int getAge(int year, int month, int day) {
//int nowMonth = now.getMonth()+1;
int nowMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
//int nowYear = now.getYear()+1900;
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
int result = nowYear - year;
if (month > nowMonth) {
result--;
}
else if (month == nowMonth) {
int nowDay = Calendar.getInstance().get(Calendar.DATE);
if (day > nowDay) {
result--;
}
}
return result;
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
Log.i("hideDialog", "called");
if (pDialog.isShowing())
pDialog.dismiss();
}
public void fetchUsers(final String email, final String agefrom, final String ageto, final String distance, final String distanceUnit, final String interested_men, final String interested_wmen){
// Tag used to cancel the request
gps = new GPSTracker(getActivity());
String tag_string_req = "req_login";
pDialog.setMessage("Finding users ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Fetch Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("success");
JSONArray users = jObj.getJSONArray("users");
// Check for error node in json
if (success == 1) {
//Log.i("success", users+"");
if (users.length() == 0) {
Toast.makeText(getActivity(), "No users found! \nPlease try again soon.", Toast.LENGTH_LONG).show();
db.emptyTable(SQLiteHandler.TABLE_USERS);
}else{
db.emptyTable(SQLiteHandler.TABLE_USERS);
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String uid = user.getString("uid");
String name = user.getString("name");
String dob = user.getString("dob");
String gender = user.getString("gender");
String photourl = user.getString("photoUrl");
String distance = user.getString("distance");
String[][] userValues = {
{ SQLiteHandler.KEY_UID, uid},
{ SQLiteHandler.KEY_NAME, name},
{ SQLiteHandler.KEY_DOB, dob},
{ SQLiteHandler.KEY_GENDER, gender},
{ SQLiteHandler.KEY_PHOTOURL, photourl},
{ SQLiteHandler.KEY_DISTANCE, distance}
};
db.insert(SQLiteHandler.TABLE_USERS, userValues);
}
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
//$lat, $lng, $email, $agefrom, $ageto, $distance, $distanceUnit, $interested_men, $interested_wmen
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("lat", gps.getLatitude()+"");
params.put("lng", gps.getLongitude()+"");
params.put("email", email);
params.put("agefrom", agefrom);
params.put("ageto", ageto);
params.put("distance", distance);
params.put("distanceUnit", distanceUnit);
params.put("interested_men", interested_men+"");
params.put("interested_wmen", interested_wmen+"");
params.put("fetch", "y");
Log.i(TAG, params+"");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
How to load GridView images with AsyncTask?
Downloading images as Bitmap in HomeFragment. Use NetworkImageView from Volley in layout of GridView item for loading images in GridView.
Instead of storing Bitmap, store image url in ImageItem.
See following tutorial for more help:
Using NetworkImageView
AsynTask class
public class GridDataAsyncTask extends AsyncTask<GridDataAsyncTask.GridCallback, Void, GridAdapter> {
public interface GridCallback {
void onAdapterReady(GridAdapter adapter);
}
private GridCallback mCallBack;
#Override
protected GridAdapter doInBackground(GridCallback... callbacks) {
mCallBack = callbacks[0];
// TODO get data and create grid adapter
return adapter;
}
#Override
protected void onPostExecute(GridAdapter gridAdapter) {
super.onPostExecute(gridAdapter);
mCallBack.onAdapterReady(gridAdapter);
}
}
Activity
public class GridActivity extends AppCompatActivity implements GridDataAsyncTask.GridCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GridDataAsyncTask().execute(this);
}
#Override
public void onAdapterReady(GridAdapter adapter) {
// TODO set adapte to GridView
}
}
Best you can do is use http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html and make a lru cache and place the images in lru cache.
Example is given in android tutorials
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
As suggested by fractalwrench and Budius, Picasso was a very good and VERY easy solution to this. All I had to do was to pass the photo url instead of the entire BitMap through to my GridView adapter and use Picasso.with(context).load(item.getImage()).into(holder.image); to create the BitMap for the image view. This was so easy to implement and gives me exactly what I need. Thaks

Categories

Resources