loading data from online MySQL database to android application - java

I am using this code to load data from online database to my android application .
I am wondering what can i add to make this code better ?
Sometimes the progress dialog keeps spinning and never gets the data, the application is stuck then, any ideas on how i can prevent that ?
class LoadAllSections extends AsyncTask<String, String, String>
{
// make a progress dialog appear with the selected specifics
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading all sections, please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// in the background run this code to retrieve data from the server
protected String doInBackground(String... args)
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_Sections,"POST", params);
try
{
int success = json.getInt(TAG_SUCCESS);
sections = json.getJSONArray(TAG_SECTIONS);
if (success == 1)
{
for (int i = 0; i < sections.length(); i++)
{
JSONObject c = sections.getJSONObject(i);
section_id = c.getString(TAG_SECTION_ID);
section_name = c.getString(TAG_SECTION_NAME);
section_desc = c.getString(TAG_SECTION_DESC);
section_image = c.getString(TAG_SECTION_IMAGE);
section_valid = c.getString(TAG_SECTION_VALID);
HashMap <String,String> sectionmap = new HashMap<String,String>();
sectionmap.put(TAG_SECTION_ID, section_id);
sectionmap.put(TAG_SECTION_NAME, section_name);
sectionmap.put(TAG_SECTION_DESC, section_desc);
sectionmap.put(TAG_SECTION_IMAGE, section_image);
sectionmap.put(TAG_SECTION_VALID, section_valid);
sectionlist.add(sectionmap);
}
}
else
{
finish();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
// disable the progress dialog and load data to the gridview
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
adapter=new SectionAdapter(MainActivity.this,sectionlist);
SectionsGridView.setAdapter(adapter);
}
}

I wanted to add a comment, but I am not allowed to.
Don't have enough reputation :-(
Pass url_section as argument to doInBackground instead of making it global.
I would place the httpRequest insde a try catch block.
Did you set the timeout, if the httpRequest is not answering? I would set that to
60 seconds. I think by default this is set to 600 seconds.
Why do you pass the file_url to onPostExecute instead of passing the
sectionList?
Take a look at AsyncTask. If you don't want to pass anything between the methods, you can also use Void. So in your case AsyncTask would also do it.

Related

Azure mobile service asynctask

I got some trouble using the asynctask to query in my cloud database.
Due the response delay to query I cant get the result correctly. Getting NULL.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
this.mBox = new Box();
super.onCreate(savedInstanceState);
setContentView(R.layout.novomenu_layout);
InicializaAzure(); // init connection to azure mobile service
this.mPalletDao = new PalletDAO(this);
this.mBoxDao = new BoxDAO(this);
mBox = mBoxDao.AzureGetBoxById(1); // query the cloud database
}
BoxDAO.java
public Box AzureGetBoxById(final long id){
final Box[] box = new Box[1];
final boolean[] flag = {false};
new AsyncTask<Void, Void, Void>() {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<Box> result = mBoxTable.where().field("id").eq(id).execute().get();
Box mBox = result.get(0);
box[0] = mBox;
} catch (Exception exception) {
//createAndShowDialog(exception, "Error");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
flag[0] = true;
}
}.execute();
return box[0];
//return null;
}
I am getting always NULL until the asynctask has finished. but I need the result in the same time.
How can I solve that? I've searched about asynctask but I didnt find anything like this.
Thank you.
Your code is correct, and it works fine. However, if you want to get the result to show in the same time of UI displayed, you can not solve it easily by using the asynctask.
Per my experience, there are two ways can help solve that.
Remove the asynctask code and use the sync method to get data, but it will cause UI hang so that it not be recommended.
Use MobileServiceSyncTable to enable offline sync to solve it.
There is a sample doc https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-get-started-offline-data/ to help adding offline data sync into your app.
You alse can watch some vedio to learn it, please move to http://channel9.msdn.com/Shows/Cloud+Cover/Episode-155-Offline-Storage-with-Donna-Malayeri and http://azure.microsoft.com/documentation/videos/azure-mobile-services-offline-enabled-apps-with-donna-malayeri/.

Retriving data using Android app using JSON and MySql

I'm trying to retrive data using WiFi but the application is crashing. When I use the localHost Emulator it is working just fine but when I use mobile data or WiFi it crashes. I can save data to MySql on localhost using WiFi but I just cant receive the data. Some of the time I get android.os.NetworkonMainThreadException. I'm a very new programmer just borrowed most of the code and need to clearly state how this can be resolved.
/**
* Background Async Task to Get complete User details
* */
class GetUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting User details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_ID", "2"));
// getting User details by making HTTP request
// Note that User details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "GET", params);
// check your log for json response
Log.d("Single User Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received User details
JSONArray UserObj = json
.getJSONArray(TAG_User); // JSON Array
// get first User object from JSON Array
JSONObject User = UserObj.getJSONObject(0);
// User with this pid found
// Edit Text
txtlname = (EditText) findViewById(R.id.editText1);
txtfname = (EditText) findViewById(R.id.editText2);
// display User data in EditText
txtfname.setText(User.getString(TAG_FNAME));
txtlname.setText(User.getString(TAG_LNAME));
}else{
// User with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Actually you shouldn't connect to internet in UI thread.
You connected to internet through JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "GET", params); in runOnUiThread( new Runnable.....
/**
* Background Async Task to Get complete User details
* */
class GetUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting User details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_ID", "2"));
// getting User details by making HTTP request
// Note that User details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "GET", params);
// check your log for json response
Log.d("Single User Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received User details
JSONArray UserObj = json
.getJSONArray(TAG_User); // JSON Array
// get first User object from JSON Array
final JSONObject User = UserObj.getJSONObject(0);
runOnUiThread(new Runnable() {
public void run() {
// User with this pid found
// Edit Text
txtlname = (EditText) findViewById(R.id.editText1);
txtfname = (EditText) findViewById(R.id.editText2);
// display User data in EditText
txtfname.setText(User.getString(TAG_FNAME));
txtlname.setText(User.getString(TAG_LNAME));
}
});
}else{
// User with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
As you can see I just returned to UI thread when I want to work with views (like text views). Pay attention to user variable. I made it final to make it reachable inside the Runnable object I used as the parameter of runOnUiThread method.
You shouldn't execute UI related code in doInBackground, you should move UI related code to onPostExecute or onProgressUpdate methods of your AsyncTask.
This answer might help you:
Android : Calling the methods on UI thread from AsyncTask doInBackground method

display hashmapped values in alertbox in android

I am getting some details from webservice and i need to display those details with checkboxes associated with it on its leftside dynamically(using java code).I already mapped all details to a Hashmap Arraylist correctly,What to do next is that display all the details to the alertbox,which is defined in my code..I tried a lot.Can anybody help me any help will be highly appreciable.....
selectButton.setOnClickListener(new View.OnClickListener() {
private Builder mDialog;
#Override
public void onClick(View v) {
Log.e(tag,"alertbox for onclickworked");
Context c =getParent();
this.mDialog = new AlertDialog.Builder(c);
alertDialog = mDialog.create();
// Setting Dialog Title
alertDialog.setTitle("Intrested In");
new Serviceclass().execute();
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.gate_logo);
alertDialog.show();
}
class Serviceclass extends AsyncTask<Void, Void, String>
{
protected String doInBackground(
Void... params) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Log.e(tag,"inside getvaluesforcheckbox()");
offferList = new ArrayList<HashMap<String, String>>();
Log.e(tag,"arraylist created");
try{
UserFunctions usf=new UserFunctions();
JSONObject json2 = usf.intrestlist(user_id);
Log.e(tag,"before try");
Log.e(tag,"after try");
JSONArray contacts = json2.getJSONArray("interested_list");
Log.e(tag,"outside forloop");
for(int i = 0; i < contacts.length(); i++){
Log.e(tag,"inside forloop");
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = contacts.getJSONObject(i);
map.put(KEY_INTRESTID, c.getString("interested_id"));
Log.e("requestclass.java",c.getString("interested_id"));
map.put(KEY_INTRESTNAME, c.getString("interested_name"));
Log.e("requestclass.java",c.getString("interested_name"));
map.put(KEY_STAUS, c.getString("status"));
Log.e("requestclass.java",c.getString("status"));
if(c.getString("interested_info").equals("null"))
{
map.put(KEY_INTERESTINFO,"");
}
else
{
map.put(KEY_INTERESTINFO,c.getString("interested_info"));
}
offferList.add(map);
// cadapter = new ClientListAdapter(this, R.layout.client_list,
// ClientDetailsCollection.getClientDetailssAsArray(), this);
}
Log.e(tag,"datas added to arraylist");
checkboxgeneration();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
HERE I NEED TO WRITE THE CODE
}
}
Advance Thanks.....
You have web request to make and display the records in dialog. Here what I suggest you.
1. Use DialogFragments.
2. Inside fragment make a listview, create custom adapter according to your design. 3. Make Web Request inside fragment. 4. For your ease you can read this Tutorial Android DialogFragment and ListView

ProgressDialog while loading data

I am encountering a problem in my Android application. I am creating a currency converter. I need to create a progressdialog that appears when you convert a value from one currency to another.
Here is part of my code:
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR") && edittextdollars.length() > 0 && edittexteuros.length()==0) {
dialog1 = ProgressDialog.show(getActivity(), "", "Calculating...");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
convertvalues("USD", "EUR");
handler.sendEmptyMessage(0);
}
catch (Exception e) {
edittexteuros.setText("Error");
}
}
});
thread.start();
}
private Handler handler = new Handler () {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
dialog1.dismiss();
break;
}
}
};
The progressdialog comes up and goes away, but nothing happens in the background. Here are a few pics of what my app looks like:
This is before the progressdialog comes.
When I press calculate:
After the progressdialog finishes:
As you can see, after the progressdialog goes away, my values don't convert.
In my code,
convertvalues("USD", "EUR");
just gets actual currency value from the internet and multiplies it with the value in my edittext. There is nothing wrong with it and it worked without the progressdialog. I have tested it many times myself.
What am I doing wrong here? I have checked Google for over a week, but I could not find a single solution. Any help regarding this problem is greatly appreciated.
Just like how you update your progressdialog in a handler, you must also update EditTexts in the handler (as it must run on the UI thread). So ideally you would return the result from convertvalues and then pass it to the handler via a message.
From what I can see, your code is fine but you aren't updating the TextView/EditText values when you dismiss the dialog. This means that although it looks like nothing is happening, it actually is - you just aren't updating to see the results.
So, assuming convertvalues() has the converted values stored somewhere, before you call dismiss() you should set your TextViews based on those values.
you can use asynctask in android
see following code may be it will help you..
private class asyncTask extends AsyncTask<Void, Void, Boolean>
{
Context context;
ProgressDialog pd;
asyncTask(Context context)
{
this.context = context;
pd = new ProgressDialog(activityContext);
}
protected void onPreExecute()
{
pd.setTitle("Loading..");
pd.setMessage("Please wait ...");
pd.setCancelable(false);
pd.show();
}
protected void onPostExecute(Boolean result)
{
if(pd.isShowing()) pd.dismiss();
}
#Override
protected Boolean doInBackground(Void... params)
{
convertvalues();
return boolean_value;
}
}
And Just Call this asynctask with
new asyncTask(Your_Context).execute();

Parse.com Android API and Android Dialog

I have placed the parse method inside onCreate method. But my problem is how to show the Android Loading... Dialog??
Parse.initialize(this, "a", "b");
ParseQuery query = new ParseQuery("Category");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> catObjects, ParseException arg1) {
Log.d("Catlength", String.valueOf(catObjects.size()));
for(int i =0; i<catObjects.size(); i++){
Log.d("lengthName"+String.valueOf(i), String.valueOf(catObjects.get(i).getInt("Id")));
Category category = new Category();
category.Name= catObjects.get(i).getString("CatName");
category.id= catObjects.get(i).getInt("Id");
categories.add(category);
}
if(categories.size()>0){
setListAdapter(new CategoryArrayAdapter(CategoryListActivity.this, R.layout.row_category, categories));
}
else{
Toast.makeText(CategoryListActivity.this, "Our servers are busy. Hit refresh..", 3000).show();
}
}
});
Everything works fine in the above code but I couldn't figure out how to show the Dialog.
I'm unable to use AsycTask also as parse sdk invokes its own thread in the background and before the findInBackground execution finishes, the doInBackground completes the Asyc thread. That's why I invoked it in the main thread.
As the result I always get no results in my ArrayList.
Can someone please enlighten me.
I was in the same situation regarding the progress dialog, tried a few tricks and finally just declared a ProgressDialog class member:
protected ProgressDialog proDialog;
then created two methods:
protected void startLoading() {
proDialog = new ProgressDialog(this);
proDialog.setMessage("loading...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setCancelable(false);
proDialog.show();
}
protected void stopLoading() {
proDialog.dismiss();
proDialog = null;
}
and called startLoading() before the background operation and stopLoading()
inside the background operation after I got the the results.
startLoading();
ParseUser.logInInBackground(userName.getText().toString(), hashedPass, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.d(Constants.TAG, "User Loged in.");
ParseManager.sCurrentUser = user;
stopLoading();
finish();
} else {
stopLoading();
invalidCreds();
}
}
});
if you want to use AsyncTask don't call findInBackground() you can use find().
you can check it out in the api https://parse.com/docs/android/api/com/parse/ParseQuery.html#find()
hope this helps.
It's easy to get the progress of both uploads and downloads using ParseFile by passing a ProgressCallback to saveInBackground and getDataInBackground. For example:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// Handle success or failure here ...
}
}, new ProgressCallback() {
public void done(Integer percentDone) {
// Update your progress spinner here. percentDone will be between 0 and 100.
}
});

Categories