how to print only name from hashmap java - 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);
}

Related

JSONParser: IOException: Unable to resolve host "my host address": No address associated with hostname

I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// 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) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.

Set Progressbar with percentage when data download from json get method in android

I want to show progress bar with percentage of the download the data from json. Right now I am getting the data from the url and store in the local database in other class and this class called in MainActivity. Now I want to show the progressbar with percentage of the download file from json url.
This is my code
public class Web_Product {
Context context;
List<Variable> list = new ArrayList<Variable>();
//List<Variable> list1;
String url = "https://api.androidhive.info/progressdialog/hive.jpg";
URL url1 = null;
InputStream is1 = null;
String product_id, product_name, product_image;
private byte[] logoImage;
private JSONArray jsonArray;
public Web_Product(Context context) {
this.context = context;
Log.e("hello", "Message");
}
public void product_insert() {
// new AsyncLogin().execute();
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("product");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("TEST_P", "in");
JSONObject details = jsonArray.getJSONObject(i);
product_id = details.getString("product_id");
product_name = details.getString("product_name");
product_image = details.getString("product_image");
logoImage = getLogoImage(product_image);
Variable variable_object = new Variable();
variable_object.setProduct_id(product_id);
variable_object.setProduct_name(product_name);
variable_object.setProduct_url_image(logoImage);
list.add(variable_object);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
Log.e("TEST1", " Ritunjay" + list.size());
Product_data product = new Product_data(context);
product.Insert_Product(list);
Log.e("listpo", "" + list);
}
public JSONArray json_web_prod() {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
jsonArray = jsonRootObject.optJSONArray("product");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}`
Main Activity
class add extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
#Override
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Downloading Data...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
flag = true;
Intent intent = getIntent();
startActivity(intent);
finish();
Log.e("flag , post", "" + flag);
}
#Override
protected String doInBackground(String... params) {
web_product = new Web_Product(getApplicationContext());
web_product.product_insert();
return null;
}
}`
In doInBackground , you need to publishProgress also . So that your progress bar can updated , like this
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
Here totalSize will help you to calculate your total remaining data and publishProgress will public it .

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

I want to return data from doInBackground method and compare with other string in other methods

what I do in this code for comparing retrieved data from server to other string, please tell me changes.
ArrayList<HashMap<String, String>> matchStudentsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_sem);
present = (Button) findViewById(R.id.button2);
bt= BluetoothAdapter.getDefaultAdapter();
// Call Async task to get the match fixture
new GetFixture().execute();
}
private class GetFixture extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_Students);
String json = serviceClient.makeServiceCall(URL_Students,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture response: ", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchRecords = jsonObj.getJSONArray(TAG_Table);
Log.d("json aray", "user point array");
int len = matchRecords.length();
Log.d("len", "get array length");
for (int i = 0; i <len; i++) {
JSONObject c = matchRecords.getJSONObject(i);
String RollNo = c.getString(TAG_Roll_No);
Log.d("RollNo", RollNo);
String FirstName = c.getString(TAG_First_Name);
Log.d("FirstName", FirstName);
String LastName = c.getString(TAG_Last_Name);
Log.d("LastName", LastName);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_Roll_No, RollNo);
matchFixture.put(TAG_First_Name, FirstName);
matchFixture.put(TAG_Last_Name, LastName);
matchStudentsList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
ThirdSem.this, matchStudentsList,
R.layout.list_checkitem, new String[]{TAG_Roll_No, TAG_First_Name, TAG_Last_Name, TAG_BAddress}
, new int[]{R.id.RollNo, R.id.FirstName, R.id.LastName }
);
setListAdapter(adapter);
}
}
}
it will be very very helpful for me please
You are returning a null value on all your if statements, you should return matchStudentsList once you are done with your for loop, otherwise return null
after your for loop , add:
return matchStudentsList;
and change your onPostExecute signature to:
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
also change your AsyncTask definition to:
AsyncTask<String, Void, ArrayList<HashMap<String, String>>>
You can get your doInBackground() string by something like this.
String desiredString = new GetFixture().execute().get();
Call the above in onCreate() method. Instead of :
new GetFixture().execute();

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

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.

Categories