android Restful GET operation - android

I need to get an image using webservice which is rest.And most of the tutorials are about click the button in order to trigger the process.I need to implement this such a way that when activity opens images has to be loaded immediately without trigger or clicking the button or something.I just need a source or idea.
Any help will be appreciated.

Implement an Asynctask and call it onCreate.
Here is an example on how to do it;
public class MainActivity extends ListActivity {
.
.
.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
.
.
// Calling async task to get json
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(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
As you can see, you only need to call the asynctask (new GetContacts().execute();) onCreate and it will behave as you design it.
References: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Write your code in onCreate() or onResume() method of activity.
For downloading images you can use Picasso and Glide.
For communication between app and webservice you can use Retrofit.
Also for more information you can read this tutorial Retrofit - Getting Started and Create an Android Client

Write your code for loading image in onCreate() method of Activity. So user don't need to trigger or clicking the button or something.

Related

How to pass extra data of a list view to another activity in Android?

I am trying to create a list view with only "name" in the parent list (MainActivity) and pass the remaining "email" and "mobile" to another activity (SingleContactActivity) along with the "name". How can I achieve that? Now my MainActivity listview is showing all details, name, email, mobile, I know I have to delete something from here. My second activity result is OK. But MainActivity must display the list with "name" only. For this I need to make changes to the MainActivity code. The issue is that I am new to JAVA and Android programming. I want your help showing exactly which line to delete from MainActivity so it show only "name" in the list, and pass the other two parameters "email" and "mobile to the second activity along with the "name".
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
*/
private 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
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);
}
}
}
you can save data in bundle and carry it on next activity. or u can also use shared preference to save data temporarily and next activity you get the data from shared preference and then clear it. https://www.tutorialspoint.com/android/android_shared_preferences.htm
Try to go in second activity using intent.and pass your variables to display in second activity like this:
use this in onPostExecute function or any other event what u want
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("name", namestringvariable);
intent.putExtra("email", emailstringvariable);
startActivity(intent);
finish();
and in second activity
Bundle bundle = getIntent().getExtras();
String name= bundle.getString("name");
String email= bundle.getString("email");

Unable to show image in listview by imageloader class

I have used view in my application. I wants to show image in my list by using POST method. I got the image url by POST method but unable to show it in list. some part of my code snippet is here....
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Home1.this);
pDialog.setMessage("Please wait....");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler1 sh = new ServiceHandler1(apikey, latitude, longitude);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler1.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String username = c.getString(TAG_USERNAME);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String contact_number = c.getString(TAG_CONTACT_NUMBER);
String postalcode = c.getString(TAG_POSTAL_CODE);
String image = c.getString(TAG_IMAGE);
Log.v("as.",image);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView Profileimage = (ImageView) findViewById(R.id.logo);
imageLoader.DisplayImage(image, Profileimage);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_IMAGE, image);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS, address);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contact.put(TAG_USERNAME, username);
contact.put(TAG_POSTAL_CODE, postalcode);
contact.put(TAG_CONTACT_NUMBER, contact_number);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
Home1.this, contactList,
R.layout.list_item1, new String[]{TAG_EMAIL, TAG_USERNAME, TAG_ADDRESS, TAG_POSTAL_CODE, TAG_CONTACT_NUMBER,
}, new int[]{
R.id.company, R.id.description, R.id.address, R.id.operating_hours, R.id.contact});
setListAdapter(adapter);
}
}
I have used image loader class for converting the image url... guys please help me
please suggest me how can I parse image in postExecute()...
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
Home1.this, contactList,
R.layout.list_item1, new String[]{TAG_EMAIL, TAG_USERNAME, TAG_ADDRESS, TAG_POSTAL_CODE, TAG_CONTACT_NUMBER,
}, new int[]{
R.id.company, R.id.description, R.id.address, R.id.operating_hours, R.id.contact});
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView Profileimage = (ImageView) findViewById(R.id.logo);
imageLoader.DisplayImage(TAG_IMAGE, Profileimage);
setListAdapter(adapter);
}
}
You need to create custom Listview adapter to achieve this task. Please check loading-image-asynchronously-in-android-listview link to create one. In your post execute method you have to create object of adapter and then pass your contactList array list which consist images URL.
In the link you will get full code of showing images in listview with code of downloading image using Imageloader library.
Let me know if it helps.

Android JSONObject cannot be converted to JSONArray

I'm new in android. I'm trying to get json but I got this error.
I trying following this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
I already search the solution, but I still don't get it how to use the JSONArray.
Here is my Json example
[{"id":"152","category_id":"14","item_name":"Restaurant1","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"161","category_id":"14","item_name":"Restaurant10","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"153","category_id":"14","item_name":"Restaurant2","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"154","category_id":"14","item_name":"Restaurant3","cuisine_id":"7","cuisine_name":"American"},{"id":"155","category_id":"14","item_name":"Restaurant4","cuisine_id":"3","cuisine_name":"Chinese"},{"id":"156","category_id":"14","item_name":"Restaurant5","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"157","category_id":"14","item_name":"Restaurant6","cuisine_id":"8","cuisine_name":"Coffee"},{"id":"158","category_id":"14","item_name":"Restaurant7","cuisine_id":"17","cuisine_name":"Middle Eastern"},{"id":"159","category_id":"14","item_name":"Restaurant8","cuisine_id":"6","cuisine_name":"Indonesian"},{"id":"160","category_id":"14","item_name":"Restaurant9","cuisine_id":"3","cuisine_name":"Chinese"}]
And Here the class
/**
* Async task class to get json by making HTTP call
* */
private class GetRestaurant extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attractions.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
// looping through All Contacts
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
String id = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CUISINE_NAME, id);
// adding contact to contact list
restaurantList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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(
Attractions.this, restaurantList,
R.layout.attractionslayout, new String[] { TAG_ITEM_NAME, TAG_CUISINE_NAME }, new int[] { R.id.item_name,
R.id.cuisine_name});
// Assign adapter to ListView
listview.setAdapter(adapter);
}
}
Thanks Before.
Try this..
Your response starts with JSONArray
[ ==> JSONArray
{ ==> JSONObject
Change this..
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
restaurant = jsonObj.getJSONArray(TAG_ITEM_NAME);
to
restaurant = new JSONArray(jsonStr);
Your string is not json object , it is json array because the string are start via third bracket
so, try this
restaurant = new JSONArray(jsonStr);
you do not need to convert it as a josn object,
JSONObject jsonObj = new JSONObject(jsonStr);

Duplicate values doing Asynctask in Listview

I have an AsyncTask that connects to a service and with an adapter set the result in a ListView. In the action bar I want to put a button to do the refresh action but the problem is that when I click this button and I call to the service it duplicates the results in the list view.
I have tried:
ListView myList=(ListView)findViewById(R.id.list);
myList.setAdapter(null);
if ((new Utils(this)).isConnected()){
new MyTask().execute();
}
My AsyncTask code:
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("searching...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url+id, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String nick = c.getString("nick");
String minuto = c.getString("minuto");
String fecha = c.getString("fecha");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("nick", nick);
contact.put("minuto", minuto);
contact.put("fecha", fecha);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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(
DetallePelicula.this, contactList,
R.layout.list_rowopiniones, new String[] { "nick", "minuto",
"fecha" }, new int[] { R.id.title,
R.id.minuto, R.id.fecha });
ListView myList=(ListView)findViewById(R.id.list);
myList.setAdapter(adapter);
}
}
Somebody can help me? thanks
In your doInBackground, you are adding the new data to an already existing list. This means that, as you've mentioned, the data will duplicate.
Just add contactList.clear() to your onPreExecute method:
#Override
protected void onPreExecute() {
super.onPreExecute();
contactList.clear(); // Add this line
// Showing progress dialog
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("searching...");
pDialog.setCancelable(false);
pDialog.show();
}

JSON Data stored to SQLite

I am following this to store JSON parsed data into SQLite Database, but whenever i use my app offline not getting stored data into ListView.
Is there anything left to implement in my existing code ?
MainActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper=new CategoryHelper(MainActivity.this);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
// Calling async task to get json
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(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
databaseHelper.saveCategoryRecord(id,name);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
I don't know what that ServiceHandler thing is, but I'm guessing the call to makeServiceCall() returns null when you're offline. This means you aren't populating the contactList, which means it's empty when you're creating the ListAdapter.
I'm guessing what you want to do, is add an else clause to if (jsonStr != null) that populates contactList with records from your DB. How to do this depends on the implementation details of CategoryHelper.
Using shared preference would be a better approach for that. Follow these steps:
search and download GSON library. This will simplify our task for saving and retrieving JSON to/from shared preferences and let your app use the GSON library
example:
SharedPreferences prefs = getSharedPreferences("mySharedPreferenceKey");
Editor editor = prefs.edit();
Gson gson = new Gson();
//convert your object to string and save it to shared preference
ArrayList<Integer> myIntArrs = new ArrayList<Integer>();
editor.putString("myJSONKey", new Gson().toJson(myIntArrs)).commit();
//get your json string from shared preferences
public final Type ARRAYLIST_INTEGER = new TypeToken<ArrayList<Integer>>(){}.getType();
ArrayList<Integer> intArrs = gson.fromJson(prefs.getString("myJSONKey", "{}"), ARRAYLIST_INTEGER);
//do something with your intArrs
Hope this helps!

Categories

Resources