i want to create a dynamic GridView, and when i click to my options meny, i refresh my asyncTask, then i get all result's from postExecute, and notify my adapter to refresh! But i doesn't work HELP me please!
GridView grid;
ImageAdapter adapter;
ArrayList<String> arrayThumbs = new ArrayList<String>();
ArrayList<String> arrayBig_image = new ArrayList<String>();
ArrayList<String> arrayAuthor = new ArrayList<String>();
ArrayList<String> arrayDescription = new ArrayList<String>();
ArrayList<String> arrayDate = new ArrayList<String>();
String[] arraymThumbs;
String[] arrayBimages;
String[] arrayauthor;
String[] arraydescription;
String[] arraydate;
final static String TAG_ITEM = "img_list";
final static String TAG_THUMBNAILS = "thumbnail";
final static String TAG_BIG_IMAGE = "big_image";
final static String TAG_AUTHOR = "author";
final static String TAG_DESCRIPTION = "description";
final static String TAG_DATE = "event_date";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
backTask();
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ImageGallery.class);
intent.putExtra("position", position);
intent.putExtra("big_images", arrayBimages);
intent.putExtra("author", arrayauthor);
intent.putExtra("description", arraydescription);
intent.putExtra("date", arraydate);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.refresh:
backTask();
break;
}
return super.onOptionsItemSelected(item);
}
public void backTask(){
BackTask task = new BackTask();
task.execute();
try {
JSONObject result = task.get();
if(result != null){
JSONArray jarray = result.getJSONArray(TAG_ITEM);
for(int i = 0; i < jarray.length(); i++){
JSONObject jrss = jarray.getJSONObject(i);
arrayThumbs.add(jrss.getString(TAG_THUMBNAILS));
arrayBig_image.add(jrss.getString(TAG_BIG_IMAGE));
arrayAuthor.add(jrss.getString(TAG_AUTHOR));
arrayDescription.add(jrss.getString(TAG_DESCRIPTION));
arrayDate.add(jrss.getString(TAG_DATE));
Log.d("LLLLLOOOOGGGG", jrss.getString("author")+"\n");
}}
else{
AlertDialog.Builder alertNetworkError = new AlertDialog.Builder(this);
alertNetworkError.setMessage("нет подключения к интернету");
alertNetworkError.setNegativeButton("Выйти", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertNetworkError.create();
alertNetworkError.show();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
arraymThumbs = new String[arrayThumbs.size()];
arraymThumbs = arrayThumbs.toArray(arraymThumbs);
arrayBimages = new String[arrayBig_image.size()];
arrayBimages = arrayBig_image.toArray(arrayBimages);
arrayauthor = new String[arrayAuthor.size()];
arrayauthor = arrayAuthor.toArray(arrayauthor);
arraydescription = new String[arrayDescription.size()];
arraydescription = arrayDescription.toArray(arraydescription);
arraydate = new String[arrayDate.size()];
arraydate = arrayDate.toArray(arraydate);
adapter = new ImageAdapter(MainActivity.this, arraymThumbs);
adapter.notifyDataSetChanged();
}
And my image adapter here i get all result's from asyncTask and print thumbs images to my GridView
public class ImageAdapter extends BaseAdapter {
public Context mContext;
String[] mThumbs;
public LayoutInflater inflater;
public DisplayImageOptions options;
public ImageLoader imageLoader;
public ImageAdapter (Context c, String[] arrayhumbss){
mContext = c;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mThumbs = arrayhumbss;
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_contact_picture_2)
.showImageForEmptyUri(R.drawable.ic_launcher)
.cacheInMemory()
.cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(c));
}
#Override
public int getCount() {
return mThumbs.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) inflater.inflate(R.layout.grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(mThumbs[position], imageView, options);
return imageView;
}
}
This is my BACKTASK
public class BackTask extends AsyncTask<String, Void, JSONObject>{
#Override
protected JSONObject doInBackground(String... params) {
InputStream ips = null;
JSONObject jsonObj = null;
String json = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(new HttpPost("http://192.168.1.179/lenta/image.js"));
ips = response.getEntity().getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader bufff = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufff.readLine()) != null){
sb.append(line + "\n");
}
ips.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result){
super.onPostExecute(result);
}
}
here i handle my json from url, and in MainActivity i get this form task.get()
Add grid.setAdapter(adapter) right after this line
adapter = new ImageAdapter(MainActivity.this, arraymThumbs);
Hope this would solve your problem.
EDIT: P.S. It seems you need to read something, because i think you don't fully understand what adapter is and how to use it.
Use this :
adapter = new ImageAdapter(YourActivity.this, arraymThumbs);
myGridView.setAdapter(adapter);
Hope this helps you.
Thanks.
Related
I am trying to get JSON data to app, but getting JSON Exception
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List<Project> projects = new ArrayList<>();
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
Button mFilterButton = (Button) findViewById(R.id.filter_button);
mFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.filter_menu);
popupMenu.show();
}
});
Button mSortButton = (Button) findViewById(R.id.sort_button);
mSortButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.sort_menu);
popupMenu.show();
}
});
new GSONExecution().execute();
}
private class GSONExecution extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String urlString = "http://starlord.hackerearth.com/kickstarter";
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
int res = httpURLConnection.getResponseCode();
if (res == 200){
InputStream inputStream = httpURLConnection.getInputStream();
String s = convertStreamToString(inputStream);
Log.v("Response :" , " is "+ s);
JSONObject rootObject = new JSONObject(s);
JSONArray jsonArray = rootObject.getJSONArray("");
for (int i=0; i<=jsonArray.length(); i++){
JSONObject contactObject = jsonArray.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean isOperationCompleted) {
super.onPostExecute(isOperationCompleted);
if (isOperationCompleted){
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
ProjectAdapter adapter = new ProjectAdapter(MainActivity.this, projects);
mListView.setAdapter(adapter);
}
}
#NonNull
private String convertStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
String line;
while ((line = bufferedReader.readLine()) != null)
stringBuilder.append(line).append("\n");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
}
Project
public class Project {
String mtitle;
Integer mPleadges;
Integer mBackers;
String mNoDays;
public String gettitle() {
return mtitle;
}
public void settitle(String mtitle) {
this.mtitle = mtitle;
}
public Integer getPleadges() {
return mPleadges;
}
public void setPleadges(Integer mPleadges) {
this.mPleadges = mPleadges;
}
public Integer getBackers() {
return mBackers;
}
public void setBackers(Integer mBackers) {
this.mBackers = mBackers;
}
public String getNoDays() {
return mNoDays;
}
public void setNoDays(String mNoDays) {
this.mNoDays = mNoDays;
}
}
ProjectAdapter
class ProjectAdapter extends BaseAdapter{
private List<Project> mList;
private Context mContext;
public ProjectAdapter(MainActivity mainActivity, List<Project> projects) {
this.mList = projects;
this.mContext = mainActivity;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.project_details,null,false);
final TextView projectName = (TextView) convertView.findViewById(R.id.projectName);
TextView pleadge = (TextView) convertView.findViewById(R.id.pledges);
TextView backers = (TextView) convertView.findViewById(R.id.backers);
projectName.setText(mList.get(position).gettitle());
pleadge.setText(mList.get(position).getPleadges());
backers.setText(mList.get(position).getBackers());
return convertView;
}
}
I am getting org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:111)
I hope you understand problem, I am still in learning stage so please give brief answer so that i can understand.
You are getting JSONArray from Response and trying to hold on JSONObject which causes org.json.JSONException: Value at org.json.JSON.typeMismatch(JSON.java:111) error
Try this
try {
JSONArray jsonArrayLST = new JSONArray(s);
for (int i = 0; i < jsonArrayLST.length(); i++) {
JSONObject contactObject= jsonArrayLST.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, you need to change in your adapter while setting item to textview, because your are setting int value which causes you android.content.res.Resources$NotFoundException: String resource ID error
pleadge.setText(String.valueOf(mList.get(position).getPleadges()));
backers.setText(String.valueOf(mList.get(position).getBackers()));
I developed a search function and it worked successfully. The class responsible for the search is called from onQueryTextSubmit and there was nothing wrong with it.
Now I wanted to add other thing that is a button in the same activity of the search bar that when it's clicked all data from the database is displayed in cardView. When I added the code the onQueryTextSubmit method is no longer working plus the button isn't displaying the data. I do not know where is the problem. Here is the code for the whole activity.
PS: for some reason it says that showdata() method is never used.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find_skill);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewer);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listView = (ListView) findViewById(R.id.searchList);
searchView = (SearchView) findViewById(R.id.searchView);
noData = (ImageView) findViewById(R.id.nodata);
noNetwork = (ImageView) findViewById(R.id.nonetwork);
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
SenderReceiver sr = new SenderReceiver(FindSkill.this, urlAdress,listView, query,noData,noNetwork);
sr.execute();
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return false;
}});}
private void getData() {
class GetData extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(FindSkill.this, "Fetching Data", "Please wait...", false, false);
}
#Override
protected void onPostExecute(String res) {
super.onPostExecute(res);
progressDialog.dismiss();
parseJSON(res);
}
#Override
protected String doInBackground(Void... params) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(Config.GET_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetData gd = new GetData();
gd.execute();
}
public void showData(){
adapter = new CardAdapter(Config.skills,Config.ids);
recyclerView.setAdapter(adapter);
}
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
Config.skills[i] = getSkill(j);
Config.ids[i] = getId(j);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSkill(JSONObject j){
String name = null;
try {
name = j.getString(Config.JSON_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
private String getId(JSONObject j){
String id = null;
try {
id = j.getString(Config.JSON_ID);
} catch (JSONException e) {
e.printStackTrace();
}
return id;
}
This is the Config class:
public class Config {
public static String[] skills;
public static String[] ids;
public static final String GET_URL = "http://skillsexchangecyprus.com/SEC/mainList.php";
public static final String JSON_ID = "id";
public static final String JSON_NAME = "skill";
public static final String TAG_JSON_ARRAY="result";
public Config(int i) {
skills = new String[i];
ids = new String[i];
}
}
Card Adapter class:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
List<ListItem> items;
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i =0; i<items.size(); i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem myAdapter = items.get(position);
holder.skillName.setText(myAdapter.getSkill());
holder.skillId.setText(String.valueOf(myAdapter.getId()));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView skillId;
public TextView skillName;
public ViewHolder(View itemView) {
super(itemView);
skillId = (TextView) itemView.findViewById(R.id.skillId);
skillName = (TextView) itemView.findViewById(R.id.skillName);
}
}
}
You did't call your showData() method. You need to create an instance of CardAdapter and set this adapter to your recyclerView.
Update OnCreate() method as below:
..............
....................
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
config = new Config(INITIAL_VALUE);
// Adapter
adapter = new CardAdapter(config.skills,config.ids);
recyclerView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
....................
..............................
Use adapter.notifyDataSetChanged() to update recyclerView with new items.
Update parseJson() method as below:
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
config.skills[i] = getSkill(j);
config.ids[i] = getId(j);
// Update
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
In your CardAdapter constructor, use skills.length instead of items.size()
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i = 0; i < skills.length; i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
Hope this will work~
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;
}
Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
i hv an application in which i am getting data from api,when data get loads and i tried to scroll the listview it get starts jerking,i tried to find the solution but get nothing.please help me to sort it out.
InboxActivity.java
list=(ListView)rootView.findViewById(R.id.list);
catagery = new ArrayList<ProfileInbox>();
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//arg0.getp.setBackgroundColor(Color.WHITE);
//parent.getChildAt(position).setBackgroundColor(Color.BLUE);
IsRead=true;
catagery.get(position).setRead(IsRead);
new Task().execute(url);
adapter.notifyDataSetChanged();
msg=catagery.get(position).getMessage();
dateFrom=catagery.get(position).getSentDate();
sub=catagery.get(position).getSubject();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
});
return rootView;
}
private void loadNextPageOfReviews()
{
page_no_count += 1;
new JSONAsyncTask().execute(loadMoreUrl);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please Wait, Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("inbox");
String unread_msg= jsono.getString("unread_msg");
Log.i("unreadMsg", unread_msg);
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
ProfileInbox category = new ProfileInbox();
String id = c.getString("msg_id");
String sub = c.getString("subject");
String name = c.getString("message");
String imageSetter=c.getString("sent_on");
//Log.i("id", id);
//Log.i("name", name);
//Log.i("imageSetter", imageSetter);
category.setMsgId(((JSONObject) c).getString("msg_id"));
if(unread_msg.contains(id)){
category.setRead(false);
}
else{
category.setRead(true);
}
category.setSubject(((JSONObject) c).getString("subject"));
category.setMessage(((JSONObject) c).getString("message"));
category.setSentDate(((JSONObject) c).getString("sent_on"));
//Log.i("category", category.toString());
catagery.add(category);
//Log.i("category", category.toString());
}
return true;
}
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if (result == false){
Toast.makeText(getActivity(),
"Unable to fetch data from server", Toast.LENGTH_LONG)
.show();
}
else if(Blank.notice.equals("true")){
msg=catagery.get(0).getMessage();
dateFrom=catagery.get(0).getSentDate();
sub=catagery.get(0).getSubject();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
else if(Blank.notice.equals("false"))
{
//adapter.notifyDataSetChanged();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
InboxAdapter
public class InboxAdaptor extends BaseAdapter {
private List<ProfileInbox> originalData;
private List<ProfileInbox> filteredData;
private Context context;
public static String url;
public static String bussinessId;
public InboxAdaptor(Context context, ArrayList<ProfileInbox> Data) {
this.context = context;
this.originalData = Data;
//Log.i("originalData", Data.toString());
filteredData = new ArrayList<ProfileInbox>();
filteredData.addAll(this.originalData);
//Log.i("filterData", filteredData.toString());
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.inboxlist, null,false);
holder.coloredlay=(RelativeLayout)convertView.findViewById(R.id.coloredlay);
holder.txtWelcom = (TextView) convertView.findViewById(R.id.txtWelcom);
holder.dateTime = (TextView) convertView.findViewById(R.id.dateTime);
holder.txtdetails = (TextView) convertView.findViewById(R.id.txtdetails);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
if(filteredData.get(position).getRead()==true)
{
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}else{
holder.coloredlay.setBackgroundColor(Color.parseColor("#E5E4E2"));
}
// holder.img.setTag(position);
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(convertView.getContext().getAssets(), fontPath);
holder.txtWelcom.setText(filteredData.get(position).getSubject());
holder.txtWelcom.setTypeface(tf);
holder.dateTime.setText(filteredData.get(position).getSentDate());
holder.dateTime.setTypeface(tf);
holder.txtdetails.setText(filteredData.get(position).getMessage());
holder.txtdetails.setTypeface(tf);
/* if(Blank.notice.equals("true")){
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}
*/
notifyDataSetChanged();
return convertView;
}
public static class ViewHolder {
public RelativeLayout coloredlay;
public TextView txtdetails;
public TextView dateTime;
public TextView txtWelcom;
}
Remove notifyDataSetChanged() from getView() , notifyDataSetChanged() will update adapter when the data which you provided for your adapter has been changed , but you are using that wrong when a View of your list has been changed.
Remove notifyDataSetChanged() from getView().
You dot need that here. Rather have Remove notifyDataSetChanged() in onPostExecute() call back of JSONAsyncTask
Use cachecolorHint for come out of your solution:
<ListView
android:id="#+id/listNewsMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent" >
</ListView>