java - Using Picasso for getting image from url with json - androidstudio - java

i'm using JSON for requesting text and put it in a list view with custom adapter, here is my code so far..
private class getMovies extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(alrehabfilms.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
http sh = new http();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
// Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray moviesp90 = jsonObj.getJSONArray("moviesalrehab");
// looping through All Contacts
for (int i = 0; i < moviesp90.length(); i++) {
JSONObject c = moviesp90.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String actors = c.getString("actors");
String tandp = c.getString("prizeandtime");
String img = c.getString("img"); //here is for the image
// Phone node is JSON Object
JSONObject pref = c.getJSONObject("pref");
String imrating = pref.getString("imrating");
String genre = pref.getString("genre");
String guide = pref.getString("guide");
String director = pref.getString("director");
// tmp hash map for single contact
HashMap<String, String> movie = new HashMap<>();
// adding each child node to HashMap key => value
movie.put("id", id);
movie.put("name", name);
movie.put("actors", actors);
movie.put("prizeandtime", tandp);
if(img != null && !img.equalsIgnoreCase("")) Picasso.with(alrehabfilms.this).load(img).into(imggg); //here idk how to put like movie.put("img", Picasso code)
movie.put("imrating", imrating);
movie.put("genre", genre);
movie.put("guide", guide);
movie.put("director", director);
// adding contact to contact list
alrehabmovieList.add(movie);
}
} catch (final JSONException e) {
// Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"An error happened, please try again!",
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
// Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Failed to retrieve data, please check your internet connection",
Toast.LENGTH_LONG)
.show();
AlertDialog.Builder adb = new AlertDialog.Builder(alrehabfilms.this);
adb.setTitle("No internet connection");
adb.setMessage("Would you like to try to gather data again?");
adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getMovies().execute();
} });
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
} });
adb.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
alrehabfilms.this, alrehabmovieList,
R.layout.imgtest, new String[]{"name", "actors",
"prizeandtime", "img", "imrating", "genre","guide", "director"}, new int[]{R.id.movieName,
R.id.movieActors, R.id.moviePrizeAndTime, R.id.imggg//imageeview, R.id.movieRating, R.id.movieGenre,R.id.pGuid, R.id.dir});
lv.setAdapter(adapter);
}
}
}
As you see here, i put this line for the image
String img = c.getString("img"); //here is for the image
My problem here is how to put it in that way
movie.put("img", THECODEIWANT);
instead of this,
if(img != null && !img.equalsIgnoreCase(""))
Picasso.with(alrehabfilms.this).load(img).into(imggg);
thanks in advance

Why do you want to directly put the image in the array?
You can do that but it will block your app while it gets real Bitmap image data from Picasso.
That is why we are using Picasso to asynchronously load image in the background thread.

Related

Is it necessary to retrieve all the values from json object?

I read this article https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ and in this article
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing 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 errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
He/she has retrieved all the values before inflating it to the listview.
I am new to JSon.I tried to retrieve only names but it is not running. So, is it necessary to retrieve all the value before using any of it.
Thank you
The simple answer is: it depends.
When you are the one defining what comes in your JSON data, then you make sure to design it in a "minimalistic" way: you only want to include information that has value for you (or your users). Meaning: in such a world, you only transport the data that you want to display. Then, most likely, your backend code will want to access all data in your JSON strings. Because you designed all these JSON objects to hold only relevant information.
But very often, your code just consumes something. You don't own/define the JSON structure, you just know "there should be fields X, Y, Z in there, which my code will use". Then, obviously, you only extract X, Y, Z. And you leave other data in that JSON alone. There is no point in touching and processing information that isn't relevant for your use case.
In other words: in the real world, you don't do things because you can. You do things, because doing so results in value to you respectively to users of your product.

How to get the attribute from jsonarray in json url and display in textview

Hi i am trying to get the json response which has attribute with jsonarray
like (ex: {A:one,B:[{a:one,b:two},{a:two,b:one}]}) i have trying to get
the a:one and b:two values only. But my logcat says error:
RecyclerView: No adapter attached; skipping layout
Json parsing error: Value custom_attributes of type java.lang.String cannot be converted to JSONArray
i want to get this values in textview for my product detail view...
My Coding is :
private class GetProductDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
dialog_pro = new ProgressDialog(Product_Detail_Activity.this);
dialog_pro.setMessage("Please wait...");
dialog_pro.setCancelable(false);
dialog_pro.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(BaseURL);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
name = jsonObj.getString("name");
JSONArray items = new JSONArray("custom_attributes");
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String atrr = c.getString("attribute_code");
if(atrr.equalsIgnoreCase("short_description")) {
des = c.getString("value");
}
}
}catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
// pro_name.setText("Json error:" + e.getMessage());
}
});
}
} 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 errors!",
Toast.LENGTH_LONG)
.show();
}
});
// AppController.getPermission().addToRequestQueue(jsonObj);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
if (dialog_pro.isShowing())
dialog_pro.dismiss();
pro_name.setText(name);
short_desc.setText(des);
}
}
Being based on your JSON
try {
JSONObject responseObject = new JSONObject(response);
String A= responseObject.getString("A");
JSONArray bArray= responseObject.getJSONArray("B");
for(int i=0;i<bArray.length();i++){
JSONObject innerObject=bArray.getJSONObject(i);
String a= innerObject.getString("a");
String b= innerObject.getString("b");
}
} catch (Exception e) {
e.printStackTrace();
}
In your code you have JSONArray items = new JSONArray("custom_attributes"); should be changed. You should get your custom_attributes array from the jsonObj object using object.getJSONArray().
For your first problem-RecyclerView: No adapter attached; skipping layout->
Just set an empty adapter first, update it as soon as you have the data (this is what works for me)
For your second problem-Json parsing error: Value custom_attributes of type java.lang.String cannot be converted to JSONArray->
The e.g json that you have posted "{A:one,B:[{a:one,b:two},{a:two,b:one}]}"
it is not in valid json format

Android when AsyncTask Process if no internet found how to give warning "please connect internet" [duplicate]

This question already has answers here:
How can i check whether an android device is connected to the web?
(4 answers)
Closed 5 years ago.
Android AsyncTask processing and found no internet connection system give warning "user please connect internet". How can I do this in my code?
Another problem is when internet not connected its show loading but I don't go back page. How to solve this problem?
I don't understand how to do this inside this code.
public class data extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://orangehostbd.com/app/bpl2/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(data.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing 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 errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
data.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
Create a Helper class.
Inside this class, create a method to check internet connection.
public static boolean isNetworkConnected(Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Inside your activity class, use above isNetworkConnected() method in doInBackground.
if (Helper.isNetworkConnected(this)) {
// do your stuff
} else{
Toast.makeText(YourActivity.this, "Your internet connection is lost.", Toast.LENGTH_SHORT).show();
}
Use this permission in Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
If the question is "how to display warning inside doInBackground" because you are not allowed to access the gui inside doInBackground technically you can use the progress indicator of asynctask to transfer a message to the gui.
However i would recommond a differen aproach: either
check for problems before starting the async task
or let the async task stop and return with an error as described by #Muthukrishnan Rajendran

how to print only name from hashmap java

This is mainActivity and i am passing data(contactList) to second activity
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contact.put("address", address);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing 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 errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
Intent in = new Intent(getApplicationContext(), MapsActivity.class);
in.putExtra("array", contactList);
startActivity(in);
return null;
}
I want to print just address from this array but I am having a problem to print just address, it is printing the whole ArrayList
Intent intent = getIntent();
if(intent!=null){
ArrayList tmp = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("array");
System.out.println(Arrays.asList(tmp));
System.out.println(tmp);
}

How to display many images through ListAdpter?

I have an android activity that reads some items from the web server, everything is alright except the image.
I've done the same with only one item and it worked, but I can't think of anyway to read many items and set their value to imageView.
Is there anyway that allows me to set the image value to the listAdapter after ending them by hashmap?
Any help would be greatly appreciated!
Here is the code:
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(GetAllRecipesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("category", R_category));
Log.d("R_category: ", R_category);
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_table);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SCB_ID);
String title = c.getString(TAG_TITLE);
String name = c.getString(TAG_NAME);
name= name.substring(1, name.length());
name="http://studentcookbook.comoj.com/android_connect"+name;
Log.d("NAME OF THE URL!",name);
// here i'm starting to set the image value it's all good here
downloadBitma =downloadBitmap(name);
// creating new HashMap
HashMap<String, Object> map=new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_SCB_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_NAME, downloadBitma);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),AddRecipeActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Buffer Error", "Error converting result " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Buffer Error", " Image is not passing to hashmap");
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// here i'm trying to set the image to imageView but it didn't work
// final ImageView imageView = (ImageView) findViewById(R.id.GetAllmg);
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// imageView.setImageBitmap(downloadBitma); }
// });
ListAdapter adapter = new SimpleAdapter(GetAllRecipesActivity.this, productsList,
R.layout.list_recipe, new String[] { TAG_SCB_ID,TAG_TITLE},
new int[] { R.id.GetAllscbid, R.id.GetAllTitle });
// updating listview
Toast.makeText(GetAllRecipesActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
setListAdapter(adapter);
}
});
}
// method for downloading images
private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
I recommend Universal Image Loader.

Categories