I am creating Application in which I have give functionality like Facebook timeline where people can update their story and any user can like or comment on the story. Everything is working fine but what I am facing issue is that when any user update story then data of updated story get saved on server but not added in recycle view at same time. When User go back and again comes on timeline screen then list will get update. How can I solve this problem ?
Custom Adapter
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
holder.txtComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
Intent intent = new Intent(context, StoryDetailActivity.class);
intent.putExtra("storyId",ide);
context.startActivity(intent);
}
});
holder.txtCommentLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
Intent intent = new Intent(context, StoryDetailActivity.class);
intent.putExtra("storyId",ide);
context.startActivity(intent);
}
});
holder.imageLike.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
TimelineActivity t = new TimelineActivity();
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
likeStory(ide,t.token);
return false;
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
private void likeStory(final String story_id, final String token) {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.likeStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_id", story_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
TimeLineActivity
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
adapter.notifyDataSetChanged();
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You need to implement some sort of polling mechanism on server end to do this. There's a workaround for it but it's not considered good practice. You can use a Timer to call your getTimeline function periodically to update the recycler view. Something like this in your onCreate:
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, page);
}
});
}
}, 0, your_time_in_milliseconds);
You can even do this asynchronously by using AsyncTask in Android.
Related
I want to make an activity to change user profil. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
public class ProfilActivity extends AppCompatActivity {
private EditText editTextNama, editTextEmail, editTextPassword, editTextNohp;
private Button Simpan;
private static final String PROFIL_URL = "http://vrai-dev.000webhostapp.com/koneksi_profil.php";
List<Profil> profilList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
Button back = (Button) findViewById(R.id.profil_back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ProfilActivity.this, MenuActivity.class);
startActivity(i);
}
});
profilList = new ArrayList<>();
getEmail();
editTextNama = (EditText) findViewById(R.id.profil_username);
editTextEmail = (EditText) findViewById(R.id.profil_email);
editTextPassword = (EditText) findViewById(R.id.profil_password);
editTextNohp = (EditText) findViewById(R.id.profil_nohp);
Simpan = (Button) findViewById(R.id.profil_simpan);
Simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
updateProfil();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void getEmail(){
final String email = "a";
StringRequest stringRequest = new StringRequest(Request.Method.POST, PROFIL_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loadProfil();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void loadProfil() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, PROFIL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray profil = new JSONArray(response);
JSONObject profilObject = profil.getJSONObject(0);
String foto_user = profilObject.getString("foto_user");
String username = profilObject.getString("username");
String email = profilObject.getString("email");
String password = profilObject.getString("password");
String nohp = profilObject.getString("nohp");
Profil viewProfil = new Profil(foto_user, username, email, password, nohp);
profilList.add(viewProfil);
editTextNama.setText(username);
editTextEmail.setText(email);
editTextPassword.setText(password);
editTextNohp.setText(nohp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfilActivity.this, error.getMessage() + "Error Load Profil", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
Had the same problem could not figure what was wrong, but this worked for, dont forget to add the dependency in the gradle file
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(com.android.volley.Request.Method.POST, YOUR_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// do work here
} catch (JSONException e) {
e.printStackTrace();
Log.d("Response", "failed: " + response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("title", title);
return params;
}
};
queue.add(postRequest);
** implementation 'com.he5ed.lib:volley:android-cts-5.1_r4'
**
Try to modify your loadProifle() method like below
// define below variable to globally
String mRequestBody=null;
private void loadProfil() {
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("namekey", "paste here name");
jsonBody.put("emailkey", "paste here email");
jsonBody.put("passkey", "paste here password");
jsonBody.put("nokey", "paste here number");
mRequestBody = jsonBody.toString();
}catch(JSONException e){
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, PROFIL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray profil = new JSONArray(response);
JSONObject profilObject = profil.getJSONObject(0);
String foto_user = profilObject.getString("foto_user");
String username = profilObject.getString("username");
String email = profilObject.getString("email");
String password = profilObject.getString("password");
String nohp = profilObject.getString("nohp");
Profil viewProfil = new Profil(foto_user, username, email, password, nohp);
profilList.add(viewProfil);
editTextNama.setText(username);
editTextEmail.setText(email);
editTextPassword.setText(password);
editTextNohp.setText(nohp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfilActivity.this, error.getMessage() + "Error Load Profil", Toast.LENGTH_LONG).show();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
Here is my php code for getting email variable.
Is there something wrong?
<?php
define('DB_HOST','Localhost');
define('DB_USER','id9815170_phpjember');
define('DB_PASS','phpjember');
define('DB_NAME','id9815170_phpjember');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
die('Unable to connect to database ' . mysqli_connect_error());
}
$email = $_POST['email'];
$stmt = $conn->prepare("SELECT foto_user, username, email, password, nohp FROM datauser WHERE email='$email';");
$stmt->execute();
$stmt->bind_result($foto_user, $username, $email, $password, $nohp);
$profil = array();
while($stmt->fetch()){
$temp = array();
$temp['foto_user'] = $foto_user;
$temp['username'] = $username;
$temp['email'] = $email;
$temp['password'] = $password;
$temp['nohp'] = $nohp;
array_push($profil, $temp);
}
echo json_encode($profil);
?>
My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});
I'm trying to add images to my listview, which is made from content retrieved from json. For the purpose of adding the images I'm trying to use picasso, and I've watched a tutorial about it and it worked, the problem is that I don't think it can be used in my app, at least not with the method I saw.
Here's my code, hope anyone can help me and explain me how to do this.
public class TodosOsPaises extends AppCompatActivity {
private String TAG = TodosOsPaises.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://";
ArrayList<HashMap<String, String>> listaPaises;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todos_os_paises);
listaPaises = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPaises().execute();
}
private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TodosOsPaises.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String Coord_LAT = jsonObject1.getString("Coord_LAT");
String Coord_LONG = jsonObject1.getString("Coord_LONG");
String Coord_Zoom = jsonObject1.getString("Coord_Zoom");
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
pais.put("Coord_LAT", Coord_LAT);
pais.put("Coord_LONG", Coord_LONG);
pais.put("Coord_Zoom", Coord_Zoom);
listaPaises.add(pais);
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(TodosOsPaises.this, listaPaises, R.layout.list_item, new String[]{"Designacao", "URL_IMAGEM"},
new int[]{R.id.Designacao, R.id.imageViewPais});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
Intent intent = new Intent(TodosOsPaises.this, MapsActivity.class);
intent.putExtra("data", listaPaises.get(position));
startActivity(intent);
}
});
Collections.sort(listaPaises, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> first, HashMap<String, String> second) {
String firstValue = first.get("Designacao");
String secondValue = second.get("Designacao");
return firstValue.compareTo(secondValue);
}
});
}
}
}
Picasso.with(content)
.load("path_or_url_or_file")
.into(new Target() {
#Override public void onBitmapLoaded(final Bitmap bitmap,
final Picasso.LoadedFrom from) {
}
#Override public void onBitmapFailed(final Drawable errorDrawable) {
}
#Override public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
I am trying to make a volley PUT request to upload an image, Since httpEntity is deprecated now, I had to do some other research, I came across these solutions and tried to implement them into my code :
1. https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
2. How to send multipart request using Volley without HttpEntity?
3. Working POST Multipart Request with Volley and without HttpEntity
but still I cannot upload my image. The image I want to upload is either captured from the camera or selected in the gallery, and it is executed onClick.
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
CustomerIcon = (ImageView) findViewById(R.id.CustomerIcon);
confirm_button = (Button) findViewById(R.id.confirm_button);
CustomerIcon.setOnClickListener(new ImageView.OnClickListener(){
public void onClick(View v){
showPickImageDialog();
}
});
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
//PUT VOLLEY
saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Choose Profile Icon");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
}
}
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "https://url to put image to";
SharedPreferences sp1=this.getSharedPreferences("FINALTOKEN", Context.MODE_PRIVATE);
final String finalToken = sp1.getString("FINALTOKEN","");
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.PUT, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succeed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers= new HashMap<>();
headers.put("Authorization",finalToken);
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", ImageConverter.getFileDataFromDrawable(getBaseContext(), CustomerIcon.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
}
VolleyMultipartRequest.java and VolleySingleton.java I am using the same class as what my first link has.
My errors are first of all I cannot resolve symbol 'Constant' in the if statement:
if (status.equals(Constant.REQUEST_SUCCESS))
so I tried commenting the statement, after running the code I got the following error:
BasicNetwork.performRequest: Unexpected response code 500 for https://my url
W/System.err: org.json.JSONException: No value for status
I am not sure what is causing my problem,please help, thank you!
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
mChoosenFile is your image file
First of all convert your image bitmap to base64 string using the following code:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then make a PUT Request like the following one and pass the base64 string as a parameter of the request
url = "http://example.com";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("imageString", base64String);
return params;
}
};
queue.add(putRequest);
Refer Android Volley Tutorial if you face any difficulty in implementing volley request.
I want to move GET method inside (if) that located inside onResponse of POST request without calling URL again because once the user post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aalm/getticket.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("responseticket")) {
showTicket();
} else {
Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
private void showTicket(){
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("responseticket");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ticket = jsonArray.getJSONObject(i);
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "Volley");
}
}
);
requestQueue2.add(jsonObjectRequest);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}