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();
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.
JSON DATA
{
VerifiedMember: [{ user_id: "23", first_name: "karan", phone: "" }],
success: 1,
message: "success"
}
Login Activity Class
public class NewLogin extends AppCompatActivity {
private static final String PREFER_NAME = "Reg";
Button btnLogin;
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
SharedPreferences sharedPreferences;
// User Session Manager Class
UserSessionManager session;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
// User Session Manager
session = new UserSessionManager(getApplicationContext());
sharedPreferences = getApplication().getSharedPreferences("KEY", Context.MODE_PRIVATE);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
private class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
#Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<>();
// Get username, password from EditText
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String url = "xxxx.xxx";
JSONObject json;
int successValue = 0;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "POST", params);
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("username")) {
uName = sharedPreferences.getString("username", "");
}
if (sharedPreferences.contains("password")) {
uPassword = sharedPreferences.getString("password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession("username", "password");
} else {
}
}else{
}
Log.d("TESS :: ", json.toString());
successValue = json.getInt("success");
Log.d("Success Response :: ", String.valueOf(successValue));
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return String.valueOf(successValue);
}
protected void onPostExecute(String jsonstring) {
pDialog.dismiss();
if (jsonstring.equals("1")) {
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
finish();
} else {
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
}
}
}
Sample activity:
public class Sample extends AppCompatActivity {
private static final String URL_DATA = "xxx.xxx";
// User Session Manager Class
UserSessionManager session;
LinearLayout linearLayout;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private List<Data_SAerver> data_sAervers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
// Session class instance
session = new UserSessionManager(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
loadRecyclerViewData();
swipeRefreshLayout.setRefreshing(false);
}
});
swipeRefreshLayout.setColorScheme(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
linearLayout = (LinearLayout) findViewById(R.id.linaralayout1);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Sample.this, Post_data_Activity.class);
startActivity(i);
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
data_sAervers = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
String filename = "";
String filetype = "";
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray posts = jsonObject.getJSONArray("posts");
if (posts != null && posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject fileObj = posts.getJSONObject(i);
String fName = fileObj.getString("firstname");
String created_at = fileObj.getString("created_at");
String post_desc = fileObj.getString("post_desc");
Log.e("Details", fName + "" + created_at + "" + post_desc);
JSONArray files = fileObj.getJSONArray("files");
if (files != null && files.length() > 0) {
for (int j = 0; j < files.length(); j++) {
JSONObject Jsonfilename = files.getJSONObject(j);
filename = Jsonfilename.getString("file_name");
filetype = Jsonfilename.getString("file_type");
if (filetype.equalsIgnoreCase("2")) {
filename = "xxx.xxx" + filename;
} else if(filetype.equalsIgnoreCase("1")) {
filename = "xxx.xxx" + filename;
}
Log.e("Files", "" + filename);
}
} else {
filename = "";
filetype = "";
}
Data_SAerver item = new Data_SAerver(fName, created_at, post_desc, filename, filetype);
data_sAervers.add(item);
}
}
adapter = new MyAdapter(data_sAervers, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuLogout:
session.logoutUser();
/*startActivity(new Intent(this, NewLogin.class));
break;*/
}
return true;
}
}
MyAdapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Data_SAerver> data_sAervers;
private Context context;
public MyAdapter(List<Data_SAerver> data_sAervers, Context context) {
this.data_sAervers = data_sAervers;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample, parent, false);
return new ViewHolder(v, context);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data_SAerver data_sAerver = data_sAervers.get(position);
holder.firstname.setText(data_sAerver.getFirstname());
holder.created_at.setText(data_sAerver.getCreated_at());
holder.post_desc.setText(data_sAerver.getPost_desc());
holder.filepathurl.setText(data_sAerver.getfilepath());
if (data_sAerver.getFiletype().equals("1")) {
holder.files.setVisibility(View.VISIBLE);
Picasso.with(context).load(data_sAerver.getfilepath()).resize(736, 1128).onlyScaleDown().into(holder.files);
holder.playvideo.setVisibility(View.GONE);
} else {
if (data_sAerver.getFiletype().equals("2")) {
holder.playvideo.setVisibility(View.VISIBLE);
holder.files.setVisibility(View.GONE);
holder.playvideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent play = new Intent(context, PlayVideo.class);
play.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
play.putExtra("url", data_sAerver.getfilepath());
context.startActivity(play);
}
});
}
}
}
#Override
public int getItemCount() {
return data_sAervers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// User Session Manager Class
UserSessionManager session;
public TextView firstname, commenttext;
public TextView created_at;
public TextView post_desc;
public ImageView files;
public LinearLayout comment_linear_layout;
public TextView comment_btn;
public TextView filepathurl;
public TextView playvideo;
// private TextView editTextUserName;
public TextView onlinefirstname;
Context con;
public ViewHolder(View itemView, Context context) {
super(itemView);
filepathurl = (TextView) itemView.findViewById(R.id.filepathurl);
filepathurl.setVisibility(View.GONE);
// editTextUserName = (TextView) itemView.findViewById(R.id.editTextUserrName);
playvideo = (TextView) itemView.findViewById(R.id.playvideo);
firstname = (TextView) itemView.findViewById(R.id.firstname);
created_at = (TextView) itemView.findViewById(R.id.created_at);
post_desc = (TextView) itemView.findViewById(R.id.post_desc);
files = (ImageView) itemView.findViewById(R.id.image_files);
con = context;
// onlinefirstname = (TextView)itemView.findViewById(R.id.online_user_firstname);
SparkButton sparkButton = (SparkButton) itemView.findViewById(R.id.star_button1);
sparkButton.setChecked(false);
comment_btn = (TextView) itemView.findViewById(R.id.comment_btn);
comment_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(con, Popup_layout.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
con.startActivity(i);
}
});
}
}
}
UserSessionManager:
public class UserSessionManager {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "username";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "firstname";
// password
public static final String KEY_PASSWORD = "password";
// Constructor
public UserSessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassord){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, uName);
// Storing email in pref
editor.putString(KEY_PASSWORD, uPassord);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Sample.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(_context, NewLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
Here I am not able to get user_id using shared preference. Please help me how to get it.
In onPostExecute try this you will get User ID
try {
String userid;
JSONObject ob = new JSONObject(jsonstring);
JSONArray arr = ob.getJSONArray("VerifiedMember");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
userid=obj.getString("user_id");
}
} catch (Exception e) {
}
You can use this pojo generator
http://www.jsonschema2pojo.org/
For parsing you can use google's gson library or jackson parser is also good.
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
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);
I have an activity in which layout I have X checkboxes and X TextView.
Through "setText()" I am filling the TextViews with text parsed through JSON in a complex form (several values from several columns plus static text).
I would like to convert this answer in a string to be later added to an Arraylist but it turns out null (I think because of the quotation marks).
this is the average text I am parsing and "setText"ing:
public void showJSON(String response){
String One="";
String Two="";
String Three = "";
String Four = "";
try {
JSONObject jsonObject = new JSONObject(response4);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
One = collegeData.getString(Config.KEY_One);
Two = collegeData.getString(Config.KEY_Two);
Three = collegeData.getString(Config.KEY_Three);
Four = collegeData.getString(Config.KEY_Four);
} catch (JSONException e) {
e.printStackTrace();
}
textView.setText("One:\t"+One+"\nTwo:\t" +Two+ "\nThree: "+ Three+"\nFour:\t"+Four);
}
I tried newString = String.valueOf("One:\t"+One+"\nTwo:\t" +Two+ "\nThree: "+ Three+"\nFour:\t"+Four); right after the setText, but it returns a null.
With a String newString = ""; it also becomes a problem as I have quotation marks in the code as well.
It goes without saying that both String newString; and TextView textView; are declared at the beginning.
Any guess?
Complete code is as following
public class Popup1 extends Activity {
public TextView textViewResult;
public String newString;
public ArrayList<String> builder = new ArrayList<String>();
public CheckBox check;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup1);
textViewResult = (TextView) findViewById(R.id.textViewResult);
final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox);
checkView(checkBox1, "holacheck", newString);
isChecked(checkBox1, "holacheck");
getData();
}
public void checkView (final CheckBox view, final String key, final String newString) {
view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (view.isChecked()) {
KeySaver.saveShare(Popup1.this, key, view.isChecked());
builder.add((String.valueOf(newString)));
builder.add("\n");
} else {
KeySaver.removeKey(Popup1.this, key);
}
}
});
}
public void isChecked(final CheckBox view, String key){
if(view != null){
if(KeySaver.isExist(Popup1.this, key)){
view.setChecked(KeySaver.getBoolSavedShare(Popup1.this, key));
}else{
view.setChecked(false);
}
}
}
public void getData() {
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
StringRequest stringRequest = new StringRequest(Config.DATA_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Popup1.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showJSON(String response){
String One="";
String Two="";
String Three = "";
String Four = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
One = collegeData.getString(Config.KEY_One);
Two = collegeData.getString(Config.KEY_Two);
Three = collegeData.getString(Config.KEY_Three);
Four = collegeData.getString(Config.KEY_Four);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("One:\t" + One + "\nTwo:\t" + Two + "\nThree:\t" + Three + "\nFour:\t" + Four);
newString = String.valueOf("One:"+One+"Two:" +Two+ "Three:"+ Three+"Four:"+Four);
}
}
#Override
public void finish() {
String risultato = builder.toString().replace("[", "").replace("]", "");
// Prepare data intent
Intent data = new Intent();
data.putExtra("result", risultato);
setResult(1, data );
super.finish();
}
}
newString is null the first time you access it in onCreate() in the line:
checkView(checkBox1, "holacheck", newString);
This is because your data hadn't been retrieved yet at that point.
Make checkBox1 a class field, and move the checkView() call to the end of the showJSON() method.
private CheckBox checkBox1;
...
public void onCreate(Bundle savedInstanceState) {
...
checkBox1 = (CheckBox) findViewById(R.id.checkBox);
isChecked(checkBox1, "holacheck");
getData();
}
public void showJSON(String response){
...
textViewResult.setText("One:\t" + One + "\nTwo:\t" + Two + "\nThree:\t" + Three + "\nFour:\t" + Four);
newString = String.valueOf("One:"+One+"Two:" +Two+ "Three:"+ Three+"Four:"+Four);
checkView(checkBox1, "holacheck", newString);
}
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