No value for "Invoice" - java

Anyone knows what might be the reason why my "invoice" does not have an value? Tallied with the php response , it is called invoice. At this line String invoice = jtransaction.getString("invoice");
public static ArrayList<Transaction> getMemberTransactions(String memberId)
{
String url= second_URL + "get_member_transactions.php";
String method = GET;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("member_id", memberId));
JSONObject result = makeHttpRequest(url, method, params);
try {
if (result.getInt("success") == 1) {
ArrayList<Transaction> list = new ArrayList<Transaction>();
JSONArray jItems = result.getJSONArray("transaction_info");
int count = jItems.length();
for (int i = 0; i < count; i++) {
JSONObject jtransaction = jItems.getJSONObject(i);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT,
Locale.US);
Date date = null;
try {
date = sdf.parse(jtransaction.getString("date"));
} catch (ParseException e) {
e.printStackTrace();
}
String invoice = jtransaction.getString("invoice");
String warehouse = jtransaction.getString("warehouse");
Transaction transaction = new Transaction(date,invoice, warehouse);
list.add(transaction);
}
return list;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
php
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$transactionInfo[]["date"] = get_date($row['Transaction_Date']);
$transactionInfo[]["invoice"] = $row['Invoice_No'];
$transactionInfo[]["warehouse"] = $row['WarehouseName'];
}
if(!empty($transactionInfo)===true)
{
response_success($transactionInfo);
}
function response_success($transactionInfo) {
$response = array();
$response["success"] = 1;
$response["transaction_info"] = $transactionInfo;
echo json_encode($response);
exit;
}

This:
$transactionInfo[]["date"] = get_date($row['Transaction_Date']);
$transactionInfo[]["invoice"] = $row['Invoice_No'];
$transactionInfo[]["warehouse"] = $row['WarehouseName'];
will create three separate items in $transactionInfo, one containing date, one with invoice and one with warehouse.
Example:
array(3) {
[0]=>
array(1) {
["date"]=>
string(10) "2014-10-20"
}
[1]=>
array(1) {
["invoice"]=>
string(5) "08/15"
}
[2]=>
array(1) {
["warehouse"]=>
int(13)
}
}
I suppose you want them in one item, so you have to build it like this:
$item["date"] = get_date($row['Transaction_Date']);
$item["invoice"] = $row['Invoice_No'];
$item["warehouse"] = $row['WarehouseName'];
// now add the item to the array
$transactionInfo[] = $item;
Example:
array(1) {
[0]=>
array(3) {
["date"]=>
string(10) "2014-10-20"
["invoice"]=>
string(5) "08/15"
["warehouse"]=>
int(13)
}
}

Related

OkHttp doesn't get the entire JSON

My JSON file that I host in my VPS is 2.2 MB and when I use OkHttp to create a request to retrieve it and then log the JSON I see that not all the JSON was requested.
My code:
public void sendJSONRequest() {
// init http client
mOkHttpClient = new OkHttpClient();
// init a request
mRequest = new okhttp3.Request.Builder().url(url).build();
// execute the request (async)
mOkHttpClient.newCall(mRequest).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, e.getMessage());
}
#Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Log.i(TAG, response.body().string());
parseGameJSONResponse(response.body().string());
}
});
}
The error that gets throw within parseGameJSONResponse:
java.lang.IllegalStateException: closed
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:398)
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:392)
at okhttp3.internal.Util.bomAwareCharset(Util.java:449)
at okhttp3.ResponseBody.string(ResponseBody.java:174)
The error is thrown because the JSON was cut
parse json method:
public ArrayList<Game> parseGameJSONResponse(String json) {
ArrayList<Game> upcomingGames = new ArrayList<>();
// Main JSON Object
JSONObject mainJsonObject = null;
try {
mainJsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
boolean removeDuplicates = mSettingsValue.getRemoveDuplicates();
if (mainJsonObject != null) {
// MAIN JSON Data Array
JSONArray jsonArray = null;
try {
jsonArray = mainJsonObject.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArray != null && jsonArray.length() > 0) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject gameObject = jsonArray.getJSONObject(i);
Game game = new Game();
if (gameObject.has("id")) {
game.id = gameObject.getInt("id");
}
if (gameObject.has("name")) {
String name = gameObject.getString("name");
game.name = name;
if (name.endsWith("Edition") && removeDuplicates) {
// skip this iteration because it's a special edition and we don't want editions if setting is set to true
continue;
}
}
if (gameObject.has("slug")) {
// Creates the URL here
game.url = gameObject.getString("slug");
}
if (gameObject.has("updated_at")) {
game.updated_at = gameObject.getLong("updated_at");
}
if (gameObject.has("summary")) {
game.summary = gameObject.getString("summary");
}
if (gameObject.has("first_release_date")) {
game.first_release_date = gameObject.getLong("first_release_date");
}
// Game Release Dates
if (gameObject.has("release_dates")) {
JSONArray jsonReleaseDatesArray = gameObject.getJSONArray("release_dates");
ArrayList<ReleaseDate> releaseDates = new ArrayList<>();
for (int y = 0; y < jsonReleaseDatesArray.length(); y++) {
ReleaseDate releaseDate = new ReleaseDate();
JSONObject jsonReleaseDateObject = jsonReleaseDatesArray.getJSONObject(y);
if (jsonReleaseDateObject.has("category") && !jsonReleaseDateObject.isNull("category")) {
releaseDate.category = jsonReleaseDateObject.getInt("category");
}
if (jsonReleaseDateObject.has("platform") && !jsonReleaseDateObject.isNull("platform")) {
releaseDate.platform = jsonReleaseDateObject.getInt("platform");
}
if (jsonReleaseDateObject.has("date") && !jsonReleaseDateObject.isNull("date")) {
releaseDate.date = jsonReleaseDateObject.getLong("date");
}
if (jsonReleaseDateObject.has("region") && !jsonReleaseDateObject.isNull("region")) {
releaseDate.region = jsonReleaseDateObject.getInt("region");
// Toast.makeText(getContext(), releaseDate.region + ": Region", Toast.LENGTH_SHORT).show();
}
if (jsonReleaseDateObject.has("y") && !jsonReleaseDateObject.isNull("y")) {
releaseDate.year = jsonReleaseDateObject.getInt("y");
}
if (jsonReleaseDateObject.has("m") && !jsonReleaseDateObject.isNull("m")) {
releaseDate.month = jsonReleaseDateObject.getInt("m");
}
if (jsonReleaseDateObject.has("human") && !jsonReleaseDateObject.isNull("human")) {
releaseDate.human = jsonReleaseDateObject.getString("human");
}
releaseDates.add(releaseDate);
}
game.releaseDates = releaseDates;
}
// Screenshots
if (gameObject.has("screenshots")) {
JSONArray jsonScreenshotsArray = gameObject.getJSONArray("screenshots");
ArrayList<String> screenshots = new ArrayList<>();
for (int y = 0; y < jsonScreenshotsArray.length(); y++) {
JSONObject jsonScreenshotObject = jsonScreenshotsArray.getJSONObject(y);
screenshots.add(jsonScreenshotObject.getString("cloudinary_id"));
}
game.screenshots = screenshots;
}
// Videos
if (gameObject.has("videos")) {
ArrayList<String> videos = new ArrayList<>();
JSONArray jsonVideosArray = gameObject.getJSONArray("videos");
for (int y = 0; y < jsonVideosArray.length(); y++) {
JSONObject jsonVideoObject = jsonVideosArray.getJSONObject(y);
videos.add(jsonVideoObject.getString("video_id"));
}
game.videos = videos;
}
// Cover image
if (gameObject.has("cover")) {
JSONObject jsonCoverObject = gameObject.getJSONObject("cover");
game.cover = jsonCoverObject.getString("cloudinary_id");
}
// Websites
if (gameObject.has("websites")) {
JSONArray jsonWebsitesArray = gameObject.getJSONArray("websites");
ArrayList<Website> websites = new ArrayList<>();
for (int y = 0; y < jsonWebsitesArray.length(); y++) {
Website website = new Website();
JSONObject jsonWebsiteObject = jsonWebsitesArray.getJSONObject(y);
website.category = jsonWebsiteObject.getInt("category");
website.url = jsonWebsiteObject.getString("url");
websites.add(website);
}
game.websites = websites;
}
upcomingGames.add(game);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getContext(), "" + upcomingGames.size(), Toast.LENGTH_SHORT).show();
return upcomingGames;
}
Thank you guys. Really appreciate any kind of help so thanks
It seems it tries to read same InputStream twice (may not save in memory).
I think you should use just response.string() instead of response.body().string().
Also if you think it might be related to timing you can edit timeouts.
client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
For more look at this.
https://github.com/square/okhttp/issues/1240

How to parsing multi dimensional json data array in android studio.? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
i have problem to parse my json data,
this is my json data :
{"data":
[
{"ean": "222222","itemname": "","location": "001010202,001010201","po":[
{"ponumber": 1,"qty": 22
},
{"ponumber": 2,"qty": 33
}
]
},
{
"ean": "11112222",
"itemname": "เหงือก",
"location": "001010601",
"po": [
{
"ponumber": 1,
"qty": 7
}
]
},
{
"ean": "22223333",
"itemname": "Crystal Water",
"location": "001010410,001010401",
"po": [
{
"ponumber": 3,
"qty": 13
}
]
}
]}
i want to show the output like :
thank you
this is my java code to parsing json data and show to listview :
void parseJsonData(String jsonString) throws JSONException {
String data = "";
String data2 = null;
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname +"\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++ ) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2 = "\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n";
list.add(data+data2);
System.err.println(data+data2);
}
}
ArrayAdapter<String> LVarray;
LVarray = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(LVarray);
}
this is screen shot the output:
1.You can use StringBuilder to save the data2(po List).
2.In the inner for loop ,you can use append method to add it in it .
3.Get the length of StringBuilder .Then remove the saved data2.
4.Then you can save again .
Edit
public void parseJsonData(String jsonString) throws JSONException {
String data = "";
StringBuilder data2 = new StringBuilder();
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname + "\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2.append("\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n");
list.add(data + data2);
}
System.err.println(data + data2);
int sb_length = data2.length();
data2.delete(0, sb_length);
}
}
this also can help
try {
//Get root array
JSONArray data_array = jsonObject.getJSONArray("data");
for (int i=0;i<data_array.length();i++){
JSONObject jsonObject1 = array.getJSONObject(i);
String ean = jsonObject1.optString("ean");
String itemname = jsonObject1.optString("itemname");
String location = jsonObject1.optString("location");
JSONArray child_Array = jsonObject1.getJSONArray("po");
for (int j=0;j<childArray.length();j++){
JSONObject childJosnObject = array.getJSONObject(i);
String ponumber = jsonObject1.optString("ponumber");
String qty = jsonObject1.optString("qty");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You have to try like this, it will help you
JsonParseModel jsonParseModel = new Gson().fromJson(jsonString,JsonParseModel.class);
public class JsonParseModel {
private ArrayList<DataClass> data;
public ArrayList<DataClass> getData() {
return data;
}
public void setData(ArrayList<DataClass> data) {
this.data = data;
}
public class DataClass{
private String ean,itemname,location;
private ArrayList<PoData> po;
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ArrayList<PoData> getPo() {
return po;
}
public void setPo(ArrayList<PoData> po) {
this.po = po;
}
public class PoData{
private int ponumber,qty;
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
}
}
private void parseJsondata(String response) {
try {
// response
JSONObject jsonObject = new JSONObject(response);
// get data from JSONArray
JSONArray data = jsonObject.getJSONArray("data");
// for loop to your JSONArray's Strings
for (int i = 0; i < data.length(); i++) {
// get JSONObject from i
JSONObject jo = data.getJSONObject(i);
// get string
String ean = jo.getString("ean");
String itemname = jo.getString("itemname");
String location = jo.getString("location");
JSONArray jA = jo.getJSONArray("po");
for (int j = 0; j < jA.length(); j++) {
// get JSONObject by jO
JSONObject jO = jA.getJSONObject(i);
// get string
String ponumber = jO.getString("ponumber");
String qty = jO.getString("qty");
}
}
//Log response
Log.e("response:", response);
} catch (JSONException e) {
e.printStackTrace();
}
}

How to replace System.out.println as return when parsing JSON ?

String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
System.out.println("Sentence is:: " + s);
System.out.println("Id is:: " + id);
System.out.println("text file is:: " + txtFile);
}
} catch (JSONException e) {
e.printStackTrace();
}
currently, the above code is able to print out all the records. However, I would like to change the system.out.println into return variables such as return ID, return txtFile, return sentence. How to do that?
Create an Object. use an arraylist to store your object and use it later.
public class myItem{
String sentence;
int id;
String txtfile;
public myItem(){
}
public String getSentence(){
return sentence;
}
public setSentence(String s){
this.sentence = sentence;
}
}
public void yourFunction(){
try {
ArrayList <myItem> myList = new ArrayList();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
myItem newItem = new myItem();
newItem.setSentence(s);
myList.add(newItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I agree with what Zhi Kai said in the comment.
PS. I can't comment yet so I'm writing this as an answer.
Create a POJO and u se data structure. In your case you are using a for loop so I assume you need to return a list of values from your JSONArray.
Here's what you can do.
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
Updated:
public class YourObject {
private String id;
private String txtFile;
private String sentence;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxtFile() {
return txtFile;
}
public void setTxtFile(String txtFile) {
this.txtFile = txtFile;
}
public String getSentence() {
return sentence;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
}
public List<YourObject> returnObject(){
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
}

Java - JSONObject Parsing only 1 string?

I'm fairly new to JSON parsing in Java but when I try and parse this JSON String & find out it's "ID", it repeats the same one twice.
[
{"id":"{ID1}","time":123},
{"id":"{ID2}","time":124}
]
This is my Java code:
// v = json string, c = "id"
String output = v.replace("[", "").replace("]", "");
JSONObject obj = new JSONObject(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < obj.length(); i++){
System.out.println(obj.getString(c));
list.add(obj.getString(c));
}
return list.get(1);
it returns ID1 twice or more. Please help
Your JSON represents an array - so that's how you should parse it. You can then easily get the id property from each JSONObject within the array. For example:
import org.json.*;
public class Test {
public static void main(String[] args) throws JSONException {
String json =
"[{\"id\":\"{ID1}\",\"time\":123}, {\"id\":\"{ID2}\",\"time\":124}]";
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
System.out.println(o.getString("id"));
}
}
}
Output:
{ID1}
{ID2}
I fixed my code by using it as a JSONArray(Thanks #HotLicks)
JSONArray obj = new JSONArray(v);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < obj.length(); i++){
Logger.WriteOutput(obj.getJSONObject(i).getString(c), Logger.LogLevel.Info);
}
Try this :
// This line is useless
// String output = v.replace("[", "").replace("]", "");
JSONArray arr = new JSONArray(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < arr.length(); i++){
System.out.println(arr.getJSONObject(i).getString(c));
list.add(arr.getJSONObject(i).getString(c));
}
First create a java bean for your json (for example here):
public class Item {
#JsonProperty("id")
private String id;
#JsonProperty("time")
private Integer time;
public final String getId() {
return id;
}
public final void setId(String id) {
this.id = id;
}
public final Integer getTime() {
return time;
}
public final void setTime(Integer time) {
this.time = time;
}
}
If you are using Jackson Java JSON-processor, you can create a List from JSON-String this way:
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Item> items = objectMapper.readValue(
yourJSONString,
objectMapper.getTypeFactory().constructCollectionType(List.class, Item.class));
for (Item item : items) {
System.out.println(item.getId());
}
} catch (IOException e) {
e.printStackTrace();
}
use below code
String v = "[{\"id\":\"ID1\",\"time\":123},{\"id\":\"ID2\",\"time\":124}]";
String c = "id";
JSONArray obj = null;
try {
obj = new JSONArray(v);
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < obj.length(); i++) {
JSONObject j = (JSONObject) obj.get(i);
System.out.println(j.getString(c));
list.add(j.getString(c));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
note that i have slightly corrected the json structure too
before
[
{"id":"{ID1}","time":123},
{"id":"{ID2}","time":124}
]
after
[
{"id":"ID1","time":123},
{"id":"ID2","time":124}
]

Something in AsyncTask Blocking the UI - causing interface to halt briefly

I have a listview that is populated thru SQLite with cache data. After it finishes loading. in the background I check for new data and get a returned JSON result from a MySQL db.
In my onPostExecute of this background task, when this code is ran (the code below), and while it is being looped thru (a maximum of 50 loops), the UI thread is blocked and scrolling a ListView is not possible. Here is code:
if (result.length() != 0) {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int ii = 0; ii < jArray.length(); ii++) {
json_data = jArray.getJSONObject(ii);
item = json_data.getString("item");
cat = json_data.getString("category");
user = json_data.getString("username");
userId = json_data.getLong("user_id");
review = json_data.getString("review");
reviewId = json_data.getLong("review_id");
itemId = json_data.getLong("item_id");
commentCount = json_data.getLong("commentCount");
url = json_data.getString("name");
url = pathUrl + url; // for profile icon
date = json_data.getString("date");
rating = json_data.getDouble("rating");
upVote = json_data.getLong("good");
wiki = json_data.getString("wiki");
watchItems.add(item);
watchCats.add(cat);
watchUsers.add(user);
watchReviews.add(review);
watchUrl.add(url);
watchDateList.add(date);
watchWikiList.add(wiki);
watchItemIdList.add(String.valueOf(itemId));
watchUserIds.add(String.valueOf(userId));
watchReviewId.add(String.valueOf(reviewId));
watchRating.add(String.valueOf(rating));
watchCommentCount.add(String.valueOf(commentCount));
watchUpVote.add(String.valueOf(upVote));
Rateit.haveFollowing = "1";
if (Rateit.isUserLoggedIn == true) {
boolean oldReview = datasource
.getReviewIds(reviewId);
if (!oldReview) {
// Cache Network Items
datasource.createTrendWatch(itemId, item,
review, reviewId, cat, user,
String.valueOf(userId), url, date,
commentCount, rating, upVote, 0,
wiki);
}
}
FollowingItems wti = new FollowingItems(
Long.valueOf(watchItemIdList.get(i)),
watchItems.get(i), watchCats.get(i),
watchReviews.get(i),
Long.valueOf(watchReviewId.get(i)),
watchUsers.get(i),
Long.valueOf(watchUserIds.get(i)),
watchUrl.get(i), watchDateList.get(i),
Long.valueOf(watchCommentCount.get(i)),
Double.valueOf(watchRating.get(i)),
Long.valueOf(watchUpVote.get(i)),
watchWikiList.get(i++));
watchingListObject.add(wti);
}
}
Why is this happening? And how can I prevent my code to prevent this? Are there any optimizations I can make?
Edit: Someone below requested full task code.
Below repeats the code above but in context with entire task.
public static class FollowingTask extends AsyncTask<String, String, Void> {
protected InputStream is = null;
protected String result = "";
protected String userId;
protected ArrayList<FollowingItems> watchingListObject;
protected Context mContext;
public FollowingTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
if (mContext != null && (fromRefresh == false)) {
((MainFragmentActivity) mContext)
.setSupportProgressBarIndeterminateVisibility(true);
}
resetLists();
if (PrefActivity.getUserLoggedInStatus(mContext) == true) {
userId = PrefActivity.getLoggedInUserId(mContext);
} else {
userId = "-1";
}
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
datasource.purgeItemWatchingTable();
Log.d("1", "Back");
String url_select = "http://www.---.info/includes_mc_php/featured_watching.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_id", userId));
param.add(new BasicNameValuePair("v2", "true"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void v) {
String pathUrl = Rateit.PROFILE_PIC_URL;
String item, cat, user, review, url, date, following, wiki;
long itemId, reviewId, userId, commentCount, upVote;
double rating;
int i = 0;
watchingListObject = new ArrayList<FollowingItems>();
try {
String c = String.valueOf(result.charAt(0));
if (c.equals("{")) {
JSONObject jsonObject = new JSONObject(result);
following = jsonObject.getString("following");
if (following.equals("0")) {
Rateit.haveFollowing = "0";
}
} else {
if (result.length() != 0) {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int ii = 0; ii < jArray.length(); ii++) {
json_data = jArray.getJSONObject(ii);
item = json_data.getString("item");
cat = json_data.getString("category");
user = json_data.getString("username");
userId = json_data.getLong("user_id");
review = json_data.getString("review");
reviewId = json_data.getLong("review_id");
itemId = json_data.getLong("item_id");
commentCount = json_data.getLong("commentCount");
url = json_data.getString("name");
url = pathUrl + url; // for profile icon
date = json_data.getString("date");
rating = json_data.getDouble("rating");
upVote = json_data.getLong("good");
wiki = json_data.getString("wiki");
watchItems.add(item);
watchCats.add(cat);
watchUsers.add(user);
watchReviews.add(review);
watchUrl.add(url);
watchDateList.add(date);
watchWikiList.add(wiki);
watchItemIdList.add(String.valueOf(itemId));
watchUserIds.add(String.valueOf(userId));
watchReviewId.add(String.valueOf(reviewId));
watchRating.add(String.valueOf(rating));
watchCommentCount.add(String.valueOf(commentCount));
watchUpVote.add(String.valueOf(upVote));
Rateit.haveFollowing = "1";
if (Rateit.isUserLoggedIn == true) {
boolean oldReview = datasource
.getReviewIds(reviewId);
if (!oldReview) {
// Cache Network Items
datasource.createTrendWatch(itemId, item,
review, reviewId, cat, user,
String.valueOf(userId), url, date,
commentCount, rating, upVote, 0,
wiki);
}
}
FollowingItems wti = new FollowingItems(
Long.valueOf(watchItemIdList.get(i)),
watchItems.get(i), watchCats.get(i),
watchReviews.get(i),
Long.valueOf(watchReviewId.get(i)),
watchUsers.get(i),
Long.valueOf(watchUserIds.get(i)),
watchUrl.get(i), watchDateList.get(i),
Long.valueOf(watchCommentCount.get(i)),
Double.valueOf(watchRating.get(i)),
Long.valueOf(watchUpVote.get(i)),
watchWikiList.get(i++));
watchingListObject.add(wti);
Log.d("1", "Post 2");
}
} else {
Rateit.haveFollowing = "2";
}
}
} catch (JSONException e1) {
e1.printStackTrace();
Rateit.haveFollowing = "2";
} catch (ParseException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("1", "Post COMPLETE");
mPullRefreshListView.onRefreshComplete();
// Reset Trending List on Pull-to-Refresh
if (mContext != null) {
if (watchUsers.size() == 0) {
l.setVisibility(View.VISIBLE);
tv.setTypeface(TypeFace.get(mContext, Rateit.BPREPLAY));
} else {
l.setVisibility(View.GONE);
}
if (mContext != null) {
listView.setAdapter(null);
if (watchItems.size() > 0) {
wAdapter = new FollowingAdapter(mContext,
watchingListObject, TypeFace.get(mContext,
Rateit.BPREPLAY), TypeFace.get(
mContext, Rateit.ROBOTO_LIGHT),
TypeFace.get(mContext, Rateit.ROBOTO_THIN),
TypeFace.get(mContext, Rateit.ROBOTO_REGULAR));
listView.setAdapter(wAdapter);
}
}
}
if (mContext != null && (fromRefresh == false)) {
((MainFragmentActivity) mContext)
.setSupportProgressBarIndeterminateVisibility(false);
MainFragmentActivity.dismissDialog(mContext);
}
fromRefresh = false;
}
}
onPostExecute runs on the UI thread. It will block the UI. doInBackground runs in the background. You should perform heavy opertaions in the doInBackground (not in onPostExecute)
Solution: you should move the parsing etc. from the onPostExecute to doInBackground and use the onPostExecute just for binding the processed information to the UI.
I would suggest as first thing to profile that code and measure how much time exactly is spent to execute it. This way at least you understand if your problem is really here or somewhere else

Categories

Resources