is there a way to use custom adapter with jsonArray obtained from a specific link?
I getting error when I run my app with my code, what should i do??
I've tried to find a way how to do, but the examples given too scrimpy, that's why I need help here,
I've tried this code to do :
Pertanyaan.java
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
}
PertanyaanAdapter.java
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setOnItemClickListener(onItemClickListener());
}
private AdapterView.OnItemClickListener onItemClickListener() {
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
EDIT :
Error from logcat :
FATAL EXCEPTION: main
Process: flix.yudi.pertanyaan3, PID: 23836
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.addAll(java.util.Collection)' on a null object reference
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:156)
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Your problem is that your ArrayList is not initialized. It crashs at this point:
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list); // CRASH!
adapter2.notifyDataSetChanged();
}
To explain more, like we discussed in the comments, what you have done is to creating a new ArrayList in your asyncTask:
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list; //NEW ARRAYLIST
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();//NEW ARRAYLIST INITIALIZING
}
but still not have initialized listPertanyaan . Wether you have to use the new created arrayList like:
list.addAll(list);
in your onPostExecute(), or you have to initialize the listPertanyaan before like
listPertanyaan = new ArrayList<Pertanyaan>();
EDIT
For your second question, you should initialize your adapter and set it to listView in onPostExecute() after you get filled the arrayList. It should look like:
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}
Related
I am three days trying to solve this problem with my filter using checkbox and a ListView.
In this code I select the checkboxes the first time and they are listed correctly with the IDs of each selected category and review the IDs for another Activity called NovaActivity. OK? So far so good.
The problem is the following when I re-open the Filters Activity to make a new same unchecking checkbox with the already listed filters it keeps going to NovaAcitivty even though they are unmarked.
EX:
1st filter selects 1 and 2;
When I send it to another it goes the 1,2;
2nd filter I select 1 and uncheck checkbox 2;
When I send it to another it goes the 1,1,2;
How do I solve this?
NOTE: important the second time so said that I open the Filters activity the already selected checkboxes are already premarked because I write them to my remote MySQL database and I retrieve them.
If I was not very clear can ask questions at will, thank you any help already.
public class MainActivity extends AppCompatActivity {
Context context;
ArrayList<Category> array_list;
FavouriteCategoriesJsonParser categoryJsonParser;
String categoriesCsv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
new asyncTask_getCategories().execute();
}
public static class CategoryAdapter extends ArrayAdapter<Category> {
private final List<Category> list;
public CategoryAdapter(Context context, int resource, List<Category> list) {
super(context, resource, list);
this.list = list;
}
static class ViewHolder {
protected TextView categoryName;
protected CheckBox categoryCheckBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(getContext());
convertView = inflator.inflate(R.layout.row_category, null);
viewHolder = new ViewHolder();
viewHolder.categoryName = (TextView) convertView.findViewById(R.id.row_categoryname_textview);
viewHolder.categoryCheckBox = (CheckBox) convertView.findViewById(R.id.row_category_checkbox);
viewHolder.categoryCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
list.get(getPosition).setSelected(buttonView.isChecked());
if (buttonView.isChecked()) {
if (!FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.add(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"ADICONOU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
} else {
if (FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.remove(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"REMOVEU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.row_categoryname_textview, viewHolder.categoryName);
convertView.setTag(R.id.row_category_checkbox, viewHolder.categoryCheckBox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.categoryCheckBox.setTag(position);
viewHolder.categoryName.setText(list.get(position).getCategory_Name());
viewHolder.categoryCheckBox.setChecked(list.get(position).isSelected());
return convertView;
}
}
public static class FavouriteCategoriesJsonParser {
public static ArrayList<String> selectedCategories = new ArrayList<>();
public ArrayList<Category> getParsedCategories() {
String JsonFavouriteCategories = "";
ArrayList<Category> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://pensoupediu.000webhostapp.com/api/filtro/getFavouriteCategories.php?id_usuario=1");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
JsonFavouriteCategories = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(JsonFavouriteCategories);
for (int i = 0; i < jsonArray.length(); i++) {
Category genres = new Category();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setCateogry_id(Integer.parseInt(MyJsonObject.getString("id")));
genres.setCategory_Name(MyJsonObject.getString("nome_cat"));
genres.setSelected(Boolean.parseBoolean(MyJsonObject.getString("selected")));
MyArraylist.add(genres);
if (MyJsonObject.getString("selected").equals("true")) {
selectedCategories.add(MyJsonObject.getString("id"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
public class asyncTask_getCategories extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
#Override
protected void onPreExecute() {
dialog.setTitle("");
dialog.setMessage("Carregando...");
dialog.show();
array_list = new ArrayList<>();
categoryJsonParser = new FavouriteCategoriesJsonParser();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
array_list = categoryJsonParser.getParsedCategories();
Log.i("ISIS"," "+array_list);
return null;
}
#Override
protected void onPostExecute(Void s) {
ListView mListViewBooks = (ListView) findViewById(R.id.category_listView);
final CategoryAdapter categoryAdapter = new CategoryAdapter(context, R.layout.row_category, array_list);
mListViewBooks.setAdapter(categoryAdapter);
Button button = (Button) findViewById(R.id.selectCategoryButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
categoriesCsv = FavouriteCategoriesJsonParser.selectedCategories.toString();
categoriesCsv = categoriesCsv.substring(1, categoriesCsv.length() - 1);
if (categoriesCsv.length() > 0) {
new asyncTask_insertUpdatefavouriteCategories().execute();
} else {
Toast.makeText(context, "Por favor, selecione um filtro.", Toast.LENGTH_SHORT).show();
}
}
});
super.onPostExecute(s);
dialog.dismiss();
}
public class asyncTask_insertUpdatefavouriteCategories extends AsyncTask<Void, Void, Void> {
String response;
#Override
protected Void doInBackground(Void... params) {
response = insertUpdateCall(categoriesCsv);
return null;
}
#Override
protected void onPostExecute(Void s) {
Toast.makeText(context, categoriesCsv, Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NovaActivity.class);
intent.putExtra("filtros", response);
startActivity(intent);
super.onPostExecute(s);
}
}
}
public static String insertUpdateCall(String categoriesCsv) {
String response = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://pensoupediu.000webhostapp.com/api/filtro/insertUpdateFavouriteCategories.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id_usuario", "1"));
nameValuePairs.add(new BasicNameValuePair("favouriteCategories", categoriesCsv));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
Use Set instead of ArrayList:
public static Set<String> selectedCategories = new HashSet<>();
This will ensure that your selectedCategories has no duplicates.
I'm having a hard time figuring out how to implement the new MyAsyncTask().execute("") that I've searched because I have separate classes that extends Asynctask. I wanted to call the class everytime i click the button. Hope you guys can help me figure this out.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
String url = "http://192.168.254.103/dbtest/categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start);
final ListView lv = (ListView) findViewById(R.id.lv);
final Downloader d = new Downloader(this,url,lv);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.execute();
}
});
}
}
Here is my Downloader.java
public class Downloader extends AsyncTask<Void,Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//BEFORE JOB STARTS
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch Data");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
String data = downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s != null){
Parser p =new Parser(c,s,lv);
p.execute();
}else
{
Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is = null;
String line = null;
try{
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
if(br != null){
while((line = br.readLine()) != null)
{
sb.append(line+"\n");
}
}
else
{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
and my Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse(){
try
{
//ADD TGAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jo = null;
categories.clear();
//LOOP THROUGH ARRAY
for(int i =0 ; i<ja.length();i++)
{
jo = ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("cat_name");
//ADD TO ARRAY LIST
categories.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
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;
}
This app is supposed to parse some JSON data (hard coded for now) from the Google Books API, and pass an ArrayList of Books to the adapter that will display it on a ListView. The problem I have is that the JSON parse is returning null instead of the parsed data.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ProgressBar pBar;
List<MyTask> tasks;
ArrayList<Book> bookList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pBar = (ProgressBar) findViewById(R.id.progressBar);
pBar.setVisibility(View.INVISIBLE);
Button sButton = (Button) findViewById(R.id.s_button);
sButton.setOnClickListener(this);
tasks = new ArrayList<>();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.s_button: {
if (isOnline()) {
new MyTask().execute("https://www.googleapis.com/books/v1/volumes?q=millionare"); //https://www.googleapis.com/books/v1/volumes?q=soft+skills
} else {
Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
}
break;
}
}
}
protected boolean isOnline() {
ConnectivityManager connectManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpManager.getData(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
bookList = BookJSONParser.parseFeed(result);
updateDisplay();
}
}
protected void updateDisplay() {
BookAdapter adapter = new BookAdapter(this, bookList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
public class BookJSONParser {
public static ArrayList<Book> parseFeed(String content) {
try {
JSONArray jsonArray = new JSONArray(content);
ArrayList<Book> bookList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("title").toString();
Book book = new Book(name);
bookList.add(book);
}
return bookList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context context, ArrayList<Book> bookList) {
super(context, 0, bookList);
}
#Override
public View getView(int position, View convertedView, ViewGroup parent) {
View listItemView = convertedView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView locationName = (TextView) listItemView.findViewById(R.id.book_title);
locationName.setText(currentBook.getTittle());
TextView locationAddress = (TextView) listItemView.findViewById(R.id.book_author);
locationAddress.setText(currentBook.getAuthor());
return listItemView;
}
}
public class HttpManager {
public static String getData(String myUrl) throws IOException {
// BufferedReader reader = null;
InputStream inputStream = null;
int len = 10000;
try {
URL url = new URL(myUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000 /* milliseconds */);
connection.setConnectTimeout(15000 /* milliseconds */);
connection.setRequestMethod("GET");
connection.setDoInput(true);
// Starts the query
connection.connect();
int response = connection.getResponseCode();
inputStream = connection.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(inputStream, len);
return contentAsString;
// Makes sure that the InputStream inputStream closed after the app inputStream
// finished using it.
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
// Reads an InputStream and converts it to a String.
public static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
public class Book {
private String mTittle;
/**
* This is the constructor.
* #param title is the book title being passed in.
*/
public Book(String title) {
mTittle = title;
}
public String getTittle() {
return mTittle;
}
public void setTittle(String tittle) {
mTittle = tittle;
}
}
FATAL EXCEPTION: main
Process: com.narvin.android.booklisting, PID: 3278
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:502)
at com.narvin.android.booklisting.MainActivity.updateDisplay(MainActivity.java:113)
at com.narvin.android.booklisting.MainActivity$MyTask.onPostExecute(MainActivity.java:100)
at com.narvin.android.booklisting.MainActivity$MyTask.onPostExecute(MainActivity.java:79)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
The issue is that one of the arguments in BookAdapter adapter = new BookAdapter(this, bookList); is null for some reason. Try passing bookList as an argument to updateDisplay and checking whether it's not null.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ProgressBar pBar;
List<MyTask> tasks;
ArrayList<Book> bookList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pBar = (ProgressBar) findViewById(R.id.progressBar);
pBar.setVisibility(View.INVISIBLE);
Button sButton = (Button) findViewById(R.id.s_button);
sButton.setOnClickListener(this);
tasks = new ArrayList<>();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.s_button: {
if (isOnline()) {
new MyTask().execute("https://www.googleapis.com/books/v1/volumes?q=millionare"); //https://www.googleapis.com/books/v1/volumes?q=soft+skills
} else {
Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
}
break;
}
}
}
protected boolean isOnline() {
ConnectivityManager connectManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpManager.getData(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<Book> bookList = BookJSONParser.parseFeed(result);
updateDisplay(bookList);
}
}
protected void updateDisplay(ArrayList<Book> bookList) {
if (bookList != null){
BookAdapter adapter = new BookAdapter(this, bookList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
}
It would appear you are getting a JSONParseException... therefore causing a NullPointerExpcetion for the List into the Adapter
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
That is your error, here is how you get it
public static ArrayList<Book> parseFeed(String content) {
try {
JSONArray jsonArray = new JSONArray(content); // <-- Throws an error
ArrayList<Book> bookList = new ArrayList<>();
// Stuff...
return bookList;
} catch (JSONException e) {
e.printStackTrace();
return null; // <----- Null is returned
}
And you use that null value here
#Override
protected void onPostExecute(String result) {
bookList = BookJSONParser.parseFeed(result);
updateDisplay();
}
Followed by
protected void updateDisplay() {
BookAdapter adapter = new BookAdapter(this, bookList); // <-- Null here
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
So, the way to fix that NullPointerExpception is to always return an ArrayList
ArrayList<Book> bookList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(content);
// Stuff...
} catch (JSONException e) {
e.printStackTrace();
}
return bookList;
to get json string from url you should do it like that
String content = new MyTask()
.execute("https://www.googleapis.com/books/v1/volumes?q=millionare")
.get();
//pass the content to BookJSONParser class
booklist = new BookJSONParser().parseFeed(content);
updateDisplay();
what you get from the url you provided is NOT jsonArray it's a jsonobject
so I think this code will work "assuming that you did everything else correctly"
JSONObject o = new JSONObject(content);
JSONArray jsonArray = o.getJSONArray("items");
the you can do the for loop
i have a list view that is populated from a database with a customlistview...everything works fine except when i first start activity, the first item on the list view, loops through all images and then sets each image to corresponding item. I cannot figure out what i am doing wrong. pls help. I have gone through al the answers on stackoverflow but nothing works for me. Here is my custom list view:
***Edit:This code is working fine now. I fixed it.
public class FriendsListView extends ArrayAdapter<FriendsRowItem> {
Context context;
ArrayList<FriendsRowItem> infoList;
private LayoutInflater inflater = null;
int Resource;
ViewHolder holder;
public FriendsListView(Context context, int resourceId,
ArrayList<FriendsRowItem> items) {
super(context, resourceId, items);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resourceId;
infoList = items;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
}
public int getCount() {
return infoList.size();
}
public RowItem getItem(RowItem position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) {
vi = inflater.inflate(R.layout.list_item_3, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) vi.findViewById(R.id.title3);
holder.imageView = (ImageView) vi.findViewById(R.id.icon3);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txtTitle.setText(infoList.get(position).getTitle());
holder.imageView.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageView).execute(infoList.get(position)
.getImage());
return vi;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
int position;
public DownloadImageTask(ImageView bmImage, int position) {
this.bmImage = bmImage;
this.position = position;
bmImage.setTag(position);
bmImage.setImageBitmap(null);
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = (InputStream) new java.net.URL(urldisplay)
.getContent();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
// Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
if (result != null && (bmImage.getTag()).equals(this.position))
bmImage.setImageBitmap(result);
bmImage.setImageBitmap(result);
}
}
And how i populate my list view using JSON:
class RetrieveFriendsTask extends AsyncTask<Void, Void, Void> {
ArrayList<FriendsRowItem> FriendList = new ArrayList<FriendsRowItem>();
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog.dismiss();
}
// Showing progress dialog
else {
pDialog = new ProgressDialog(Friends.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("eposta", email));
pairs.add(new BasicNameValuePair("sifre", pass));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, pairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject obj = jsonObj.getJSONObject("data");
friends = obj.getJSONArray(TAG_EVENTS);
for (int i = 0; i < friends.length(); i++) {
friend = new FriendsRowItem();
JSONObject c = friends.getJSONObject(i);
nick = c.optString("nick");
// friend.setTitle(c.optString("nick"));
img = c.optString("url_resim");
// friend.setImage(c.optString("url_resim"));
friend.setTitle(nick);
friend.setImage(img);
FriendList.add(friend);
}
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(Void result) {
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new FriendsListView(Friends.this, R.layout.list_item_3,
FriendList);
lvfriends.setAdapter(adapter);
OnItemClickListener myListViewClicked = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
FriendsRowItem name = (FriendsRowItem) parent
.getItemAtPosition(position);
Intent i = new Intent(Friends.this, FriendsDisplay.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("FriendName", name.toString());
startActivity(i);
}
};
lvfriends.setOnItemClickListener(myListViewClicked);
}
}
I would really appreciate the help.