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 ?
Related
I am trying to fetch JSON object from an Api and display it on a checkList on a LinearLayout. Even though I am adding the checklist View to the container it is not showing. Is it the case that I have to use notifyDataSetChanged(), If so how can I implement it in LinearLayout.
Thank you . I do apologize for my english.
public class NasilYapilir extends Fragment {
int index;
private CheckBox checkBox;
private CheckBox[] checkBoxes;
List<Reciep> reciepList = new ArrayList<>();
LinearLayout linearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nasil_yapilir, container, false);
index = getArguments().getInt(DetailViewPager.KEY_INDEX_TAG);
load_data(index);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
checkBoxes = new CheckBox[reciepList.size()];
populateDirections(reciepList,linearLayout);
Log.i("we are in nasil yaplir",index + "");
return view;
}
public void populateDirections(List<Reciep> reciep, ViewGroup container){
int i = 0;
for(Reciep recieps : reciep){
checkBoxes[i] = new CheckBox(getActivity());
// checkBoxes[i].setPadding(8,16,8,16);
checkBoxes[i].setText(recieps.getQuantity()+ " "+ recieps.getUnit_ad()+ " "+ recieps.getIngredients_ad());
reciep.size();
container.addView(checkBoxes[i]);
i++;
}
}
public void load_data(int index) {
task.execute("http://yemekapp.kuarkdijital.com.tr/v_recipe.php?id=" + index);
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
JSONObject itemObject = null;
JSONObject quantityObject = null;
// JSONObject popularObject = null;
JSONObject jsonObject = new JSONObject(current);
String item = jsonObject.getString("item");
JSONArray itemArray = new JSONArray(item);
// JSONArray popularArray = new JSONArray(popular);
for (int i = 0; i < itemArray.length(); i++) {
itemObject = itemArray.getJSONObject(i);
String itemsQuantity = itemObject.getString("items");
JSONArray quantityArray = new JSONArray(itemsQuantity);
for(int j = 0; j<quantityArray.length() ;j++){
quantityObject = quantityArray.getJSONObject(i);
Reciep reciep = new Reciep(quantityObject.getString("Quantity"),quantityObject.getString("unit_ad"),quantityObject.getString("ingredient_ad"));
reciepList.add(reciep);
Log.i("quatityArray",quantityArray.get(j).toString());
}
// popularObject = popularArray.getJSONObject(i);
// DailyData DailyData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
// DailyData PopularData = new DailyData(popularObject.getInt("id"), popularObject.getString("Servings"), popularObject.getString("Title"), popularObject.getString("CookTime"), popularObject.getString("Image"));
// daily_data_list.add(DailyData);
// popular_data_list.add(PopularData);
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// notifyDataSetChanged();
}
};
}
Try this code
public class NasilYapilir extends Fragment {
int index;
private CheckBox checkBox;
private CheckBox[] checkBoxes;
List<Reciep> reciepList = new ArrayList<>();
LinearLayout linearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nasil_yapilir, container, false);
index = getArguments().getInt(DetailViewPager.KEY_INDEX_TAG);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
checkBoxes = new CheckBox[reciepList.size()];
load_data(index);
//populateDirections(reciepList,linearLayout);
Log.i("we are in nasil yaplir",index + "");
return view;
}
public void populateDirections(List<Reciep> reciep, ViewGroup container){
int i = 0;
for(Reciep recieps : reciep){
checkBoxes[i] = new CheckBox(getActivity());
// checkBoxes[i].setPadding(8,16,8,16);
checkBoxes[i].setText(recieps.getQuantity()+ " "+
recieps.getUnit_ad()+ " "+ recieps.getIngredients_ad());
reciep.size();
container.addView(checkBoxes[i]);
i++;
}
}
public void load_data(int index) {
task.execute("http://yemekapp.kuarkdijital.com.tr/v_recipe.php?id=" + index);
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String current) {
super.onPostExecute(current);
if(current.isEmpty())
return;
JSONObject itemObject = null;
JSONObject quantityObject = null;
JSONObject jsonObject = new JSONObject(current);
String item = jsonObject.getString("item");
JSONArray itemArray = new JSONArray(item);
for (int i = 0; i < itemArray.length(); i++) {
itemObject = itemArray.getJSONObject(i);
String itemsQuantity = itemObject.getString("items");
JSONArray quantityArray = new JSONArray(itemsQuantity);
for(int j = 0; j<quantityArray.length() ;j++){
quantityObject = quantityArray.getJSONObject(i);
Reciep reciep = new Reciep(quantityObject.getString("Quantity"),quantityObject.getString("unit_ad"),quantityObject.getString("ingredient_ad"));
reciepList.add(reciep);
Log.i("quatityArray",quantityArray.get(j).toString());
}
}
populateDirections(reciepList,linearLayout);
}
}
}
hello i want to get string from activity and set it to the another non activity class please help me i am adding my code.and i need to set the edittext value in non activity class url. help me
my activity.
public class AlertForIp extends AppCompatActivity {
String value;
private Button mButton;
final Context c = this;
static String urlString;
private static AlertForIp instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
instance = this;
final EditText input = new EditText(AlertForIp.this);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
/* SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
final SharedPreferences.Editor editor = prefss.edit();*/
value = input.getText().toString();
// Setting Dialog Title
String urlsss="http://";
String urls=":1219/Json/Handler.ashx";
// This above url string i need to set in that class
urlString = urlsss+value+urls;
/* editor.putString("stringid", urlString); //InputString: from the EditText
editor.commit();
*/
alertDialog.setTitle("WELCOME TO RESTROSOFT");
// Setting Dialog Message
alertDialog.setMessage("ENTER YOUR IP");
//final EditText input = new EditText(this);
//alertDialog.setView(input);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
//input.setText("http://");
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt
.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i = 0; i < splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
return "";
}
}
}
}
return null;
}
};
input.setFilters(filters);
//input.setText(ip);
alertDialog.setView(input); //
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.waiting);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*if(input.getText().length()==0)
{
input.setError("Field cannot be left blank.");
dialog.dismiss();
}*/
String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";
if (value.matches(validation))
{
Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
// or
}
else if(!input.getText().toString().equals(""))
{
Intent intent = new Intent(AlertForIp.this, Sample.class);
startActivity(intent);
//Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else
{
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
//dialog.cancel();
finish();
}
});
// closed
// Showing Alert Message
alertDialog.show();
}
public static Context getContext() {
RestAPI rss=new RestAPI();
rss.persistItems(urlString);
return instance.getApplicationContext();
}
}
And here is my no activity class
public class RestAPI {
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
This is my another Activity i have created the instance of restApi
public class UserDetailsActivity extends Activity {
TextView tvFisrtName, tvLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
// Show the Up button in the action bar.
//setupActionBar();
tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
tvLastName=(TextView)findViewById(R.id.tv_lastname);
Intent i=getIntent();
String username=i.getStringExtra("User_Name");
new AsyncUserDetails().execute(username);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
{
String str1;
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonObj = null;
//here i have error
RestAPI api = new RestAPI();
try {
jsonObj = api.GetUserDetails(params[0]);
//JSONParser parser = new JSONParser();
//userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
try {
JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);
str1=jsonObj.getString("user_id").toString();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();
tvFisrtName.setText(str1);
}
}
public class RestAPI {
String url;
// create constructor here
public RestAPI(String url){
this.url=url;
}
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
now you can use here url directly
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
use here
RestAPI rss=new RestAPI(urlString );
I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}
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.
Following is my coding for downloading the data from web and on post execute I save it to DB and then update the ListAdapter for GUI.
Problem is when saving to the DB, screen freezes for the time it is getting saved in DB and for 600 records it is about 20 secs.
Please let me know, how can I change this, so that UI do not freeze.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
try {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
if((result==null)|| result.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
long endTime = System.currentTimeMillis();
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
}
}
catch (JSONException e) {
Log.e("log tag", "Error parsing data" + e.toString());
}
}
}
Changed Code as Suggested, screen do not freeze now, but I f I move to another screen , it crashes on the post execute.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("value of the response"+response);
//adding new */
if((response==null)|| response.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray;
try {
jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
System.out.println("All the not empty");
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
System.out.println("im area of tarinin");
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
System.out.println("Time for one JSON parsing "
+ (System.currentTimeMillis() - insideStart));
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog.dismiss();
}
}
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
System.out.println("category id on lcick listnere inside the post ecexute" + category_id);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
The database operation should be done in doInBackground()
Just like LuxuryMode says, all blocking operations need to be in background.
The problem with your approach is that you put all this in Activity, lifecycle of which is not appropriate for background operations.
Create application model that lives outside (usually in Application subclass) and move your AsyncTask there. In Activities bind to that model using simple pattern like observer/callback to update your Adapter.