I am loading JSON from server but the app crashes if the internet is not available. How to fix this problem? I have added try catch in most part. Unable to find the problem. lvMovies.setAdapter(adapter); gives error when internet is not available. Code works fine when internet is available
public class JSONTest extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private ListView lvMovies;
private ProgressDialog dialog;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsontest);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeMovieHits);
swipeRefreshLayout.setOnRefreshListener(this);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView) findViewById(R.id.lvMovies);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
//new JSONTask().execute("http://ankushkapoor2016.16mb.com/ankush/myjson.txt");
//new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");
}
#Override
public void onRefresh() { //SwipeRefreshLayout Refresh Listener
try {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
} catch (Exception e) {
Toast.makeText(JSONTest.this, e.getMessage() + "\n\n" + e.getCause(), Toast.LENGTH_LONG).show();
}
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> 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);
}
String finalJson1 = buffer.toString();
SharedPreferences sharedPreferences = getSharedPreferences("JSON_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("json", finalJson1);
editor.commit();
String finalJson=sharedPreferences.getString("json","N/A");
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float) finalObject.getDouble("rating"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setTagline(finalObject.getString("tagline"));
movieModel.setImage(finalObject.getString("image"));
movieModel.setStory(finalObject.getString("story"));
List<MovieModel.Cast> castList = new ArrayList<>();
for (int j = 0; j < finalObject.getJSONArray("cast").length(); j++) {
MovieModel.Cast cast = new MovieModel.Cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
movieModel.setCastList(castList);
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> s) {
super.onPostExecute(s);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, s);
lvMovies.setAdapter(adapter);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
}
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagline);
holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar;
progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
try {
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year: " + movieModelList.get(position).getYear());
holder.tvDuration.setText(movieModelList.get(position).getDuration());
holder.tvDirector.setText(movieModelList.get(position).getDirector());
holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);
StringBuffer stringBuffer = new StringBuffer();
for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText(stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage() + "\n" + e.getCause(), Toast.LENGTH_SHORT).show();
}
return convertView;
}
class ViewHolder {
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_json, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.jsonRefresh) {
try {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
return true;
} catch (Exception e) {
Toast.makeText(JSONTest.this, e.getMessage() + "\n\n" + e.getCause(), Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
}
To prevent crash you should check is device have internet connection, to do that you can use:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need to add to your AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you provide logcat message, then maybe I can tell you more about your problem.
Your problem is that you are returning a null arraylist when the internet exceptions are caught. So, the onPostExecute gets null, then the adapter gets null.
If you don't want a null value, pre-declare an empty list and always return it.
Then, the app won't crash, but you will see no data populate in the list, so you may want to do some additional validation that internet is available.
#Override
protected List<MovieModel> doInBackground(String... params) {
List<MovieModel> movieModelList = new ArrayList<>();
try {
// TODO: Stuff
return movieModelList;
} catch ( ... ) {
} finally {
}
return movieModelList;
}
Related
I written json and created url with the help of git.but now i am not able to get the requested data as result is coming null.Please help me in that
public class TestActivity extends AppCompatActivity {
Button btnHit;
ListView moviList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btnHit= (Button) findViewById(R.id.btn);
moviList=(ListView)findViewById(R.id.lvMovie);
/* btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/050254dd568a972442cdff0d984c396b9b340b7f/movie.json");
}
});*/
}
public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson=buffer.toString();
JSONObject parentObj=new JSONObject(finalJson);
JSONArray parentArray=parentObj.getJSONArray("movies");
List<MovieModel> movieModelList=new ArrayList<>();
for (int i=0; i<parentArray.length() ; i++)
{
JSONObject finalObj=parentArray.getJSONObject(i);
MovieModel movieModel=new MovieModel();
movieModel.setMovie(finalObj.getString("movie"));
movieModel.setYear(finalObj.getInt("year"));
movieModel.setRating((float) finalObj.getDouble("rating")/2);
movieModel.setStory(finalObj.getString("story"));
//movieModel.setImage(finalObj.getString("image"));
List<MovieModel.Caste> casteList=new ArrayList<>();
for (int j=0;j<finalObj.getJSONArray("caste").length();j++){
MovieModel.Caste caste=new MovieModel.Caste();
caste.setName(finalObj.getJSONArray("caste").getJSONObject(j).getString("name"));
casteList.add(caste);
}
movieModel.setCasteList(casteList);
movieModelList.add(movieModel);
Log.d("hi","list+++++++++++++++++++++++" +movieModelList);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
if (result==null){
Log.d("Hi","sorry no result");
return;
}
//set data to recycler view
MovieAdapter adapter=new MovieAdapter(getApplicationContext(),R.layout.movie_cell,result);
moviList.setAdapter(adapter);
}
}
public class MovieAdapter extends ArrayAdapter{
private List<MovieModel> movieModelList=new ArrayList<MovieModel>();
private int resource;
LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList=objects;
this.resource=resource;
inflater= (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null)
{
convertView=inflater.inflate(resource,null);
}
ImageView movieIcon;
TextView name;
TextView year;
RatingBar ratingBar;
TextView tvCaste;
TextView story;
movieIcon= (ImageView) convertView.findViewById(R.id.place_image);
name= (TextView) convertView.findViewById(R.id.tv_name);
year= (TextView) convertView.findViewById(R.id.tv_year);
ratingBar= (RatingBar) convertView.findViewById(R.id.rt_ratebar);
tvCaste= (TextView) convertView.findViewById(R.id.tv_cast);
story= (TextView) convertView.findViewById(R.id.tv_story);
name.setText(movieModelList.get(position).getMovie());
year.setText(" year -"+ movieModelList.get(position).getYear());
StringBuffer stringBuffer=new StringBuffer();
for (MovieModel.Caste caste: movieModelList.get(position).getCasteList()){
stringBuffer.append(caste.getName() + ",");
}
tvCaste.setText(stringBuffer);
story.setText(movieModelList.get(position).getStory());
// rating bar
ratingBar.setRating(movieModelList.get(position).getRating()/2);
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar_profile,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.refresh){
String url="https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/9e3de75ffa48c70f81ad07b7623e5fd0789142f0/movie.json";
Log.d("url____",url);
new JSONTask().execute(url);
return true;
}
return super.onOptionsItemSelected(item);
}
}
It is working fine on my device.
Few doubts regarding your scenario.
Do you have internet permission set in manifest.xml file
Are you using emulator for running application?
If your are using WiFi, try reconnecting and check again.
Are you using VPN? If yes then disconnect from VPN and try again.
Thanks
I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..
if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html
Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}
I am building a news app and I want to cache a JSON response to use when there is no network. I tried a lot of ways but it did not work for me.
My async task and my adapter are another side problem when the list loads new items it goes to the top of the screen and after that it adds the items. How can I fix this?
private class jsontask extends AsyncTask<String, String, List<newsmodel>> {
#Override
protected List<newsmodel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = 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);
}
String finaljson = buffer.toString();
JSONObject parentobject = new JSONObject(finaljson);
JSONArray parentarray = parentobject.getJSONArray("articles");
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalobject = parentarray.getJSONObject(i);
newsmodel newsmodel = new newsmodel();
newsmodel.setAuthor(finalobject.getString("author"));
if (finalobject.isNull("author")) {
}
newsmodel.setDescription(finalobject.getString("description"));
newsmodel.setTitle(finalobject.getString("title"));
newsmodel.setImage(finalobject.getString("urlToImage"));
newsmodel.setUrl(finalobject.getString("url"));
newsmodel.setPublishedAt(finalobject.getString("publishedAt"));
moviemodelList.add(newsmodel);
}
return moviemodelList;
} catch (MalformedURLException e) {
e.printStackTrace();
return moviemodelList;
} catch (IOException e) {
e.printStackTrace();
return moviemodelList;
} catch (JSONException e) {
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<newsmodel> result) {
super.onPostExecute(result);
newsadapter adapter = new newsadapter(getApplicationContext(), R.layout.row, result);
lvnews.setAdapter(adapter);
}
}
public class newsadapter extends ArrayAdapter {
private List<newsmodel> moviemodelList;
private int resource;
private LayoutInflater inflater;
public newsadapter(Context context, int resource, List<newsmodel> objects) {
super(context, resource, objects);
moviemodelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewholder holder = null;
if (convertView == null) {
holder = new viewholder();
convertView = inflater.inflate(resource, null);
holder.newsimage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.title = (TextView) convertView.findViewById(R.id.textView2);
holder.description = (TextView) convertView.findViewById(R.id.textView3);
holder.author = (TextView) convertView.findViewById(R.id.textView4);
holder.publishdate = (TextView) convertView.findViewById(R.id.textView5);
holder.dotsmenu = (ImageButton) convertView.findViewById(R.id.dots);
convertView.setTag(holder);
} else {
holder = (viewholder) convertView.getTag();
}
final ProgressBar progressBar;
progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(moviemodelList.get(position).getImage(), holder.newsimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(view.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(view.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(view.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(view.GONE);
}
});
holder.title.setText(moviemodelList.get(position).getTitle());
holder.description.setText(moviemodelList.get(position).getDescription());
holder.author.setText(moviemodelList.get(position).getAuthor());
holder.publishdate.setText(moviemodelList.get(position).getPublishedAt());
final viewholder finalHolder = holder;
holder.dotsmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(page.this, finalHolder.dotsmenu);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.dots_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, moviemodelList.get(position).getUrl());
sendIntent.setType("text/plain");
startActivity(sendIntent);
return true;
}
return false;
}
});
popup.show();
}
});
lvnews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(page.this, webview.class);
intent.putExtra("Link", moviemodelList.get(position).getUrl());
startActivity(intent);
}
});
return convertView;
}
Make a class for testing whether net connection is available or not .
ConnectionDetector.java
public class ConnectionDetector {
public Context context;
public ConnectionDetector(Context context)
{
this.context=context;
}
public boolean isConnecting() {
ConnectivityManager check=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (check!=null){
NetworkInfo[] infos=check.getAllNetworkInfo();
for (int i=0;i<infos.length;i++)
{
if (infos[i].getState()== NetworkInfo.State.CONNECTED)
return true;
}}
return false;
}
}
Create an object ob of above class .
ConnectionDetector ob=new ConnectionDetector(getApplicationContext());
Declare these variables as global variables :
File httpCacheDir;
long httpCacheSize = 5 * 1024 * 1024;// In place of 5 you can use size in mb
HttpResponseCache cache;
Make a function cacher():
public void cacher()
{
httpCacheDir = getExternalCacheDir();
// Cache Size of 5MB
try {
// Install the custom Cache Implementation
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (Exception e) {
e.printStackTrace();
}
}
Just below the setContentView in onCreate ,add the following code :
cacher();
cache = HttpResponseCache.getInstalled();
if(cache != null) {
// If cache is present, flush it to the filesystem.
// Will be used when activity starts again.
cache.flush();
}
And here comes the final thing , below the url.openConnection line put the following snippet:
if (ob.isConnecting()){
connection.addRequestProperty("Cache-Control", "max-age=0");}
else{
connection.addRequestProperty("Cache-Control", "max-stale=" + 60*60*36);//In place of 36 , you can put hours for which cache is available
connection.setUseCaches(true);
}
trying to make a searchview works, with php and mysql.
user enters search query into search view/search bar to search for particular information, the query is sent to php file and result from php file is displayed on RecyclerView.
dont know whats wrong
MainActivity
public class MainActivity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVProd;
private AdapterProd mAdapter;
SearchView searchView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmain, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://192.168.0.2/prod-search.php");
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return("Erro");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
List<DataProd> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "Nenhum resultado encontrado", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataProd prodData = new DataProd();
prodData.nomep = json_data.getString("nomeprod");
prodData.marcap = json_data.getString("marcaprod");
prodData.pesop = json_data.getInt("pesoprod");
prodData.valorp = json_data.getInt("valorprod");
prodData.pratp = json_data.getInt("pratprod");
data.add(prodData);
}
mRVProd = (RecyclerView) findViewById(R.id.listaprodpreco);
mAdapter = new AdapterProd(MainActivity.this, data);
mRVProd.setAdapter(mAdapter);
mRVProd.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
Adapter
public class AdapterProd extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataProd> data= Collections.emptyList();
DataProd current;
int currentPos=0;
public AdapterProd(Context context, List<DataProd> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.containerprod, parent, false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder= (MyHolder) holder;
DataProd current=data.get(position);
myHolder.textnomep.setText(current.nomep);
myHolder.textmarcap.setText("Marca: " + current.marcap);
myHolder.textpesop.setText("Peso: " + current.pesop);
myHolder.textvalorp.setText("Rs " + current.valorp + "\\Und");
myHolder.textvalorp.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
myHolder.textpratp.setText("Prateleira: current.pratprod");
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textnomep;
TextView textmarcap;
TextView textpesop;
TextView textvalorp;
TextView textpratp;
public MyHolder(View itemView) {
super(itemView);
textnomep = (TextView) itemView.findViewById(R.id.textnomep);
textmarcap = (TextView) itemView.findViewById(R.id.textmarcap);
textpesop = (TextView) itemView.findViewById(R.id.textpesop);
textvalorp = (TextView) itemView.findViewById(R.id.textvalorp);
textpratp = (TextView) itemView.findViewById(R.id.textpratp);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "VocĂȘ clicou em um item", Toast.LENGTH_SHORT).show();
}
}
}
dont know what im doing wrong, keep getting this E/RecyclerView: No adapter attached; skipping layout, anyone can help?
Is there any chance that you are getting an exception while decoding the JSON and go directly to catch block, which skips the adapter initialization?
If you'd like to avoid that I'd suggest you to create an empty adapter set it to the recycler view when the UI initializes(in onCreate() for example), after that just have a method setData(List data) and use it to set the data after the async task finishes. In this case don't forget to call notifyDataSetChanged() when the data changes so that the recycler view is updated with the new data. This way you don't have to recreate the adapter each time you call the service.
PS: For your current code you will get that message each time the UI initializes as it doesn't have adapter attached. You should stop seeing this message once the async task finishes with no exceptions decoding the json.
I am trying to fetch data using AsyncTask & displaying into a ListView. It never calls getView(), I checked getCount() return always 0.
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
SourceAdapter adapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
adapter = new SourceAdapter(getActivity());
ListView listView = (ListView) rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
Log.d(LOG_TAG,"after list view set to adapter");
return rootView;
}
#Override
public void onStart() {
new FetchDataTask().execute();
super.onStart();
}
public class FetchDataTask extends AsyncTask<String, Void, SourceObject[]>{
private final String LOG_TAG = FetchDataTask.class.getSimpleName();
private SourceObject[] getSourceDataFromJson(String jsonStr)throws JSONException{
JSONArray jsonArray = new JSONArray(jsonStr);
SourceObject[] sourceObjects = new SourceObject[jsonArray.length()];
for (int i=0; i<jsonArray.length();i++){
sourceObjects[i] = new SourceObject(
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getString("message")
);
}
return sourceObjects;
}
#Override
protected SourceObject[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
String baseUrl = "https://api.github.com/repos/rails/rails/commits";
URL url = new URL(baseUrl);
Log.d(LOG_TAG,"URL IS "+url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonStr = buffer.toString();
Log.d(LOG_TAG,"JSON STRING "+jsonStr);
}catch (IOException e){
Log.e(LOG_TAG, "ERROR"+e);
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getSourceDataFromJson(jsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
SourceAdapter.java
public class SourceAdapter extends BaseAdapter {
private final String LOG_TAG = SourceAdapter.class.getSimpleName();
Context context;
ArrayList<SourceObject> objects = new ArrayList<SourceObject>();
public SourceAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
Log.d(LOG_TAG,"getCount called "+objects.size());
return objects.size();
}
#Override
public Object getItem(int position) {
Log.d(LOG_TAG,"getItem called");
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG,"get view method is called");
SourceObject sourceObject = (SourceObject) getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_source,parent,false);
}
TextView personName = (TextView) convertView.findViewById(R.id.person_name);
TextView commit = (TextView) convertView.findViewById(R.id.xxx);
TextView commitMessage = (TextView) convertView.findViewById(R.id.commit_message);
personName.setText(sourceObject.getPersonName());
commit.setText(sourceObject.getCommit());
commitMessage.setText(sourceObject.getCommitMessage());
return convertView;
}
}
Please help.
You are not setting data retrieved from AsyncTask to adapter.
Add this method to your adapter class:
public void setItems(SourceObject[] items) {
this.objects = new ArrayList<SourceObject>();
for(SourceObject item : items){
this.objects.add(item);
}
this.notifyDataSetChanged();
}
And change onPostExecute of AsyncTask to:
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.setItems(strings);
super.onPostExecute(strings);
}