I receive a null pointer exeception when trying to populate the interface beacuse I have no data in my instance object.
I am using a login button and call a service, i receive a json and after I parse it i have a status handler...login ok... Here I want to start an asynk task to get some photo data
public void StatusHandlerLogin(String status, Activity currentActivity) {
if (status.equals("0")) {
new GetPhotoDataTask(currentActivity).execute();
Intent intent = new Intent(currentActivity,
NavigationActivity.class);
currentActivity.startActivity(intent);
}
//}
The asynk task is like this
public class GetPhotoDataTask extends
AsyncTask<Void, Void, List<PhotoData>> {
Activity activity;
public GetPhotoDataTask(Activity activity) {
this.activity = activity;
}
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
Log.d("GetPhotoDataTask onPreExecute",
"GetPhotoDataTask onPreExecute");
super.onPreExecute();
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
#Override
protected List<PhotoData> doInBackground(Void... params) {
Log.d("GetPhotoDataTask doInBackground",
"GetPhotoDataTask doInBackground");
MyStyleApi myStyleApi = new MyStyleApi();
List<PhotoData> photoData = null;
try {
photoData = myStyleApi.getPhotoDataWithDispatch();
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> photoStr = new ArrayList<String>();
for (int i = 0; i < photoData.size(); i++) {
photoStr.add(photoData.get(i).getPhotoURL());
}
String[] photoUrls = new String[photoStr.size()];
photoUrls = photoStr.toArray(photoUrls);
for (int i = 0; i < photoUrls.length; i++) {
if (photoUrls[i].contains("\"")) {
photoUrls[i] = photoUrls[i].replace("\"", "");
}
}
AppManager.getInstance().setphotoUrls(photoUrls);
List<PhotoData> photoDataS = AppManager.getInstance().setPhotoData(
photoData);
return photoData;
}
protected void onProgressUpdate(Integer... percent) {
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
protected void onPostExecute(List<PhotoData> photoData) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
on do in background i have a method that call other service
get PhotoData with userId as param
public List<PhotoData> getPhotoDataWithDispatch() throws JSONException,
ClientProtocolException, IOException {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
UserData data = AppManager.getInstance().getUserData();
String userID = data.getUserID();
if (userID.contains("\"")) {
userID = userID.replace("\"", "");
}
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("userID", userID);
JsonArray response = WebServiceApi.PostToServiceWithStringResponse(
"images/get_images_data", params);
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
if (response != null) {
photoDataList = parseJsonArrayForFotoData(response);
}
return photoDataList;
}
and if response is not null i parse it
public static List<PhotoData> parseJsonArrayForFotoData(JsonArray jsonArray) {
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
for (int i = 0; i < jsonArray.size(); i++) {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
JsonElement photoID = ((JsonObject) jsonArray.get(i)).get("pozaID");
JsonElement photoUrl = ((JsonObject) jsonArray.get(i))
.get("pozaURL");
JsonElement thumbURL = ((JsonObject) jsonArray.get(i))
.get("thumbURL");
JsonElement tags = ((JsonObject) jsonArray.get(i)).get("tags");
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(tags.toString()).getAsJsonArray();
List<Tags> tagsList = new ArrayList<Tags>();
for (int j = 0; j < array.size(); j++) {
JsonElement tagId = ((JsonObject) array.get(j)).get("tagID");
JsonElement coordX = ((JsonObject) array.get(j)).get("coordX");
JsonElement coordY = ((JsonObject) array.get(j)).get("coordY");
JsonElement productId = ((JsonObject) array.get(j))
.get("productID");
Tags tagPData = new Tags(tagId.toString(), coordX.toString(),
coordY.toString(), productId.toString());
tagsList.add(tagPData);
}
PhotoData photoData = new PhotoData(photoID.toString(),
photoUrl.toString(), thumbURL.toString(), null, tagsList);
photoDataList.add(photoData);
}
return photoDataList;
}
ok in GetPhotoDataTaskFb do in background i set the instance of the photos object
AppManager.getInstance().setphotoUrls(photoUrls);
and in fragmnet
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.ac_image_pager, container,
false);
// Dummy code
if (counter == 0) {
for (int i = 0; i <= 20; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
counter++;
String[] imageUrls = AppManager.getInstance().getphotoUrls();
//here is where i get the null.. i tried some dummy code to delay and receive data but it is not working
How can I manage to stop create view until all data is parsed?
Related
This is my getView() method where I am trying to set the values of distance after fetching from the volley .Here distance calculation is proper.
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
if (convertView == null)
{
LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowallassigendloction, null);
holder = new ViewHolder();
holder.distance = (TextView) convertView.findViewById(R.id.distance);
holder.lati = (TextView) convertView.findViewById(R.id.lati);
holder.longi = (TextView) convertView.findViewById(R.id.longi);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.lati.setText(salesmanlocationArrayList.get(listrowposition).getLati());
holder.longi.setText(salesmanlocationArrayList.get(listrowposition).getLongi());
double lat1= Double.parseDouble(holder.lati.getText().toString());
double lng1= Double.parseDouble(holder.longi.getText().toString());
vollyRequest_Fetch_distance(lat1,lng1,lat,lng);
Log.d("distance_ll=","tex="+text+" "+value+" "+lat1);
double d= Double.parseDouble(value)/1000;
holder.distance.setText(""+new DecimalFormat("##.##").format(d)+" KM");
return convertView;
}
This is my volley request code
public void vollyRequest_Fetch_distance(double lat11, double lon11, double lat22, double lon22)
{
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+lat11+","+lon11+"&"+"destinations="+lat22+","+lon22;
Log.d("RESPOetchlocation..>>> ", url + "<<<");
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d("RESPONFetchlocation>>> ", response + "<<<");
// progressDialog.dismiss();
Jsonresponse_Distance(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE:Error>>> ", error.toString() + "<<<");
// progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "Arz5SyA5UFy-pTsr5cIdwxghhnV6BoH-pCJBARg");
return params;
}
};
queue.add(request);
}
public void Jsonresponse_Distance(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONArray jsonArray_elements = null;
JSONObject jsonObject_elements = null;
JSONObject jobj;
String error = null;
String msg = null;
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("OK"))
{
jsonArray = jsonObject.getJSONArray("rows");
Log.d("jsonArray.length()=",""+jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
jobj= jsonArray.getJSONObject(i);
jsonArray_elements= jobj.getJSONArray("elements");
Log.d("jsonArray_ets.length()=",""+jsonArray_elements.length());
for (int j = 0; j < jsonArray_elements.length(); j++)
{
jsonObject_elements= jsonArray_elements.getJSONObject(0);
Log.d("jsonObject_elements=",jsonObject_elements.toString());
JSONObject job= jsonObject_elements.getJSONObject("distance");
Log.d("job=",job.toString());
text= job.getString("text");
value= job.getString("value");
Log.d("job=",""+text+" "+value);
}
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
I am getting proper result for value (distance ) but getting null inside getview method please help me out.
// Here I am trying to set my adapter after fetching volley request
public void Jsonresponse_Viewlocation(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jobj;
String error = null;
String msg = null;
salesmanlocationArrayList.clear();
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("true")) {
jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++)
{
salesmanlocation = new Salesmanlocation();
jobj = jsonArray.getJSONObject(i);
address = jobj.getString("address");
salesmanlocation.setAddress(address); salesmanlocation.setAddress(jobj.getString("address"));
String latlong_string=getLocationFromAddress(address);
String latlong[]=latlong_string.split(",");
String lat1=latlong[0];
String lng1=latlong[1];
Log.d("latlng==",""+lat1+" "+lng1);
double latt= Double.parseDouble(lat1);
double lng1g= Double.parseDouble(lng1);
salesmanlocation.setLati(String.valueOf(lat1));
salesmanlocation.setLongi(String.valueOf(lng1));
salesmanlocationArrayList.add(salesmanlocation);
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter = new Baseddapter_Allassignloc();
alllist.setAdapter(adapter);
}
I have an app that at launch inside onCreate method copies data from assets folder. It does it in three for cycles, each with activity indicator and the problem is that when first two cycles run white screen shows and only when third loop starts i can seen activity screen with indicator on it.
The code is following
Realm realm;
ListView list;
int[] imageidsm = {R.drawable.fon_sovety350, R.drawable.fon_german350, R.drawable.fon_usa350, R.drawable.fon_uk350, R.drawable.fon_fr_it200, R.drawable.fon_japan_china200, R.drawable.fon_history200};
String[] itemname = {"СССР", "ГЕРМАНИЯ", "США", "ВЕЛИКОБРИТАНИЯ", "ФРАНЦИЯ И ИТАЛИЯ", "ЯПОНИЯ И КИТАЙ", "ИСТОРИЯ"};
Boolean firstLaunch = false;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
MainAdapter adapter = new MainAdapter(this, itemname, imageidsm, height, width);
list = (ListView) findViewById(R.id.mainListView);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
Intent toSssr = new Intent(MainActivity.this, TankListActivity.class);
toSssr.putExtra("category", "СССР");
startActivity(toSssr);
} else if (position == 3) {
Intent listActivity = new Intent(MainActivity.this, ArticleListActivity.class);
startActivity(listActivity);
}
}
});
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("db.realm")
.build();
realm.setDefaultConfiguration(realmConfiguration);
realm = Realm.getDefaultInstance();
preferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
firstLaunch = preferences.getBoolean("firstLaunch", false);
if (firstLaunch == false) {
firstLaunch();
}
}
public void firstLaunch() {
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json", "10f.json"};
String[] arrayOfArticles = {"32.json", "34.json", "44.json", "51.json", "33.json", "40.json", "41.json", "42.json", "52.json", "45.json", "37.json", "46.json", "36.json", "54.json", "35.json", "43.json", "47.json", "50.json", "49.json", "48.json", "56.json", "58.json", "53.json", "59.json" , "55.json", "60.json", "61.json"};
String[] arrayOfUsssr = {"62.json", "74.json", "75.json", "76.json", "63.json", "78.json", "79.json", "77.json", "81.json", "80.json"};
for (int i = 0; i < arrayOfCatLists.length; i++) {
new GetArticlesListFromDisk(arrayOfCatLists[i], i).execute();
}
for (int i = 0; i < arrayOfArticles.length; i++) {
new GetArticleFromDisk(arrayOfArticles[i]).execute();
}
for (int i = 0; i < arrayOfUsssr.length; i++) {
new GetTanksFromDisk(arrayOfUsssr[i]).execute();
}
firstLaunch = true;
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstLaunch", firstLaunch);
editor.apply();
}
private class GetArticlesListFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int index;
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json"};
private GetArticlesListFromDisk(String id, int index) {
this.id = id;
this.index = index;
}
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("listing");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String image = object.getString("image");
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(image);
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("getArticleFromDisk", "Saved article " + title);
ImageStorage.saveToSdCard(bitmap, image, getApplicationContext());
if (index == 0) {
category = "Танковые сражения";
} else if (index == 1) {
category = "Справочник танкиста";
} else if (index == 2) {
category = "Танковые асы";
} else if (index == 3) {
category = "СССР";
} else if (index == 4) {
category = "Германия";
} else if (index == 5) {
category = "США";
} else if (index == 6) {
category = "Великобритания";
}
realm.beginTransaction();
ArticleList articleList = realm.createObject(ArticleList.class);
articleList.setId(id);
articleList.setTitle(title);
articleList.setSubtitle(subtitle);
articleList.setImage(image);
articleList.setCategory(category);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetArticleFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int categoryIndex;
private GetArticleFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetArticleFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String body = object.getString("body");
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Saved article with id " + id);
realm.beginTransaction();
Article article = realm.createObject(Article.class);
article.setId(id);
article.setTitle(title);
article.setSubtitle(subtitle);
article.setBody(body);
article.setHash(hash);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetTanksFromDisk extends AsyncTask<String, Void, Tank> {
private String id;
private int categoryIndex;
private GetTanksFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetTankFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
Tank tank = new Tank();
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(LOG_TAG, "Entered preExecute");
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected Tank doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(json);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
JSONArray signatures = object.getJSONArray("signatures");
ArrayList<String> signatures_list = new ArrayList<String>();
for (int j = 0; j < signatures.length(); j++) {
signatures_list.add(signatures.get(j).toString());
}
String signatures_string = Joiner.on(",").join(signatures_list);
String body = object.getString("body");
String construction = object.getString("construction");
String modification = object.getString("modification");
String ttx = object.getString("ttx");
JSONObject images = object.getJSONObject("images");
JSONArray tank_slider = images.getJSONArray("tank_slider");
ArrayList<String> tank_slider_list = new ArrayList<String>();
for (int k = 0; k < tank_slider.length(); k++) {
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(tank_slider.getString(k));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
ImageStorage.saveToSdCard(bitmap, tank_slider.getString(k), getApplicationContext());
tank_slider_list.add(tank_slider.getString(k));
}
String tank_slider_string = Joiner.on(",").join(tank_slider_list);
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Imported from assets tank with id " + id);
tank.setId(id);
tank.setTitle(title);
tank.setSignatures(signatures_string);
tank.setBody(body);
tank.setConstruction(construction);
tank.setModification(modification);
tank.setTtx(ttx);
tank.setTank_slider(tank_slider_string);
tank.setHash(hash);
}
} catch (JSONException e) {
e.printStackTrace();
}
return tank;
}
#Override
protected void onPostExecute(Tank tank) {
super.onPostExecute(tank);
pd.dismiss();
realm.beginTransaction();
Tank newTank = realm.createObject(Tank.class);
newTank.setId(tank.getId());
newTank.setTitle(tank.getTitle());
newTank.setSignatures(tank.getSignatures());
newTank.setBody(tank.getBody());
newTank.setConstruction(tank.getConstruction());
newTank.setModification(tank.getModification());
newTank.setTtx(tank.getTtx());
newTank.setTank_slider(tank.getTank_slider());
newTank.setHash(tank.getHash());
realm.commitTransaction();
}
}
What Im I doing wrong ?
The code below tested on LG G3 and it worked fine. However when I tested it on a Samsung Galaxy S3/S2 doInBackground() is not called for some reason.
Code to check api:
public void startBlat(String tosearch) {
AsynctaskMovie asynctaskMovie = new AsynctaskMovie();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
asynctaskMovie.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,tosearch);
}
else {
asynctaskMovie.execute(tosearch);
}
The Asynctask code:
class AsynctaskMovie extends AsyncTask<String, String, ArrayList<Movie>> {
JSONParser jsonParser = new JSONParser();
private static final String SEARCH_URL = "http://www.omdbapi.com/?";
#Override
protected void onPreExecute() {
super.onPreExecute();
movieArrayList = new ArrayList();
Log.i(getActivity().getCallingPackage(), "onPreExecute");
}
#Override
protected ArrayList<Movie> doInBackground(String... args) {
Log.i(getActivity().getCallingPackage(),"doInBackground");
HashMap<String, String> params = new HashMap<>();
params.put("s", args[0]);
params.put("r", "json");
JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
Log.i(getActivity().getCallingPackage(), json.toString());
if (json != null) {
try {
if (json.getString("Response").equals("False")) {
return movieArrayList;
}
} catch (JSONException e) {
}
try {
JSONArray jsonArray = json.getJSONArray("Search");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String movieid = jsonObject.getString(App.getInstance().IMDBimdbID);
if (!movieid.equals("null")) {
Movie movie = new Movie(movieid);
movieArrayList.add(movie);
}
}
jsonArray = new JSONArray();
for (Movie movie : movieArrayList) {
params = new HashMap<>();
params.put("i", movie.getMovieid());
params.put("plot", "short");
params.put("r", "json");
JSONObject jsongetfullinfo = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
if (jsongetfullinfo != null) {
jsonArray.put(jsongetfullinfo);
Log.i("", jsongetfullinfo.toString());
}
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
movieArrayList.get(i).updateFromIMDB(jObject);
}
for (Movie movie : movieArrayList) {
movie.setMovieposter(LoadFromUrl(movie.getPosterURL()));
}
return movieArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return movieArrayList;
}
#Override
protected void onPostExecute(ArrayList<Movie> movieArrayList) {
Log.i("ronen", "list size: " + movieArrayList.size());
if (movieArrayList.size() > 0) {
listView.setAdapter(new MovieAdapter(getActivity(), movieArrayList));
listView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity().getApplicationContext(), "No found", Toast.LENGTH_SHORT).show();
}
}
private Bitmap LoadFromUrl(String theurl) {
URL url = null;
Bitmap bmp = null;
try {
url = new URL(theurl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
}
return bmp;
}
}
I have no idea what could solve this problem.
Following the answers I read here it seems that the code should work, but not so.
Can't see anything suspicious.
I'd recommend running a very simple AsyncTask on a very simple app, make sure it works (if not, maybe it something to do with the phone, so try on an emulator to be sure)
Then change it step by step to resemble your code, and you'll see where the bug is.
G'Luck!
I am having huge problems with my android application. In the app, I fetch data every thirty seconds from a JSON stream to update a listview--i only update the custom adapter if there is new data. If I call the JSONParse/update tasks once, everything works fine, though when I put this method inside a timer task, my application barely runs and ends up closing down after 10 seconds. If there is any way you can help me, i would be more than grateful. I am really sorry there is so much code here. Most importantly, pay attention to the callAsynchonousTask() method.
Here is the class where most the application work is being done:
public class LiveStreamFragment extends Fragment{
public WXYCMediaPlayer mediaPlayer;
ListView list;
TextView song;
TextView artist;
public ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String wxycUrl = "http://www.wxyc.info/playlists/recentEntries?v=2";
private static String streamURL = "http://152.2.204.90:8000/wxyc.mp3";
private static final String TAG_PLAYCUTS = "playcuts";
private static final String TAG_SONG = "songTitle";
private static final String TAG_ARTIST = "artistName";
private static final String TAG_ALBUM = "releaseTitle";
private static final String TAG_TALKSETS = "talksets";
private static final String TAG_CHRONID = "chronOrderID";
private static final String TAG_BREAKPOINTS = "breakpoints";
private static final String TAG_HOUR = "hour";
private static final String TAG_LAYOUT = "layoutType";
private SwipeRefreshLayout swipeLayout;
private Button update_button;
private JSONArray playcuts = null;
private JSONArray talksets = null;
private JSONArray breakpoints = null;
private Playcut[] playcutArr;
private Talkset[] talksetArr;
private Breakpoint[] breakpointArr;
public View rootView;
boolean firstCall = true;
boolean buttonActivated;
LiveAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = inflater.inflate(R.layout.stream_fragment, container, false);
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
buttonActivated = false;
new JSONParse().execute();
this.callAsynchronousTask();
update_button = (Button) rootView.findViewById(R.id.update_button);
update_button.setText("New Tracks!");
update_button.setGravity(Gravity.CENTER_HORIZONTAL);
update_button.setVisibility(View.GONE);
update_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.updateDataList(oslist);
update_button.setVisibility(View.GONE);
buttonActivated = false;
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
if(buttonActivated) {
update_button.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(buttonActivated) {
update_button.setVisibility(View.GONE);
}
}
});
return rootView;
}
public void addHeartData(HashMap<String, String> heartMap){
Bus bus = new Bus();
BusProvider.getInstance().post(heartMap);
}
/******** Calling the JSON Feed to update every 30 seconds ********/
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new JSONParse().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000); //execute in every 50000 ms
}
/******** JSON Parsing and sorting class ********/
public class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
private String chronIDCheck;
#Override
protected void onPreExecute() {
super.onPreExecute();
oslist = new ArrayList<HashMap<String, String>>();
/*DELAY THIS TASK FOR THE SPLASH SCREEN TIME*/
//mediaPlayer = new WXYCMediaPlayer(streamURL, this.getActivity());
//HashMap<String, String> streamMap = new HashMap<String, String>(); //Add this to the media player method.
//streamMap.put(TAG_LAYOUT, "LiveStream");
//oslist.add(streamMap);
/*list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);*/
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(wxycUrl);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
playcuts = json.getJSONArray(TAG_PLAYCUTS);
talksets = json.getJSONArray(TAG_TALKSETS);
breakpoints = json.getJSONArray(TAG_BREAKPOINTS);
playcutArr = new Playcut[playcuts.length()];
talksetArr = new Talkset[talksets.length()];
breakpointArr = new Breakpoint[breakpoints.length()];
for(int i = 0; i < playcuts.length(); i++){
JSONObject playcut = playcuts.getJSONObject(i);
playcutArr[i] = new Playcut(
playcut.getString(TAG_SONG),
playcut.getString(TAG_ARTIST),
playcut.getString(TAG_ALBUM),
playcut.getInt(TAG_CHRONID));
}
for(int j = 0; j < talksets.length(); j++){
JSONObject talkset = talksets.getJSONObject(j);
talksetArr[j] = new Talkset(
talkset.getInt(TAG_CHRONID));
}
for(int k = 0; k < breakpoints.length(); k++){
JSONObject breakpoint = breakpoints.getJSONObject(k);
breakpointArr[k] = new Breakpoint(
breakpoint.getInt(TAG_CHRONID),
breakpoint.getLong(TAG_HOUR)
);
}
} catch (JSONException e) {
e.printStackTrace();
}
int playcutIndex = 0;
int talksetIndex = 0;
int breakpointIndex = 0;
int minID;
int i = 0;
/******** Algorithm to consolidate playcuts, breakpoints, and talksets into one arraylist by their chronological ID ********/
while(i < 30){
HashMap<String, String> map = new HashMap<String, String>();
minID = Math.max(
playcutArr[playcutIndex].chronID, (int) Math.max(
talksetArr[talksetIndex].chronID, breakpointArr[breakpointIndex].chronID
)
);
if(minID == playcutArr[playcutIndex].chronID) {
map.put(TAG_SONG, playcutArr[playcutIndex].song);
map.put(TAG_ARTIST, playcutArr[playcutIndex].artist);
map.put(TAG_ALBUM, playcutArr[playcutIndex].album);
map.put(TAG_LAYOUT, "Playcut");
map.put(TAG_CHRONID,""+playcutArr[playcutIndex].chronID);
StringBuilder stringBuilder = new StringBuilder("http://ws.audioscrobbler.com/2.0/");
stringBuilder.append("?method=album.getinfo");
stringBuilder.append("&api_key=");
stringBuilder.append("2ead17554acf667f27cf7dfd4c368f15");
String albumURL = null;
try {
stringBuilder.append("&artist=" + URLEncoder.encode(map.get(TAG_ARTIST), "UTF-8"));
stringBuilder.append("&album=" + URLEncoder.encode(map.get(TAG_ALBUM), "UTF-8"));
albumURL = new RetrieveAlbumArtUrlTask().execute(stringBuilder.toString()).get();
} catch (UnsupportedEncodingException e) {
albumURL = null;
} catch (InterruptedException e) {
albumURL = null;
} catch (ExecutionException e) {
albumURL = null;
} catch (IllegalArgumentException e) {
albumURL = null;
}
map.put("albumArtUrl", albumURL);
playcutIndex = playcutIndex + 1;
}
if(minID == talksetArr[talksetIndex].chronID) {
map.put(TAG_SONG, "Talkset");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Talkset");
map.put(TAG_CHRONID,""+talksetArr[talksetIndex].chronID);
talksetIndex = talksetIndex + 1;
}
if(minID == breakpointArr[breakpointIndex].chronID) {
map.put(TAG_SONG, "Breakpoint");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Breakpoint");
map.put(TAG_HOUR, ""+breakpointArr[breakpointIndex].hour);
map.put(TAG_CHRONID,""+breakpointArr[breakpointIndex].chronID);
breakpointIndex = breakpointIndex + 1;
}
map.put("Clicked", "False");
oslist.add(map);
chronIDCheck = oslist.get(0).get(TAG_CHRONID);
i++;
}
/* If this is the first JSON Parse, we instantiate the adapter, otherwise we just update */
if(firstCall) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
firstCall = false;
} else {
if(!adapter.chronIdCheck().equals(oslist.get(0).get(TAG_CHRONID))) {
//adapter.updateDataList(oslist);
update_button.setVisibility(View.VISIBLE);
buttonActivated = true;
}
}
}
}
}
Here is my new doInBackground() Code:
#Override
protected Void doInBackground(String... args) {
jParser = new JSONParser();
json = jParser.getJSONFromUrl(wxycUrl);
Log.v("TEST","BACKGROUND");
try {
playcuts = json.getJSONArray(TAG_PLAYCUTS);
talksets = json.getJSONArray(TAG_TALKSETS);
breakpoints = json.getJSONArray(TAG_BREAKPOINTS);
playcutArr = new Playcut[playcuts.length()];
talksetArr = new Talkset[talksets.length()];
breakpointArr = new Breakpoint[breakpoints.length()];
for(int i = 0; i < playcuts.length(); i++){
JSONObject playcut = playcuts.getJSONObject(i);
playcutArr[i] = new Playcut(
playcut.getString(TAG_SONG),
playcut.getString(TAG_ARTIST),
playcut.getString(TAG_ALBUM),
playcut.getInt(TAG_CHRONID));
}
for(int j = 0; j < talksets.length(); j++){
JSONObject talkset = talksets.getJSONObject(j);
talksetArr[j] = new Talkset(
talkset.getInt(TAG_CHRONID));
}
for(int k = 0; k < breakpoints.length(); k++){
JSONObject breakpoint = breakpoints.getJSONObject(k);
breakpointArr[k] = new Breakpoint(
breakpoint.getInt(TAG_CHRONID),
breakpoint.getLong(TAG_HOUR)
);
}
} catch (JSONException e) {
e.printStackTrace();
}
int playcutIndex = 0;
int talksetIndex = 0;
int breakpointIndex = 0;
int minID;
int i = 0;
/******** Algorithm to consolidate playcuts, breakpoints, and talksets into one arraylist by their chronological ID ********/
while(i < 30){
HashMap<String, String> map = new HashMap<String, String>();
minID = Math.max(
playcutArr[playcutIndex].chronID, (int) Math.max(
talksetArr[talksetIndex].chronID, breakpointArr[breakpointIndex].chronID
)
);
if(minID == playcutArr[playcutIndex].chronID) {
map.put(TAG_SONG, playcutArr[playcutIndex].song);
map.put(TAG_ARTIST, playcutArr[playcutIndex].artist);
map.put(TAG_ALBUM, playcutArr[playcutIndex].album);
map.put(TAG_LAYOUT, "Playcut");
map.put(TAG_CHRONID,""+playcutArr[playcutIndex].chronID);
StringBuilder stringBuilder = new StringBuilder("http://ws.audioscrobbler.com/2.0/");
stringBuilder.append("?method=album.getinfo");
stringBuilder.append("&api_key=");
stringBuilder.append("2ead17554acf667f27cf7dfd4c368f15");
String albumURL = null;
try {
stringBuilder.append("&artist=" + URLEncoder.encode(map.get(TAG_ARTIST), "UTF-8"));
stringBuilder.append("&album=" + URLEncoder.encode(map.get(TAG_ALBUM), "UTF-8"));
albumURL = new RetrieveAlbumArtUrlTask().execute(stringBuilder.toString()).get();
} catch (UnsupportedEncodingException e) {
albumURL = null;
} catch (InterruptedException e) {
albumURL = null;
} catch (ExecutionException e) {
albumURL = null;
} catch (IllegalArgumentException e) {
albumURL = null;
}
map.put("albumArtUrl", albumURL);
playcutIndex = playcutIndex + 1;
}
if(minID == talksetArr[talksetIndex].chronID) {
map.put(TAG_SONG, "Talkset");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Talkset");
map.put(TAG_CHRONID,""+talksetArr[talksetIndex].chronID);
talksetIndex = talksetIndex + 1;
}
if(minID == breakpointArr[breakpointIndex].chronID) {
map.put(TAG_SONG, "Breakpoint");
map.put(TAG_ARTIST, null);
map.put(TAG_LAYOUT, "Breakpoint");
map.put(TAG_HOUR, ""+breakpointArr[breakpointIndex].hour);
map.put(TAG_CHRONID,""+breakpointArr[breakpointIndex].chronID);
breakpointIndex = breakpointIndex + 1;
}
map.put("Clicked", "False");
oslist.add(map);
chronIDCheck = oslist.get(0).get(TAG_CHRONID);
i++;
}
Log.v("Test", "Background 2");
return null;
}
#Override
protected void onPostExecute(Void args) {
Log.v("TEST","POST");
/* If this is the first JSON Parse, we instantiate the adapter, otherwise we just update */
if(firstCall) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LiveAdapter(LiveStreamFragment.this.getActivity(), oslist, LiveStreamFragment.this, list);
list.setAdapter(adapter);
firstCall = false;
} else {
if(!adapter.chronIdCheck().equals(oslist.get(0).get(TAG_CHRONID))) {
//adapter.updateDataList(oslist);
update_button.setVisibility(View.VISIBLE);
buttonActivated = true;
}
}
}
}
The method onPostExecute is called on the UI thread, and you are doing a lot of things in it. Try keeping the code as from if(firstCall) in onPostExecute, because that is where you need to access the UI. The rest of the code above can be moved to doInBackground, which is invoked on a background thread.
From the docs :
doInBackground(Params...), invoked on the background thread
immediately after onPreExecute() finishes executing.
onPostExecute(Result), invoked on the UI thread after the background
computation finishes.
On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}