Getting Data from JSON? - android

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
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();
}
}
MainActivity.java
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 = "https://someLink";
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("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// 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[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**

You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}

Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}

i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}

Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

Related

My UI is not updating after API call of openweather

I want to parse JSON from the Openweather API but after many iterations and debugging, my JSON string is not updating, I do not think that there is any problem still the temperatures( minTemperature and maxTemperature) and the name of the place(mPlace) is not set, also I logged the maxtemperature but the console is showing nothing please look into my code.
public class MainActivity extends AppCompatActivity {
private EditText placeText;
private Button enterPlaceButton;
private TextView minTemperature;
private TextView maxTemperature;
private TextView mPlace;
private static final String AppID ="56a5e01eba3af36a7a9b7b210a437d09";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Weather");
placeText = findViewById(R.id.myPlaceEditText);
enterPlaceButton = findViewById(R.id.enterPlace);
minTemperature = findViewById(R.id.minTemperature);
maxTemperature = findViewById(R.id.maxTemperature);
mPlace = findViewById(R.id.mPlace);
}
#Override
protected void onResume() {
final URL[] url = {null};
enterPlaceButton.setOnClickListener(v -> {
url[0] = makeUrl(placeText.getText().toString());
placeText.setText("");
});
if (url[0] != null) {
MyAsync myAsync = new MyAsync();
myAsync.execute(url[0]);
}
super.onResume();
}
public URL makeUrl(String place) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("http");
uriBuilder.authority("api.openweathermap.org/");
uriBuilder.appendPath("data");
uriBuilder.appendPath("2.5");
uriBuilder.appendPath("weather");
uriBuilder.appendQueryParameter("q",place);
uriBuilder.appendQueryParameter("appid",AppID);
try {
return new URL(uriBuilder.build().toString());
} catch (MalformedURLException e) {
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
public class MyAsync extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... urls) {
StringBuilder jsonResponseBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
jsonResponseBuilder.append(line);
line = bufferedReader.readLine();
}
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
Log.d(MyAsync.class.getName(),jsonResponseBuilder.toString());
return jsonResponseBuilder.toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
setDataFromJSON(s);
super.onPostExecute(s);
}
public void setDataFromJSON(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject getMainObject = jsonObject.getJSONObject("main");
String maxTemp = getMainObject.getString("temp_max");
Log.i(MainActivity.class.getName(), maxTemp);
maxTemperature.setText(maxTemp);
String minTemp = getMainObject.getString("temp_min");
minTemperature.setText(minTemp);
mPlace.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
}
}
}

arraymap is better than sparse array to memorise some data catched from a JSON file?

I had wrote a code which use a parse to catch some data from a JSON file but i don't know what kind of structure is better between the sparse array or the array map for memorise these data ?
I had used a array map but I don't know if it's too wasted on so little data data.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pd;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, ValoriDiSueg> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
The parse of these data
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("weather"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new ValoriDiSueg( jsonPart.getString("main"), jsonPart.getString("description")));
//ArrayDati.put(i,new ValoriDiSueg("description : "+ jsonPart.getString("description")));
textViewProg.setText(textViewProg.getText()+"main : "+ ArrayDati.get(i).Main +"\n"+textViewProg.getText()+"description : "+ ArrayDati.get(i).Description );
}
} catch (Exception e ){
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
}
And I created a class:
public class ValoriDiSueg {
String Main;
String Description;
public ValoriDiSueg(String main, String description) {
this.Main = main;
this.Description = description;
}
}
any suggestions??
In simple:
If your key is int or long, you should use SparseArray, SparseLongArray as it will not boxing/un-boxing the key value when operates. Also, it provides similar classes for int/long values as long as the key is int/long.
If you key is not int nor long, such as an object or String, you should use ArrayMap instead as it will handle the conflicts of key hashes.
There are no much performance and memory usage difference between these two class as they are all requires O(log n) to search and O(n) to insert/delete (in most cases).

Parse json multiple url

I can parse json from a url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
I created a class MyAsyncTask, this class receive the URL's list and the context activity. Guide yourself with the sample code.
public class MyAsyncTask extends AsyncTask<Void, Void, List<JSONObject>> {
private Activity activity;
private List<String> urls;
public MyAsyncTask(Activity activity, List<String> urls) {
this.urls = urls;
this.activity = activity;
}
#Override
protected List<JSONObject> doInBackground(Void... voids) {
HttpURLConnection connection = null;
BufferedReader reader = null;
List<JSONObject> jsonURls = new ArrayList<>();
try{
for (String url : urls) {
URL link = new URL(url);
connection = (HttpURLConnection) link.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
sb.append(line);
reader.close();
JSONObject jsonResult = new JSONObject(sb.toString());
jsonURls.add(jsonResult);
}
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(activity, "URL error", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, "Connection error", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(activity, "JSON Parsing error", Toast.LENGTH_SHORT).show();
}
return jsonURls;
}
#Override
protected void onPostExecute(List<JSONObject> jsonObjects) {
super.onPostExecute(jsonObjects);
// Process your JSONs
}
}
For to call it, you should do the following (Within your activity):
List<String> urls = new ArrayList<>();
urls.add("https://jsonplaceholder.typicode.com/posts/1");
MyAsyncTask myAsyncTask = new MyAsyncTask(MyActivity.this, urls);
myAsyncTask.execute();
The processing of the JSONs, you must in the PostExecute method.
Don't forget add internet permissions.
you can simple add your urls into the arraylist and parse the urls through a loop.
Arralist<String> arraylist = new Arraylist;
arraylist.add(link1);
arralist.add(link2);
private void fetchMovies() {
int x = arralist.size();
for(int i = 0;i<x;i++)
{ JsonArrayRequest req = new JsonArrayRequest(arralist.get(i),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}}

Unable to parse JSON data into Listview

im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
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.lv);
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(Locations.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 {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// 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");
// 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);
// 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();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
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();
}
}
Thanks for your input
Override getCount method into adapter class.

AsyncTask with timeout

I want my application throws timeout after 10 seconds in AsyncTask.So what should i do ? If i am not using this so my application is crash.
And sorry for my bad English.
this is my AsyncTask
LoginTask
public class LoginTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
/* JSONParser jParser = new JSONParser();
// JSONArray data = null;
String jsonstr = jParser.makeServiceCall(URL, JSONParser.POST);*/
BufferingH call = new BufferingH();
jsonstr = call.makeBufferCall(URL);
System.out.println("Json url view string " + jsonstr);
return null;
}
#SuppressLint("ShowToast")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (jsonstr != null) {
try {
JSONObject jobj = new JSONObject(jsonstr);
URLmessage = jobj.getString("message").toString();
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjj = jarray.getJSONObject(i);
Username = jobjj.getString("r_name");
Password = jobjj.getString("r_password");
FirstName=jobjj.getString("first_name");
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid username password", Toast.LENGTH_SHORT).show();
Log.e("Login Screen", "Couldn't get any data from the url");
}
try {
if (URLmessage.matches("Invalid Login")) {
Toast.makeText(getApplicationContext(), "Invalid Login.....",
Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Login.this, Register.class);
// startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login Successful...",
Toast.LENGTH_SHORT).show();
Password = et_password.getText().toString();
Username = et_username.getText().toString();
Intent k = new Intent(getBaseContext().getApplicationContext(),
MainActivity.class);
k.putExtra("regId", regId);
startActivity(k);
finish();
SettingsFragment.setDefaults("Username", Username, getApplicationContext());
SettingsFragment.setDefaults("Password", Password, getApplicationContext());
SettingsFragment.setDefaults("FirstName", Login.FirstName, getApplicationContext());
Toast.makeText(getApplicationContext(), "FirstName = "+FirstName, Toast.LENGTH_SHORT).show();
// gcmregister_from_sharedpref
gcmafterregistration();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
} catch (Exception e) {
e.printStackTrace();
}
progress.setVisibility(View.INVISIBLE);
}
}
And this is my logcat so you can batter understand.
I have put one dummy code change your code by referring this.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (commonUtils.isNetworkAvailable(mContext)) {
NewHistoryAsync task = new NewHistoryAsync(getContext(), listDataHeader, listDataChild);
task.execute(CommonUtils._History + "ID=" + userUhid);
} else {
Toast.makeText(mContext, "No Network Available!!",
Toast.LENGTH_LONG).show();
}
private class NewHistoryAsync extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
Context mContext;
List listDataHeader;
HashMap listDataChild;
public NewHistoryAsync(Context context, List listDataHeaderList, HashMap listDataChildMap) {
mContext = context;
listDataHeader = listDataHeaderList;
listDataChild = listDataChildMap;
this.listDataHeader = new ArrayList<String>();
this.listDataChild = new HashMap<String, List<String>>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog = ProgressDialog.show(mContext, Html.fromHtml(
"<b>Heading<b>"), Html.fromHtml("<medium>Downloading Details..</medium>"), true);
// progressDialog.setTitle("Downloading Details");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String resResult = NewHistoryService(params[0]);
JSONObject jsonResponse;
try {
//JSONObject jsonObject = new JSONObject(resResult);
JSONArray jsonArray = new JSONArray(resResult);
// Log.i("doinb---> ", resResult);
/* ArrayList<ClaimsHistoryNewSearchModel> listDataHeader=new ArrayList<ClaimsHistoryNewSearchModel>();*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
List<String> historyResult = new ArrayList<String>();
historyResult.add((jsonObject.get("AdmissionDate").toString()));
historyResult.add((jsonObject.get("DischargeDate").toString()));
//AdmissionDate= exact name to ur json response from server
listDataHeader.add(KeyString);
listDataChild.put(KeyString, historyResult);
}
} catch (Exception e) {
e.printStackTrace();
}
return resResult;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String result) {
if (progressDialog != null && progressDialog.isShowing() == true) {
progressDialog.dismiss();
if (result.equals("[]")) {
Toast.makeText(mContext, "No Details found!!",
Toast.LENGTH_LONG).show();
} else
// Log.i("Result:", result);
// Log.i("listDataHeader:", listDataHeader.toString());
// Log.i("listDataChild:", listDataChild.toString());
listAdapter = new ClaimHistoryNewAdapter(getActivity(), listDataHeader, listDataChild);
if (listDataHeader != null && listDataHeader.size() > 0 && listDataChild != null && listDataHeader.size() > 0) {
expListView.setAdapter(listAdapter);
} else {
// setting list adapter
tClaimHistory.setVisibility(View.VISIBLE);
}
}
}
public String NewHistoryService(String serviceUrl) {
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
//ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
//response.append("Error");
}
Log.v("Response:", response.toString());
return response.toString();
}
}
}
Use this JsonParser class
Hope it will help you
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONParser {
public JSONParser() {
}
public String makeServiceCall(String serviceUrl) {
Boolean registered = false;
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
registered = true;
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
/* ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
response.append("Error");*/
}
Log.v("Response:", response.toString());
return response.toString();
}
}
setConnectionTimeout(Your Time);

Categories

Resources