I am new to android development.
I want to perform some db operations and then, want to start a new activity. I have written AsyncTask code below.
I am getting error on startActivity call. Please help me out.
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
Context mainContext;
public AsyncTaskRunner(Context mainContext){
this.mainContext=mainContext;
}
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
sql.updateRelations();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
InitActivity.progress.dismiss();
Intent intent = new Intent(mainContext, MainActivity.class);
if(mainContext!=null){
mainContext.startActivity(intent);
((Activity)mainContext).finish();
}
}
#Override
protected void onPreExecute() {
InitActivity.progress.show();
}
#Override
protected void onProgressUpdate(String... text) {
}
}
If your async task is an inner class of your activity then do the below
Intent intent = new Intent(YourActivityName.this, MainActivity.class);
if(mainContext!=null){
mainContext.startActivity(intent);
((Activity)mainContext).finish();
}
Else if your async task is a separate class then try the below
Intent intent = new Intent((YourActivityName)mainContext, MainActivity.class);
if(mainContext!=null){
mainContext.startActivity(intent);
((Activity)mainContext).finish();
}
If it doesn't work please post your logs so i can be of better help.
Related
I tried to put finish() method to stop back stack.but it gave syntax error to me.how can I stop back stack.Thanks in advance.
private class getNewMessages extends AsyncTask<ApiConnector, Long, JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
try {
JSONArray array = params[0].getMessage(name, password);
// String [] array=new String[10];
if (array.length() > 0) {
Intent nextScreen = new Intent(getApplicationContext(), bussiness.class);
nextScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(nextScreen);
}
}catch (Exception e)
{
Toast.makeText(getApplicationContext(),"Wrong Credintials", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(JSONArray result) {
}
}
Shift your code to your onPostExecute callback
#Override
protected void onPostExecute(JSONArray result) {
if (result.length() > 0) {
Intent nextScreen = new Intent(getApplicationContext(), bussiness.class);
nextScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(nextScreen);
}
}
Try using (Activity)mContext).finish(); or finish();
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();
I'm write a music application online.But i'm meet a problem... A new activity starts slowly when I select an item in listview...
I don't know resolve, please help me ! :(
Sorry. I'm speak English very bad :(
This is my code:
public class startNewActivity extends AsyncTask<String, Void, String> {
private Activity activity;
private String selectDoc = "div.gen img";
private String attr = "title";
private String result;
public String Quality;
public startNewActivity(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... arg0) {
nameSong = (String) lvSong.getItemAtPosition(positionId);
link = linkSong.get(Integer.valueOf(obj.toString()));
Quality = Utils.getQuality(link, selectDoc, attr, result);
Log.i("Quality", Quality);
changeLink = link.replace(".html", "_download.html").substring(15)
.replaceFirst("", "http://download")
.replace("nhac-hot", "mp3".concat("/vietnam/v-pop"));
Log.i("Change link", changeLink);
try {
//Connect internet
linkIntent = Utils.getLinkPlay(selectLinkPlay, changeLink,
afterChangeLink);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Server has problem... Please while for minutes",
Toast.LENGTH_SHORT).show();
}
return linkIntent;
}
#Override
protected void onPostExecute(String result) {
//i'm want help here
Intent i = new Intent(SongActivity.this, PlayMusicActivity.class);
i.putExtra("song", linkIntent);
i.putExtra("namesong", nameSong);
i.putExtra("Quality", Quality);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
pDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(SongActivity.this, "",
"Please wait...");
}
}
You're starting the new activity inside onPostExecute() which executes only after you've completed doInBackground(). Hence, the time delay.
Ideally, you should start the activity just after you execute your AsyncTask. The AsyncTask will continue in the background while your activity changes.
The problem has been solved, thank you for the help.
Essentially, I have my onCreate() class that sets an OnClick listener on a button. Once I click it, an async task is created and executed.
This async task gets a response from a server and then sends the info to onPostExecute().
From here, if the info is valid or not, I want to toast the result and switch activities accordingly.
As of now, I have tried to do it from the onPostExecute() and it does not work. Somehow, I must get back to my main thread and do it there. How do I do this?
Here is the code:
public class Class1 extends Activity {
JSONObject jObj = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
Button submit = (Button) findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
(new CallAPI(restfulCall)).execute();
}
});
}
public class CallAPI extends AsyncTask<Void,Void,String>
{
private String restfulCall = "";
public CallAPI(String command)
{
restfulCall = command;
}
protected String doInBackground(Void... urls)
{
return API.getData(restfulCall);
}
protected void onPostExecute(String result) {
try {
jObj = new JSONObject(result);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
if(jObj.get("status").toString().equals("success"))
{
Toast.makeText(getBaseContext(),"Registration Succesful",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Class1.this,Success.class);
Class1.this.startActivity(intent);
}
else
{
Toast.makeText(getBaseContext(),jObj.get("error").toString(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(Class1.this,Error.class);
Class1.this.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
use equals for comparing Strings intead of == as :
if(jObj.get("status").toString().equals("success")
instead of
if(jObj.get("status").toString() == "success")
I'm creating a login form. When the user logs in, it will lead to the home page.
I create an activity that has an AsyncTask. Here's the relevant part of my code:
public class iniTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(GPSTracerActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Connect to server...");
Dialog.show();
}
protected String doInBackground(String... url_req) {
String url = url_req[0];
try {
Log.v("doing background", executeHttpGet(url));
return executeHttpGet(url);
} catch(Exception e) {
Log.v("Exception doing background","Exception:"+e.getMessage());
return "";
}
}
protected void onPostExecute(String result) {
try {
Dialog.dismiss();
// here when thing go wrong
startNewAction(result);
} catch(Exception e) {
Log.v("Exception process response","Exception:"+e.getMessage());
}
}
}
Here's startNewAction(result):
public void startNewAction(String result){
if (result.substring(0, 6) == "300 OK"){
Intent i = new Intent(GPSTracerActivity.this, Home.class);
startActivity(i);
}
}
The task starts correctly, but when I call startNewAction(result),
it does not call a new activity. Why?
NOTE : when i enable if structure to test string == 300 OK it is not work ! why
I see this in logcat:
07-16 14:57:23.345: WARN/InputManagerService(37): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#40777ee0
In your onPostExecute dismiss the dialog first.
Dialog.dismiss();
I just found the solution,there is an error because of the way i compare the string,
It should be,
if (result.substring(0, 6).equals("300 OK") ){
Intent i = new Intent(GPSTracerActivity.this, Home.class);
startActivity(i);
}
Anyway, Thanks for ideas !!!