I am trying to parse data from json using an API, but I don't know for what reasons when I am calculating the size of m_name3 it is showing 0 but the data is being parsed through the file. When putting toast at String name = o.getString("name"); it is showing the content of name string, so this means it is parsing the data but not storing in arraylist. I don't know why. Please help!
package com.example.amitc.pvrathome;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
public class msms extends AppCompatActivity {
String img_src;
private ArrayList<String> m_name3 = new ArrayList<>();
private ArrayList<String> m_release_year3 = new ArrayList<>();
private ArrayList<String> m_genre3 = new ArrayList<>();
private ArrayList<String> m_director3 = new ArrayList<>();
private ArrayList<String> m_rating3 = new ArrayList<>();
private ArrayList<String> m_actor3 = new ArrayList<>();
private ArrayList<String> m_desc3 = new ArrayList<>();
private ArrayList<String> m_imgsrc3 = new ArrayList<>();
StringRequest stringRequest;
Context mContext;
String url_all = "https://www.dropbox.com/s/ofzv2j16vq9ofmq/100MovieList.json?dl=1";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msms);
new getIncomingIntent().execute();
ImageView imageView = findViewById(R.id.msms_image);
mContext = this;
Glide.with(this)
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//txt.setText("Searching by: "+ query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
String uri = intent.getDataString();
final int index = Integer.parseInt(uri.replaceAll("[^0-9]", ""));
//
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(msms.this);
requestQueue.add(stringRequest);
Toast.makeText(this, "Index: "+ m_name3.size(), Toast.LENGTH_SHORT).show();
// TextView m_name = findViewById(R.id.msms_name);
// m_name.setText(m_name3.get(index));
//
// TextView m_name1 = findViewById(R.id.msms_name1);
// m_name1.setText(m_name3.get(index));
// // TextView m_year = (TextView) findViewById(R.id.msms_year);
// // m_year.setText(year);
//
// TextView m_genre = findViewById(R.id.msms_genre);
// m_genre.setText(m_genre3.get(index));
//
// TextView m_rating = findViewById(R.id.msms_rating);
// m_rating.setText(m_rating3.get(index));
//
// TextView m_desc = findViewById(R.id.msms_desc);
// m_desc.setText(m_desc3.get(index));
//
// TextView m_direc = findViewById(R.id.msms_direc);
// m_direc.setText(m_director3.get(index));
//
// TextView m_actor = findViewById(R.id.msms_actor);
// m_actor.setText(m_actor3.get(index));
// Glide.with(this)
// .load(img_src)
// .apply(new RequestOptions()
// .placeholder(R.drawable.rec)
// .dontAnimate()
// .error(R.drawable.movies))
// .into(imageView);
}
}
public class getIncomingIntent extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String name = getIntent().getStringExtra("names");
// String year = getIntent().getStringExtra("years");
String genre = getIntent().getStringExtra("genres");
String rating = getIntent().getStringExtra("ratings");
String desc = getIntent().getStringExtra("decss");
String director = getIntent().getStringExtra("direcs");
String actor = getIntent().getStringExtra("stars");
img_src = getIntent().getStringExtra("img1");
TextView m_name = (TextView) findViewById(R.id.msms_name);
m_name.setText(name);
TextView m_name1 = (TextView) findViewById(R.id.msms_name1);
m_name1.setText(name);
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = (TextView) findViewById(R.id.msms_genre);
m_genre.setText(genre);
TextView m_rating = (TextView) findViewById(R.id.msms_rating);
m_rating.setText(rating);
TextView m_desc = (TextView) findViewById(R.id.msms_desc);
m_desc.setText(desc);
TextView m_direc = (TextView) findViewById(R.id.msms_direc);
m_direc.setText(director);
TextView m_actor = (TextView) findViewById(R.id.msms_actor);
m_actor.setText(actor);
return null;
}
}
}
EDITED:
package com.example.amitc.pvrathome;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
public class msms extends AppCompatActivity {
String img_src;
private ArrayList<String> m_name3 = new ArrayList<>();
private ArrayList<String> m_release_year3 = new ArrayList<>();
private ArrayList<String> m_genre3 = new ArrayList<>();
private ArrayList<String> m_director3 = new ArrayList<>();
private ArrayList<String> m_rating3 = new ArrayList<>();
private ArrayList<String> m_actor3 = new ArrayList<>();
private ArrayList<String> m_desc3 = new ArrayList<>();
private ArrayList<String> m_imgsrc3 = new ArrayList<>();
StringRequest stringRequest;
Context mContext;
String url_all = "https://www.dropbox.com/s/ofzv2j16vq9ofmq/100MovieList.json?dl=1";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msms);
new getIncomingIntent().execute();
ImageView imageView = findViewById(R.id.msms_image);
mContext = this;
Glide.with(this)
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//txt.setText("Searching by: "+ query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
String uri = intent.getDataString();
final int index = Integer.parseInt(uri.replaceAll("[^0-9]", ""));
//
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
ProgressDialog progress;
progress= new ProgressDialog(mContext);
progress.setMessage("Loading...");
progress.show();
TextView m_name = findViewById(R.id.msms_name);
m_name.setText(m_name3.get(index));
TextView m_name1 = findViewById(R.id.msms_name1);
m_name1.setText(m_name3.get(index));
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = findViewById(R.id.msms_genre);
m_genre.setText(m_genre3.get(index));
TextView m_rating = findViewById(R.id.msms_rating);
m_rating.setText(m_rating3.get(index));
TextView m_desc = findViewById(R.id.msms_desc);
m_desc.setText(m_desc3.get(index));
TextView m_direc = findViewById(R.id.msms_direc);
m_direc.setText(m_director3.get(index));
TextView m_actor = findViewById(R.id.msms_actor);
m_actor.setText(m_actor3.get(index));
ImageView imageView = findViewById(R.id.msms_image);
Glide.with(getApplicationContext())
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
progress.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(msms.this);
requestQueue.add(stringRequest);
}
}
public class getIncomingIntent extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String name = getIntent().getStringExtra("names");
// String year = getIntent().getStringExtra("years");
String genre = getIntent().getStringExtra("genres");
String rating = getIntent().getStringExtra("ratings");
String desc = getIntent().getStringExtra("decss");
String director = getIntent().getStringExtra("direcs");
String actor = getIntent().getStringExtra("stars");
img_src = getIntent().getStringExtra("img1");
TextView m_name = (TextView) findViewById(R.id.msms_name);
m_name.setText(name);
TextView m_name1 = (TextView) findViewById(R.id.msms_name1);
m_name1.setText(name);
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = (TextView) findViewById(R.id.msms_genre);
m_genre.setText(genre);
TextView m_rating = (TextView) findViewById(R.id.msms_rating);
m_rating.setText(rating);
TextView m_desc = (TextView) findViewById(R.id.msms_desc);
m_desc.setText(desc);
TextView m_direc = (TextView) findViewById(R.id.msms_direc);
m_direc.setText(director);
TextView m_actor = (TextView) findViewById(R.id.msms_actor);
m_actor.setText(actor);
return null;
}
}
}
Since your stringRequest runs on a different thread, you can't be sure if you already have the response by the time you are showing the toast, so you should have a look at the size only after you have the response.
In short, move the toast inside of onResponse:
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
Toast.makeText(msms.this, "Index: "+ m_name3.size(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
Related
PLEASE HELP, WHAT IS WRONG WITH MY CODE, IT DISPLAYS NOTHING BUT ZEROS AND NULL
I already search through tutorials, i even copied the whole code but i cant get the data from this API, my textviews on int are returning zeros and my textviews on string are returning null after a press the update button.
here is my api link = api link
here is the result
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("All");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cases = jsonArray.getJSONObject(i);
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I don't know what is the problem here, can someone help
I already fixed it thank you so much.
my solution is I removed JsonArray.
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
//JSONArray jsonArray = response.getJSONArray();
for (int i = 0; i < response.length(); i++) {
JSONObject cases = response.getJSONObject("All");
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I replaced
JSONObject cases = jsonArray.getJSONObject(i);
with
JSONObject cases = response.getJSONObject("All");
and removed
JSONArray jsonArray = response.getJSONArray();
because it is not necessary.
I am trying to use if else in a spinner layout in android. But the if condition is never accepted with a given condition.
Id of spinner is stateView.
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The same code works everywhere else in the block.
I assume the problem is in
if(obj.getString("state").equals(State))
If it is used if(true) the block works correctly, that means code is reaching there but there is a problem in the condition applied int the if statement.
even the below code is not working
if(obj.getString("state").equals("Delhi"))
this code is working outside the listener
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)){
Log.d("error","working");
}
The whole code for reference
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.VoiceInteractor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView stateActiveCases, stateConfirmed, stateDeceased, stateRecovered, cChanges, rChanges, dChanges;
String State;
Spinner stateView;
FusedLocationProviderClient fusedLocationProviderClient;
RecyclerView recyclerView;
RecyclerView.Adapter<DistrictAdapter.ViewHolder> mAdapter;
RecyclerView.LayoutManager layoutManager;
List<Districts> districtsList;
ArrayList<String> States;
#SuppressLint("SourceLockedOrientationActivity")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
districtsList = new ArrayList<>();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
final TextView Total = findViewById(R.id.textView4);
final TextView Recovered = findViewById(R.id.textView5);
final TextView Death = findViewById(R.id.textView6);
final TextView TodayCases = findViewById(R.id.textView7);
final TextView TodayDeath = findViewById(R.id.textView8);
final TextView ActiveCases = findViewById(R.id.textView10);
stateActiveCases = findViewById(R.id.textView29);
stateView = findViewById(R.id.spinner);
stateConfirmed = findViewById(R.id.textView26);
stateRecovered = findViewById(R.id.textView27);
stateDeceased = findViewById(R.id.textView28);
cChanges = findViewById(R.id.textView14);
rChanges = findViewById(R.id.textView15);
dChanges = findViewById(R.id.textView16);
States = new ArrayList<>();
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://coronavirus-19-api.herokuapp.com/countries/india", null, objectResponse -> {
try {
int cases = objectResponse.getInt("cases");
int recovered = objectResponse.getInt("recovered");
int deaths = objectResponse.getInt("deaths");
int todayCases = objectResponse.getInt("todayCases");
int todayDeaths = objectResponse.getInt("todayDeaths");
int activeCases = objectResponse.getInt("active");
Total.setText(String.valueOf(cases));
Death.setText(String.valueOf(deaths));
Recovered.setText(String.valueOf(recovered));
String tc = ("+" + todayCases);
String td = ("+" + todayDeaths);
TodayCases.setText(tc);
TodayDeath.setText(td);
ActiveCases.setText(String.valueOf(activeCases));
} catch (JSONException ex) {
ex.printStackTrace();
}
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonObjectRequest);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2199);
} else {
getLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 2199) {
getLocation();
}
}
private void getLocation() {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task -> {
Location location = task.getResult();
if (location != null) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1
);
stateData(addresses.get(0).getAdminArea(), addresses.get(0).getLocality());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://api.covidindiatracker.com/state_data.json", null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)) {
stateActiveCases.setText(String.valueOf(obj.getInt("active")));
stateConfirmed.setText(String.valueOf(obj.getInt("confirmed")));
stateRecovered.setText(String.valueOf(obj.getInt("recovered")));
stateDeceased.setText((String.valueOf(obj.getInt("deaths"))));
String stateCChanges, stateRChanges, stateDChanges;
stateCChanges = "+" + obj.getInt("cChanges");
stateRChanges = "+" + obj.getInt("rChanges");
stateDChanges = "+" + obj.getInt("dChanges");
cChanges.setText(stateCChanges);
rChanges.setText(stateRChanges);
dChanges.setText(stateDChanges);
JSONArray array = obj.getJSONArray("districtData");
for (int j = 0; j < array.length(); j++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(j);
if (obj1.getString("name").equals(cityName)) {
districts.setName(obj1.getString("name"));
districts.setConfirmed((obj1.getInt("confirmed")));
districtsList.add(districts);
}
}
for (int k = 0; k < array.length(); k++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(k);
if (obj1.getString("name").equals(cityName)) {
continue;
}
districts.setName(obj1.getString("name"));
districts.setConfirmed(obj1.getInt("confirmed"));
districtsList.add(districts);
}
}
String state=obj.getString("state");
States.add(state);
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
((TextView )parent.getChildAt(0)).setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.colorAccent));
((TextView)parent.getChildAt(0)).setTextSize(16);
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, States);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateView.setAdapter(arrayAdapter);
int spinner = arrayAdapter.getPosition(stateName);
stateView.setSelection(spinner);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new DistrictAdapter(districtsList);
recyclerView.setAdapter(mAdapter);
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonArrayRequest);
}
}
I want to move the if statement inside the listener such that when I select a state the data for that state is displayed. right now I am getting state data from the parameter which fetches data from GPS location.
Check the whole project on
Github
Any other suggestions are welcome.
Thanks in advance.
I have a Recycler View which uses AsyncTask to populate UI.
Currently it retrieves all the data from the DB and displays it in one shot, but
I want to retrieve only 15 records in one go and after the scroll ends I want to load more 15 records and so on...can anybody please help. I have pasted the code below:
FeedActivity.java
package com.bbau.ankit.test_splash;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Window;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class FeedListActivity extends Activity {
private static final String TAG = "RecyclerViewExample";
private List<FeedItem> feedItemList = new ArrayList<FeedItem>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Allow activity to show indeterminate progressbar */
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.news);
/* Initialize recyclerview */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.BLACK).build());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
/*Downloading data from below url*/
final String url = "http://192.168.170.72/bbau_news.php?before=1&after=5";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(FeedListActivity.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("NEWS");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedItem>();
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("news_desc"));
item.setDescription(post.optString("Date"));
item.setUrl(post.optString("News"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
MyRecyclerAdapter.java
package com.bbau.ankit.test_splash;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.style.AlignmentSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<FeedListRowHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public FeedListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
FeedListRowHolder mh = new FeedListRowHolder(v);
mh.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("List Size", Integer.toString(getItemCount()));
TextView redditUrl = (TextView) v.findViewById(R.id.url);
String postUrl = redditUrl.getText().toString();
Log.d("The URL:", postUrl);
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("url", postUrl);
mContext.startActivity(intent);
}
});
return mh;
}
#Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {
final FeedItem feedItem = feedItemList.get(i);
feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
feedListRowHolder.description.setText(feedItem.getDescription());
feedListRowHolder.url.setText(feedItem.getUrl());
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
Of course you can use Recycler view and EndlessScrool as a combination like this..
Here is a sample
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
Log.v("...", "Last Item Wow !");
}
}
}
});
Don't forget to add
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
Here is a Github example: EndlessRecyclerOnScrollListener
I have a table in the server and I want to retrieve specific records based on email address sent from android java code.
The email address is stored in global variable and I can get its value but I don't know how to send its value to the server and get the records.
my code retrieves all the records from the table
Please Help me to do it, I tried to do it for 3 days but with no solution
this is my PHP code :
<?php
$objConnect = mysql_connect("****","******","******");
$objDB = mysql_select_db("******");
$strSQL = "SELECT * FROM Appointment ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
echo json_encode($resultArray);
?>
this is my java code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ServicesBMWGarageActivity extends Activity {
private ClipData myClip;
private ClipboardManager myClipboard;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.services_bmw_garage);
GlobalClass globalVariable = (GlobalClass) getApplicationContext();
// Get email from global/application context
final String Email = globalVariable.getEmail();
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
String url = "http://ec2-54-148-64-28.us-west-2.compute.amazonaws.com/Codiad/workspace/BMWdatabase/MyAppointments.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("A_ID", c.getString("A_ID"));
map.put("A_Model", c.getString("A_Model"));
map.put("A_Services", c.getString("A_Services"));
map.put("A_DATE", c.getString("A_DATE"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(ServicesBMWGarageActivity.this, MyArrList, R.layout.activity_column,
new String[] {"A_ID", "A_Model", "A_Services", "A_DATE"}, new int[] {R.id.ColMemberID, R.id.ColName, R.id.ColTel,R.id.Coldate });
lisView1.setAdapter(sAdap);
final AlertDialog.Builder viewDetail = new AlertDialog.Builder(this);
// OnClick Item
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView,
int position, long mylng) {
String A_ID1 = MyArrList.get(position).get("A_ID")
.toString();
String Type1 = MyArrList.get(position).get("A_Model")
.toString();
String Model1 = MyArrList.get(position).get("A_Services")
.toString();
String Model2 = MyArrList.get(position).get("A_DATE")
.toString();
final String phoneNumber = MyArrList.get(position).get("A_ID")
.toString();
//String sMemberID = ((TextView) myView.findViewById(R.id.ColMemberID)).getText().toString();
// String sName = ((TextView) myView.findViewById(R.id.ColName)).getText().toString();
// String sTel = ((TextView) myView.findViewById(R.id.ColTel)).getText().toString();
viewDetail.setIcon(android.R.drawable.btn_star_big_on);
viewDetail.setTitle("Appointment Detail");
viewDetail.setMessage("ID : " + A_ID1 + "\n"
+ "Vehicle Model : " + Type1 + "\n" + "Service Type : " + Model1
+ "\n" + "Date : " + Model2);
viewDetail.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
String text = phoneNumber;
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Appointment ID Copied",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
viewDetail.show();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download results..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_home_page, menu);
return true;
}
}
I found the answer and the problem is solved
It was an easy solution
I just put my condition in the java code with no changes in the PHP code
the changes are :
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("V_ID", c.getString("V_ID"));
map.put("V_Type", c.getString("V_Type"));
map.put("V_Model", c.getString("V_Model"));
map.put("V_Year", c.getString("V_Year"));
map.put("V_Plate", c.getString("V_Plate"));
map.put("ImagePath", c.getString("ImagePath"));
map.put("Email", c.getString("Email"));
String email = c.getString("Email");
GlobalClass globalVariable = (GlobalClass) getApplicationContext();
// Get name and email from global/application context
final String Email = globalVariable.getEmail();
if(email.equals(Email))
MyArrList.add(map);
}
currently I am developing an Android Application (Native). In my application, I need to load many images and that cause a problem.
The problem is:
1. When I first open the app after deploy it on my android phone, it works fine. However, after I close the application (by clicking the back button), and then I open the application again, the app closed unexpectedly. When I check the logcat, I found out that it was closed because of OutOfMemory error.
2. Second problem: after I open my application, and I go to the next page, it also give me OutOfMemory error.
I guess, the problem occur because I load too many images. After I do some searching on the internet, it suggest me to do System.gc
But unfortunately, it did not work for me.
Here is my code:
Homepage_Activity.java
package dev.com.friseur;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.friseur.insert.AddComment;
import dev.friseur.rest.Photo;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class HomePage extends ActionBarActivity {
private String p_id = "1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Intent intent = getIntent();
int size = Integer.parseInt(intent.getStringExtra("size")) * 2;
LinearLayout hp = (LinearLayout)findViewById(R.id.homepage);
Photo photo = new Photo(hp, this, size);
photo.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The photo.execute() code will call an asynchronous task. Here it is:
package dev.friseur.rest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.com.friseur.RecognizeFace;
import dev.com.friseur.ViewPhoto;
import dev.friseur.insert.AddComment;
import dev.friseur.insert.AddLike;
import android.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.SystemClock;
import android.text.InputFilter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Photo extends AsyncTask<String, Void, String>{
private Context context;
private LinearLayout homepage;
private int size;
private String sessionUname;
private String sessionUserid;
private File file;
private ArrayList<String> photo_id;
private ArrayList<String> imageName;
private ArrayList<String> date_upload;
private ArrayList<String> url_original;
private ArrayList<String> url_with_hair;
private ArrayList<String> caption;
private ArrayList<String> user_id;
private ArrayList<String> username;
private ArrayList<JSONArray> comments;
private ArrayList<Integer> totalcomment;
public Photo(LinearLayout homepage, Context context, int size){
this.context = context;
this.homepage = homepage;
this.size = size;
this.sessionUname = "testuser";
this.sessionUserid = "1";
photo_id = new ArrayList<String>();
imageName = new ArrayList<String>();
date_upload = new ArrayList<String>();
url_original = new ArrayList<String>();
url_with_hair = new ArrayList<String>();
caption = new ArrayList<String>();
user_id = new ArrayList<String>();
username = new ArrayList<String>();
comments = new ArrayList<JSONArray>();
totalcomment = new ArrayList<Integer>();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.43.8:8080/FriseurRest/WebService/GetPhotos");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
JSONObject json_data = new JSONObject(line);
photo_id.add(json_data.getString("p_id"));
imageName.add(json_data.getString("imagename"));
date_upload.add(json_data.getString("date_upload"));
url_original.add(json_data.getString("url_original"));
url_with_hair.add(json_data.getString("url_with_hair"));
caption.add(json_data.getString("caption"));
user_id.add(Integer.toString(json_data.getInt("user_id")));
username.add(json_data.getString("username"));
comments.add(json_data.getJSONArray("photoComments"));
totalcomment.add(json_data.getInt("total_comment"));
i++;
}
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onDestroy() {
System.gc();
Runtime.getRuntime().gc();
}
protected void onPostExecute(String p_id) {
for(int i = 0; i < imageName.size(); i++){
final int j = i;
LinearLayout photo = new LinearLayout(context);
photo.setOrientation(LinearLayout.VERTICAL);
photo.setPadding(0, 0, 0, 50);
LinearLayout postdesc = createPostDesc(i);
file = new File(Environment.getExternalStorageDirectory() + "/" + url_original.get(i), imageName.get(i));
Uri imgUri = Uri.fromFile(file);
ImageView img = new ImageView(context);
img.setImageURI(imgUri);
img.setMaxWidth(size);
img.setMinimumWidth(size);
img.setMaxHeight(size);
img.setMinimumHeight(size);
TextView tv = new TextView(context);
tv.setText(caption.get(i));
final LinearLayout showcomment = new LinearLayout(context);
showcomment.setOrientation(LinearLayout.VERTICAL);
showcomment.setPadding(0, 10, 0, 10);
try {
if(totalcomment.get(i) > 5){
LinearLayout more = new LinearLayout(context);
more.setPadding(0, 0, 0, 5);
TextView viewmore = new TextView(context);
viewmore.setTextColor(Color.GRAY);
viewmore.setText("View More Comments");
viewmore.setClickable(true);
viewmore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ViewPhoto.class);
intent.putExtra("size", size);
intent.putExtra("p_id", photo_id.get(j));
intent.putExtra("imageName", imageName.get(j));
intent.putExtra("date_upload", date_upload.get(j));
intent.putExtra("url_original", url_original.get(j));
intent.putExtra("url_with_hair", url_with_hair.get(j));
intent.putExtra("caption", caption.get(j));
intent.putExtra("user_id", user_id.get(j));
intent.putExtra("username", username.get(j));
context.startActivity(intent);
}
});
more.addView(viewmore);
showcomment.addView(more);
}
for(int k = 0; k < comments.get(i).length(); k++) {
//ArrayList<String> photoCom = comments.get(k);
//int userCom = photoCom.length();
JSONObject photoCom = comments.get(i).getJSONObject(k);
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(photoCom.getString("com_username"));
TextView showcom = new TextView(context);
showcom.setText(photoCom.getString("com_desc"));
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
} catch (Exception e) {
}
LinearLayout addcomment = createAddComment(i);
final EditText et_comment = new EditText(context);
et_comment.setHint("Add Comment");
et_comment.setMaxWidth(size*3/4);
et_comment.setMinimumWidth(size*3/4);
int maxLength = 150;
et_comment.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Button button_comment = new Button(context);
button_comment.setText("Post");
button_comment.setTextSize(15);
button_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String com = et_comment.getText().toString();
try{
AddComment ac = new AddComment(sessionUserid, com, photo_id.get(j));
ac.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(sessionUname);
TextView showcom = new TextView(context);
showcom.setText(com);
showcom.setAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in));
et_comment.setText("");
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
});
addcomment.addView(et_comment);
addcomment.addView(button_comment);
addcomment.setVisibility(View.GONE);
LinearLayout social = createSocialFeature(i, addcomment, et_comment);
photo.addView(postdesc);
photo.addView(img);
photo.addView(tv);
photo.addView(showcomment);
photo.addView(social);
photo.addView(addcomment);
homepage.addView(photo);
}
}
private LinearLayout createPostDesc(int i){
LinearLayout postdesc = new LinearLayout(context);
postdesc.setOrientation(LinearLayout.VERTICAL);
postdesc.setMinimumHeight(40);
TextView uname = new TextView(context);
uname.setText("#"+username.get(i));
TextView timeupload = new TextView(context);
timeupload.setText(date_upload.get(i));
if(i>0){
View separator = new View(context);
separator.setMinimumHeight(1);
separator.setBackgroundColor(Color.BLACK);
separator.setPadding(0, 10, 0, 0);
postdesc.addView(separator);
}
postdesc.addView(uname);
postdesc.addView(timeupload);
return postdesc;
}
private LinearLayout createSocialFeature(final int i, final LinearLayout addcomment, final EditText et_comment){
LinearLayout social = new LinearLayout(context);
social.setOrientation(LinearLayout.HORIZONTAL);
social.setMinimumHeight(40);
social.setPadding(0,10,10,0);
TextView tv_comment = new TextView(context);
tv_comment.setText("Add Comment");
tv_comment.setPadding(0, 0, 15, 0);
tv_comment.setClickable(true);
tv_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addcomment.setVisibility(View.VISIBLE);
et_comment.setFocusableInTouchMode(true);
et_comment.setFocusable(true);
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
});
final TextView tv_like = new TextView(context);
tv_like.setText("Like");
tv_like.setClickable(true);
tv_like.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String like = tv_like.getText().toString();
try{
AddLike lk = new AddLike(sessionUserid, like, photo_id.get(i));
lk.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(like.equals("Like")){
tv_like.setText("Unlike");
}
else{
tv_like.setText("Like");
}
}
});
social.addView(tv_comment);
social.addView(tv_like);
return social;
}
private LinearLayout createAddComment(int i){
LinearLayout addcomment = new LinearLayout(context);
addcomment.setId(Integer.parseInt(photo_id.get(i)));
addcomment.setOrientation(LinearLayout.HORIZONTAL);
addcomment.setPadding(0,20,0,0);
return addcomment;
}
}
This asynchronous task used to call the rest service.
What is wrong with my code? And how can I solve the OutOfMemory error. Any help would be appreciated. Thanks in advance
You can use lazyloading to fix this and follow this url for lazy loading:
https://github.com/nostra13/Android-Universal-Image-Loader
You can see my answer here.It will be useful to handle your bitmap efficiently.
How to make application more responsive which uses several bitmaps?