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);
}
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 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;
}
I've used a ListView to show my data from wamp server using mysql, also using JSON parsing , the following is my code....
public class JSONTask extends AsyncTask<String, String, List<PumpModel>> {
#Override
protected List<PumpModel> 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 finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("server_response");
List<PumpModel> pumpModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
PumpModel pumpModel = new PumpModel();
pumpModel.setPump(finalObject.getString("Pump"));
pumpModel.setAvailable(finalObject.getString("Available"));
pumpModelList.add(pumpModel);
}
return pumpModelList;
} 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<PumpModel> result) {
super.onPostExecute(result);
//TODO need to set the data to the list
PumpAdapter adapter = new PumpAdapter(getApplicationContext(), R.layout.row, result);
lvPump.setAdapter(adapter);
}
}
public class PumpAdapter extends ArrayAdapter {
private List<PumpModel> pumpModelList;
private int resource;
private LayoutInflater inflater;
public PumpAdapter(Context context, int resource, List<PumpModel> objects) {
super(context, resource, objects);
pumpModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView ivIcon;
TextView tvPump;
ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
tvPump = (TextView) convertView.findViewById(R.id.tvPump);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(pumpModelList.get(position).getAvailable(), ivIcon); // Default options will be used
tvPump.setText(pumpModelList.get(position).getPump());
return convertView;
}
}
Now I want to create an onclick listener for my list view, which can be used to open another activity, and show the Description of pumps in TextView.
In your activity, where you defined your listview
you can write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
public ItemClicked getItem(int position){
return items.get(position);
}
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
In your activity, where you defined your listview
you write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
in your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
Implement an OnItemClickListener (Best place to implement is in your adapter) & on your ListView object setOnItemClickListener(yourItemClickListener);
Refs :
https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
https://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
i have created a custom alertbar on context menu, which is on the list viewed from json parsing. what i want is to get a details(name of the specific person on which the context menu is opened). i want to set Text in the on the alertbar.
Thank you very much for help.
enter code here
public class MyConnectionAsyncTask extends AsyncTask> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Connecting...");
progressDialog.show();
}
#Override
protected List<MyconnectionManager> doInBackground(String... params) {
try {
URL url = new URL(params[0]);// taking params from execute method
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();//opening connection
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));//putting data into buffer from input stream
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
String json_str = result.toString();
JSONObject parentObject = new JSONObject(json_str);
JSONArray parentArray = parentObject.getJSONArray("result_array");//ARRAY name from API will come here
ArrayList<MyconnectionManager> connectionManagerList = new ArrayList<MyconnectionManager>();//created a list bc we have list of connections
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MyconnectionManager myconnectionManager = new MyconnectionManager(getActivity());
myconnectionManager.setFullname_myConnection(finalObject.getString("fullname"));
myconnectionManager.setProfilePic_myConnection(finalObject.getString("profile_pic"));
myconnectionManager.setPosition_myconnection(finalObject.getString("position"));
myconnectionManager.setCompany_myConnection(finalObject.getString("company"));
myconnectionManager.setLocation_myConnection(finalObject.getString("location"));
connectionManagerList.add(myconnectionManager);//adding to list
}
return connectionManagerList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<MyconnectionManager> result) {
super.onPostExecute(result);
progressDialog.dismiss();
MyConnectionAdapter adapter = new MyConnectionAdapter(getActivity(), R.layout.single_row_my_connections, result);//creating adpater here
connectionList.setAdapter(adapter);
}
}
adpater Class is below
public class MyConnectionAdapter extends ArrayAdapter {
private List<MyconnectionManager> myconnectionManagerList;
private int resource;
LayoutInflater inflater;
public MyConnectionAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
this.resource = resource;// resource has the layout view so we can also give resource below instead of layout
myconnectionManagerList = objects;
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_my_connections, null);//we can give resource here
}
ImageView imageView;
TextView name, company, location, position_company;
imageView = (ImageView) convertView.findViewById(R.id.iv_profile_pic_myconnection);
name = (TextView) convertView.findViewById(R.id.tvname_myconncetion);
company = (TextView) convertView.findViewById(R.id.tvCompany_myconnection);
location = (TextView) convertView.findViewById(R.id.tvlocation_myconnections);
position_company = (TextView) convertView.findViewById(R.id.tvPosition_myconnection);
ImageLoader.getInstance().displayImage(myconnectionManagerList.get(position).getProfilePic_myConnection(), imageView);
name.setText(myconnectionManagerList.get(position).getFullname_myConnection());
company.setText(myconnectionManagerList.get(position).getCompany_myConnection());
location.setText(myconnectionManagerList.get(position).getLocation_myConnection());
position_company.setText(myconnectionManagerList.get(position).getPosition_myconnection());
return convertView;
}
}
context menu is below
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderIcon(R.drawable.small_logo);
menu.setHeaderTitle("Choose Action");
menu.add(0, 1, 0, "Send Message");
menu.add(0,2,1,"Remove Connection");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId()==1){
Toast.makeText(getActivity(),"Send Message",Toast.LENGTH_SHORT).show();
View view=LayoutInflater.from(getActivity()).inflate(R.layout.send_message_layout,null,false);
final EditText et_sub= (EditText) view.findViewById(R.id.et_sub_send_Message);
final EditText et_msg= (EditText) view.findViewById(R.id.etMessage_send_Message);
TextView name= (TextView) view.findViewById(R.id.tv_name_send_message);
name.setText("To: ");//name of user will come here
AlertDialog.Builder ab=new AlertDialog.Builder(getActivity());
ab.setTitle("Send Message");
ab.setView(view);
ab.setNegativeButton("Cancel", null);
ab.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String sub = et_sub.getText().toString();
String msg = et_msg.getText().toString();
Toast.makeText(getActivity(), sub + " " + msg, Toast.LENGTH_SHORT).show();
}
});
ab.show();
}else {
Toast.makeText(getActivity(),"Remove Connection",Toast.LENGTH_SHORT).show();
}
return true;
}
You can use
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
String nameoOfUser = ((TextView)info.targetView.findViewById(R.id.YOUR_TEXTVIEW_ID)).getText().toString();
name.setText("To: " + nameoOfUser );
}
TextView textViewItem = (TextView)convertView.findViewById(R.id.textViewItem);
textViewItem.setText("your text");
I would like to know if it is possible to load an image inside a ListView directly from the web, when the URL is stocked inside a json.
Edit : Solved, It is possible to use an AsyncTask
public class ParseImage extends AsyncTask<Object, String, Drawable> {
private ProgressBar pd;
private ImageView imv;
private int position;
public ParseImage(int position, ImageView imv, ProgressBar pd2) {
this.position = position;
this.imv = imv;
this.pd = pd2;
}
#Override
public Drawable doInBackground(Object... params) {
Drawable d = null;
try {
d = Drawable.createFromStream(
(InputStream) new URL(list.get(position).get("Cover"))
.getContent(), "src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
public void onPostExecute(Drawable result) {
if (result != null && imv != null) {
pd.setVisibility(View.INVISIBLE);
imv.setImageDrawable(result);
}
}
}
}
You need to create your own custom Listview to show more than a String.Here is a piece of code you can refer:
MovieAdaptor.java:
public class MovieAdaptor extends ArrayAdapter<Movie> {
Context context;
int layoutResourceId;
ArrayList<Movie> movieArrayList = new ArrayList<Movie>();
public MovieAdaptor(Context context, int layoutResourceId, ArrayList<Movie> movies) {
super(context, layoutResourceId, movies);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.movieArrayList = movies;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ContactHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.thumbnail = (ImageView) row.findViewById(R.id.imageThumbnail);
holder.title = (TextView) row.findViewById(R.id.MovieTitle);
holder.synopsis = (TextView) row.findViewById(R.id.synopsis);
row.setTag(holder);
} else {
holder = (ContactHolder) row.getTag();
}
holder.title.setText(movieArrayList.get(position).title);
holder.synopsis.setText(movieArrayList.get(position).synopsis);
newAsyncDownloadImage(holder.thumbnail).execute(movieArrayList.get(position).posters.get("thumbnail"));
return row;
}
static class ContactHolder {
ImageView thumbnail;
TextView title;
TextView synopsis;
}
}
Activity.class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
moviesListView = (ListView) findViewById(R.id.list_movies);
moviesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position > HEADER) {
Intent intent = new Intent(getBaseContext(), MovieActivity.class);
intent.putExtra(MOVIE_OBJECT, movieArrayList.get(position - 1));
startActivity(intent);
}
}
});
View header = (View) getLayoutInflater().inflate(R.layout.listview_row_header, null);
moviesListView.addHeaderView(header);
movieAdaptor = new MovieAdaptor(this, R.layout.listview_row_item, movieArrayList);
moviesListView.setAdapter(movieAdaptor);
AsyncDownloadImage.java:
public class AsyncDownloadImage extends AsyncTask<Object, Object, Object> {
ImageView iv;
private HttpURLConnection connection;
private InputStream is;
private Bitmap bitmap;
public AsyncDownloadImage(ImageView mImageView) {
iv = mImageView;
}
#Override
protected Object doInBackground(Object... params) {
URL url;
try {
url = new URL((String) params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if (null != result) {
iv.setImageBitmap((Bitmap) result);
} else {
iv.setBackgroundResource(R.drawable.ic_launcher);
}
}
}
}
Can you send the return of
JSONfunction.getJSONfromURL("http://colmarmagazine.ctai.fr/issues.php");
Please ?
I think it's a bad parting ! Because you have :
Unable to decode stream: java.io.FileNotFoundException: /http:/colmarmagazine.ctai.fr/content/numerodemo/numerodemo.png: open failed: ENOENT (No such file or directory)
and a "/" too much in the url for your cover !