Get all JSON response and then start another activity - android

I am doing socket programming and getting JSON response. Everything is working perfectly but the only thing that is getting me in trouble is that I start another activity before getting response but I want to get all response and after that start another activity.
Here is my code.
jsonobject1.put("username", edt.getText().toString());
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4");
try {
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
In my above code I am sending JSON data to server and getting JSON object in response. But before getting the response I am being sent to another activity. So I first want response and then start activity. Help me with some pseudo code.
Thanks

Create an AsyncTask class
public class GetJSONResult extends AsyncTask<String, Void, Void>
{
ProgressDialog pd ;
private Context _context;
public GetJSONResult(Context c)
{
_context = c;
}
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(_context);
pd.setTitle("Getting JSON details");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
jsonobject1.put("username", params[0]); // params[0] is the value passed i.e edittext value
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4")
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
}
catch (Exception e)
{
if (pd.isShowing())
pd.dismiss();
}
return null;
}
protected void onPostExecute(Void v)
{
super.onPostExecute(v);
try
{
if (pd.isShowing())
pd.dismiss();
}
catch(Exception e)
{
}
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
}
}
Form your MainActivity call the AsyncTask like this
public MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// First get the reference to EditText using findViewById, then
String s = edt.getText().toString();
// Call the AsyncTask
new GetJSONResult(MainActivity.this).execute(s); // pass the edittext value to doInBackGround method.
}
}

private class getResponse extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonobject1.put("username", edt.getText().toString());
jsonobject1.put("udid",
"A892E0AB-6732-4F42-BEFA-3157315E9EE4");
try {
socket.emit("setPseudo", jsonobject1);
socket.emit("findAllUsers", jsonobject1);
Log.e("TAG",""+ socket.getId());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
intent.putExtra("onlineuser", onlineuser);
intent.putExtra("finduser", finduserjson);
startActivity(intent);
}
#Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
and for executing new getResponse().execute();

Related

ProgressDialog is showing after doInBackground() finished in android

I want to show the progressdialog when the webservice is called and stop the dialog on request is finished.
I did the following way but the dialog showing after the web service request is finished.
public class NetWorkRunTask extends AsyncTask<String, Void, String> {
Context ctx;
public NetWorkRunTask(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(ctx);
}
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog.setMessage("Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//contactService.getAssetsAtFirstRun();
// mProgressDialog.show();
return ServerConnection.getXmlRespFromUrl(params[0]); //this will include HttpPost
//return null;
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
}
and in onClickListener
String xml=null;
try {
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null).get();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
what's going wrong here.....
just do this in your asynk task
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
}
Remove the get() method, while calling your async task
change
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null).get();
to
xml =new NetWorkRunTask().execute(finalURL,null,null);
and
public class NetWorkRunTask extends AsyncTask {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//contactService.getAssetsAtFirstRun();
return ServerConnection.getXmlRespFromUrl(params[0]); //this will include HttpPost
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
In your code you are calling 'get()' method. [get() -waits if necessary for the computation to complete"].
Replace your Asynch task calling line with the below code and try
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null);
You can define an interface in your Async task
public interface OnProcessCompleteListener{
public void onSuccess(String result);
public void onFailure();
}
and in your activity class you can implement the call back methods and can return results to the class.
OnProcessCompleteListener listener = listener = new OnProcessCompleteListener() {
#Override
public void onSuccess(String result) {
// do what u want
}
#Override
public void onFailure() {
}
};
Pass the 'listener' to the AsyncTask and call the onSuccess(String result), onFailure() methods where u want.
#Override
protected void onPostExecute(String result) {
if(result != null) {
listner.onSuccess(result);
}else{
listner.onFailure();
}
if(mProgressDialog != null){
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}

how to Show loading box while sending data?

Hi everyone i am facing problem in showing loading box on pressing send button using send_Schedule() function. I have the following code.
#Override
public void onClick(View arg0) {
pdialog.setCancelable(true);
pdialog.setMessage("Loading ....");
pdialog.show();
send_Schedule();
}
In send_Schedule() function i am putting delay of 3 secs like this in the following code. but dialog box always shows up after completion of loop.
send_Schedule(){
for(int i=0;i<100;i++){
Log.d("TAG",""+i)
try {
Thread.sleep(3000);
Log.e("----------------", "-----------------");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pdialog.dismiss();
}
I want to show dialog box while sending data...
Try this..
private class YourTaskLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(YourActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Importing Messages...!");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Write you back ground logic here
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
Invoke like in your Activity
new YourTaskLoader().execute();
Check this more info AsyncTask

tabhost groupactivity not working(deprecated)

public class Feedback extends ActivityGroup {
protected static LocalActivityManager mLocalActivityManager;
private EditText fd=null;
private Button send=null;
public int res_flag=0;
public String result="";
public String url="";
private RelativeLayout newaccount;
private TextView needhelp=null;
private String currentDateandTime="";
private boolean isonline;
protected String fd_text="";
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); this.setContentView(view);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
initialization();
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
currentDateandTime = sdf.format(new Date());
}catch (Exception e) {
System.out.println(e);
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Feedback.Retrieve().execute();
}
});
}
private void initialization()
{
fd=(EditText)findViewById(R.id.fd);
send=(Button)findViewById(R.id.send);
}
class Retrieve extends AsyncTask<Void, Integer, Integer> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(Feedback.this);
pd.setMessage("Please wait while sending feedback..");
pd.setCancelable(false);
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
try{
System.out.println("IN BKGRND");
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
url="url"+fd_text.toString().trim()+"&datetime="+currentDateandTime;
url=url.replace(" ","%20");
url=url.replace("+","%2B");
System.out.println(url);
JSONObject json = JSONfunctions.getJSONfromURL(url);
JSONObject response1=json.getJSONObject("response");
result=response1.getString("Success").toString().trim();
System.out.println(result);
if(result.equalsIgnoreCase("1"))
{
System.out.println("Logged In");
res_flag=1;
}
else
{
System.out.println("failed");
res_flag=5;
}
}
catch (JSONException e) {
System.out.println(e);
}catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
}
Error is:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#40e16110 is not valid; is your activity running?
PROBLEM
I calling activity through another tabhost.,It loading only the view .The webservice and button are not working ., When i click the buttons it shows above error.Help me to proceed guys..
Reference:
http://www.gamma-point.com/content/android-how-have-multiple-activities-under-single-tab-tabactivity
NOw the ActivityGroup is deprecated.., What should i use now..
For what you have posted, it doesn't seem like you need to use ActivityGroup at all. Simply extend your Feedback from Activity class. For example:
public class Feedback extends Activity

AsyncTask HttpParams

Could anyone help me on following questions.
1) onPostExecute - Toast.make while in background i am sending HttpRequest.
0nCraeteBunle - execute() ; startNewActivity
showing error. AsycTask# Runtime Exception .
While commenting Http request in background, no error is showed.
here, how can i know that http Request and reply finished , so that i can start my new Activity.
2) how to get HttpParams. Sending from TIBCO BE (As event with properties)
3) What if i am recieving JSONObject, JAVAObject, Integer other than String in onPostExecute. unable to override .
Try this,
protected class GetTask extends AsyncTask<Void, Void, Integer> {
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"Loading", "Please wait");
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
//call ur HttpRequest
httpRequest();
return 0;
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mHandler.sendEmptyMessage(0);
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message Msg) {
if (Flag) {
//Add ur stuff
}else{
}
And then in ur method set Flag value
public void httpRequest() {
// TODO Auto-generated method stub
String URL ="ADD UR URL";
try {
JSONObject ResponseObject = mAPIService.CallAPI(
YourActivity.this, URL);
String status = ResponseObject.getString("status");
Flag = true;
} catch (Exception err) {
Flag = false;
}
}

Progress Dialog only shows up when the job is already done

I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});

Categories

Resources