Calling another activity from AsyncTask - java

I'm new to android and I have a problem with this code. I'm trying to get a JSON String and start another activity to display it as a ListView.
I'm not able to start the activity. It says that the The constructor Intent(RequestJsonString, Class) is undefined and The constructor Intent(RequestJsonString, Class) is undefined .
Here:
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
and Here:
RequestJsonString.this.startActivity(intent);
I have read many posts on this on stackoverflow and tried with activity, context and this. But still I'm not getting it right. I think I should be missing something. Any help is appreciated.
public class RequestJsonString extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
// Code HTTP Get Request and get JSONObject
return jsonObject;
}
protected void onPostExecute(JSONObject jsonObj){
try {
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
RequestJsonString.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("Json_OutPut","Done");
}
}

To start the activity from AsyncTask.
Intent intent = new Intent(YourActivityName.this,DisplayResults.class);
or you can do same like below.
Declare the context instance variable and initialize it in onCreate method.
private Context context;
public void onCreate(Bundle bundle) {
............
context = this;
........
}
Start the activity like this.
Intent intent = new Intent(context,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
startActivity(intent);

In your case you are referring to asynctask class context
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
Use a Activity Context
Intent intent = new Intent(ActivityName.this,DisplayResults.class);
Check the link to know when to use getApplicationContext() and when to use Activity Context
When to call activity context OR application context?
Edit:
Pass the Activity context to the asynctask constructor
new RequestJsonString(ActivityName.this).execute(params..);
In your asynctask constructor
Context c;
public RequestJsonString( Context context)
{
c= context;
}
Then
Intent intent = new Intent(c,DisplayResults.class);
startActivity(intent);

Related

How to pass data from a fragment class to an activity

Please, I am having problem sending an ArrayList data to Activity.
The data is an URL saved in ArrayList but after using bundle extras, I am getting null pointer exception. I also try to catch the exception but still the data i get using get extra string is null
// below is the code i used to pass the data
Bundle extras = new Bundle();
extras.putString("VidUrl",VideoLecturesUrl.get(position));
extras.putString("bookUrl",bookUrl.get(position));
extras.putString("VidTitle",titleList.get(position));
Intent intent = new Intent(getActivity(),DetailsView.class);
intent.putExtras(extras);
startActivity(intent);
// below is the receiving activity
Intent intent = getIntent();
extras =intent.getExtras();
if (extras!=null){
try {
Video_Url = extras.getString("VidUrl");
BookUrl = extras.getString("bookUrl");
Title = extras.getString("VidTitle");
Toast.makeText(this,Video_Url,Toast.LENGTH_SHORT).show();
Toast.makeText(this,BookUrl,Toast.LENGTH_SHORT).show();
Toast.makeText(this,Title,Toast.LENGTH_SHORT).show();
videotexTitle.setText(Title);
setTitle(Title);
setVideo(Video_Url.toString());
}catch (Exception e){
e.printStackTrace();
}
} else {
Toast.makeText(this, "the extrass is empty", Toast.LENGTH_SHORT).show();
}
in the fragment
public interface NoticeFragmentListener {
public void onFragmentSendArray(ArrayType yourArray);
}
NoticeFragmentListener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeFragmentListener so we can send events to the host
listener = (NoticeFragmentListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
}
}
//metod to send array
public void SendArray(ArrayType yourArray){listener.onFragmentSendArray(yourArray);}
in de activity
public class yourActivity extends AppCompatActivity implements YourFragment.NoticeFragmentListener
and recive the array
#Override
public onFragmentSendArray(ArrayType yourArray) {
}
For simplicity use the SharedPreferences for this purpose

Android App keeps on crashing upon new Intent

So I've got this error code: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
The line: Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
What I'm trying to do is to set a new activity when I receive a call. The following function is what should "switch" to that activity.
public void callMode() {
Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
startActivity(callMode);
}
And it is located inside of the MainActivity class, outside of the onCreate function.
When I try to put it inside of the onCreate function (without public void callMode() of course) it works, but that's not the goal.
I'm trying to activate this new activity from another class, which listens for calls.
public class CallReceiver extends BroadcastReceiver {
IncallActivity incallActivity = new IncallActivity();
public MainActivity mainActivity;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
mainActivity.callMode();
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
incallActivity.endCallMode();
}
}
}
So why does this error show up?
I found a way to do it.
You need to add a public static Context context to your code, and then in onCreate, do context = getBaseContext();
From there you can launch the second activity from any class you'd like.

Android - StartActivityForResult on finish() method freezes UI

I have the following situation:
Activity A starts Activity B, by using startActivityForResult
Activity B then returns an ArrayList of Strings to Activity A by using on finish().
Here is a code example of what exactly Activity B does:
ArrayList<String> urls = new ArrayList<>();
urls.add("Some string");
Intent intent = new Intent();
intent.putStringArrayListExtra(KEY, urls);
setResult(Activity.RESULT_OK, intent);
finish();
Then Activity A receive the data in onActivityResult(...)
The issue I have is that when the user taps the done button and Activity B's code example executes, Activity B freezes for about 3 seconds (when I have about 2 strings in the ArrayList). The more strings I have in the ArrayList the longer it freezes. I have more or less determined that it is finish() that causes the UI thread to freeze.
Is there a way to call finish() without freezing Activity B? If not, why is this happening?
EDIT:
Here is the full example:
/**
* Background task
*/
private class gatherUrlsTask extends AsyncTask<ArrayList<PictureEntry>, Integer, Intent> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
bt_done.setVisibility(View.GONE);
fab_add_picture.setVisibility(View.GONE);
}
#SafeVarargs
#Override
protected final Intent doInBackground(ArrayList<PictureEntry>... params) {
ArrayList<String> imagePaths = new ArrayList<>();
for (PictureEntry pictureEntry : params[0]) {
if (pictureEntry.isSelected()) {
imagePaths.add(pictureEntry.getPath());
}
}
if (imagePaths.size() == 0) {
Toast.makeText(getApplicationContext(), R.string.please_select_atleast_one_image, Toast.LENGTH_LONG).show();
return null;
} else {
Intent intent = new Intent();
intent.putStringArrayListExtra(SELECTED_IMAGES_KEY, imagePaths);
return intent;
}
}
#Override
protected void onPostExecute(Intent intent) {
setResult(Activity.RESULT_OK, intent);
finish();
}
}
However I can remove everything from the AsyncTask since it did not have any effect on performance.
i don't know what is cause of that, but for prevent ui getting freezed, use asyncTask and then in the onPostExcecute call finish()

Can't run new activity from onPostExecute

I'm having trouble starting my mainActivity after I have gotten a response from a httpUrlConnection.
Here is my onPostExecute method
protected void onPostExecute(String[] result) {
serv.httphelper.handleResults(result);
}
In the method handleResult() im handling the response code. If the response code is 200 i want to run a new method inside my loginActivity class
public void handleResults(String[] result) {
status = result[0].toString();
instructions = result[1].toString();
jsonString = result[2];
Log.d("DEBUG", status);
if (status.equals("200")) {
serv.loginActivity.proceed();
} else if (status.equals("400")) {
serv.loginActivity.loginError();
} else if (status.equals("401")) {
serv.loginActivity.loginError();
}
}
When i try to start a new activity from the proceed() method i get a nullpointerexception
public void proceed(){
startActivity(new Intent (LoginActivity.this, MainActivity.class));
Log.d("TEST", "Proceed success");
}
My service class for anyone wondering:
public class Service {
public static HttpHelper httphelper = new HttpHelper();
public static HttpConnect conn = new HttpConnect();
public static LoginActivity loginActivity = new LoginActivity();
}
And here is my logCat:
Thanks in advance!
Your problem is when you start the activity at the line:
startActivity(new Intent (LoginActivity.this, MainActivity.class));
Well, you creates an intent that tries to get to LoginActivity.this which probably does not exists!
Instead of this, you have to give an instance of a real activity that is currently running.
A solution that I can suggest you is to pass to proceed() the instance of the currently running activity and put it instead of LoginActivity.this.
In case you don't have a current activity, try to put your application's context instead and add it a flag of a new task.

How to open browser in android app?

i'm doing a project where i have to call a browser via my android app, but when i call it, the app stops.
the code can be found here: https://github.com/coppetti/android-pulsometer
but for fast view, i have a "Pulsometro" class where
public void onPreviewFrame(byte[] data, Camera cam) {
...
Browser browser = new Browser();
browser.callBrowser(beats);
return;
...
}
and a Browser class where:
public class Browser extends Activity{
public void callBrowser(int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return;
}
}
There's a way to call a browser and my app doesn't breaks?
Try this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onOpenWebBrowser(View v)
{
Intent webPageIntent = new Intent(Intent.ACTION_VIEW);
webPageIntent.setData(Uri.parse("https://www.google.co.in/"));
try {
startActivity(webPageIntent);
} catch (ActivityNotFoundException ex) {
}
}
Do not just randomly choose superclasses. Do not just create some subclass of Activity and expect it to work.
Move your callBrowser() method into some real Activity implementation, and get rid of Browser entirely.
Or, remove the superclass from Browser, have callBrowser() take a Context as a parameter, and call startActivity() on that Context.
Try this class. Call the callBrowser method and give it and Activity for the context parameter.
public class Browser{
public void callBrowser(Context context, int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}

Categories

Resources