Using StartActivity i reached SecondActivity from FirstActivity..Now i want to access object declared in the previous activity.
Is there any obvious mechanisms that i am missing.I cant use Parceable on the object(DropboxAPI) i want to pass since i do not have its source(i can't make it parceable).
Can i pass FirstActivity.this since i can make it Parceable using an intent?or like
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("MyClass",FirstActivity.this);
startActivity (intent);
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import android.app.Application;
import android.hardware.Camera.Parameters;
import android.os.Parcel;
import android.os.Parcelable;
public class temp extends Application {
DropboxAPI<AndroidAuthSession> mApi;
public void onCreate() {
super.onCreate();
}
temp(DropboxAPI<AndroidAuthSession> Api)
{
mApi=Api;
}
public DropboxAPI<AndroidAuthSession> getName() {
return mApi;
}
public void setName(DropboxAPI<AndroidAuthSession> dropboxclient) {
this.mApi = dropboxclient;
}
}
Code in first class:
t = (temp)getApplication();
t.setName(mApi);
//basket.putParcelable("key", MCActivity.this);
Intent intent=new Intent(MCActivity.this,DownActivity.class);
//intent.putExtra("MyClass",t);
startActivity (intent);
Code in Second class:
public void onCreate(Bundle bun) {
// TODO Auto-generated method stub
super.onCreate(bun);
setContentView(R.layout.download);
mImage = (ImageView)findViewById(R.id.image_view);
//Bundle gotit=getIntent().getExtras();
t = (temp)getApplication();
int i=2;
i=5;
dApi=t.getName();
}
Logcat:
06-28 02:24:31.979: I/System.out(729): debugger has settled (1308)
06-28 02:25:08.387: D/AndroidRuntime(729): Shutting down VM
06-28 02:25:08.387: W/dalvikvm(729): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-28 02:25:08.705: E/AndroidRuntime(729): FATAL EXCEPTION: main
06-28 02:25:08.705: E/AndroidRuntime(729): java.lang.ClassCastException: android.app.Application
06-28 02:25:08.705: E/AndroidRuntime(729): at cloud.mobile.MCActivity$3.onClick(MCActivity.java:164)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.view.View.performClick(View.java:2408)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.view.View$PerformClick.run(View.java:8816)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Handler.handleCallback(Handler.java:587)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Handler.dispatchMessage(Handler.java:92)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Looper.loop(Looper.java:123)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-28 02:25:08.705: E/AndroidRuntime(729): at java.lang.reflect.Method.invokeNative(Native Method)
06-28 02:25:08.705: E/AndroidRuntime(729): at java.lang.reflect.Method.invoke(Method.java:521)
06-28 02:25:08.705: E/AndroidRuntime(729): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-28 02:25:08.705: E/AndroidRuntime(729): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-28 02:25:08.705: E/AndroidRuntime(729): at dalvik.system.NativeStart.main(Native Method)
try using Application class:
public class MyApplication extends Application {
//Variable we want to share to All Activities in Application
private DropboxClient dropboxclient;
#Override
public void onCreate() {
super.onCreate();
}
//Getter Method
public DropboxClient getName() {
return dropboxclient;
}
//Setter Method
public void setName(DropboxClient dropboxclient) {
this.dropboxclient = dropboxclient;
}
}
In MyFirstActivity Activity:
private MyApplication app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app = (MyApplication)getApplication(); //Get Application
app.setName(dropboxclient);
Intent intent = new Intent();
intent.setClass(this, MySecondActivity.class);
startActivity(intent);
In MySecondActivity Activity:
private MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MyApplication)getApplication(); //Get Application
DropboxClient dropboxclient=app.getName();//Access global value
do the following,
start the activity with startActivityForResult()
startActivityForResult(0, MyActivity.class);
before your started activity finished, in the started activity, create an intent, and put whatever data you want to pass back as extras in the intent. now call setResult(..., intent);
Intent resultIntent = new Intent();
resultIntent.putExtra("myKey", myVal);
setResult(0, resultIntent);
in your starting activity, implement onActivityResult(), and handle the result of the started activity. you will be passed an Intent, which is the intent where you added extras in the started activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//TODO handle here.
}
Extend Application class and declare and initialize your cross activity objects in that class and write getters for those objects.
now using following code in an activty, you can access those Objects.
getApplication().getMyObject().doSomeAction();
remember, you will have to modifiy your androidManifest.xml to tell android about your extended application class.
Solution:
Using StartActivityforResult there data moveback to Second Activity to First Activity
One Example there data move to second Activity to first Activity-
http://micropilot.tistory.com/1577
Related
I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.
I believe it is the way I am instantiating it but this is what I have:
// This onClick is in my adapter class - which is a separate Java File and class
#Override
public void onClick(View v) {
UploadRes uploadRes = new UploadRes();
UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
uploadResConfirm.execute(fileName, filePath);
}
public class UploadResConfirm extends AsyncTask<String, String, String> {
Dialog dialog;
Context context;
public UploadResConfirm(Context context){
this.context = context;
}
#Override
protected void onPreExecute(){
dialog = new Dialog(UploadRes.this);
dialog.setTitle("Currently uploading");
dialog.show();
}
I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.
The error stack trace on Logcat - its the Dialog, I think its in the wrong place...
java.lang.NullPointerException
at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Some help if any would be much obliged.
Instead of dialog = new Dialog(UploadRes.this);
Try
dialog = new Dialog(context);
your are passing a wrong context to create dialog.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtUserName = (EditText)findViewById(R.id.editText1);
final EditText txtPassword = (EditText)findViewById(R.id.editText2);
Button btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
String foo = new String("131031001");
String foo2 = new String("131031002");
String foo3 = new String("131031003");
String foo4 = new String("131031004");
String foo5 = new String("131031005");
try{
if(username.length() > 0 && password.length() >0) {
DBUserAdapter dbUser = new DBUserAdapter(MainActivity.this);
dbUser.open();
dbUser.AddUser();
if(dbUser.Login(username, password))
{
Toast.makeText(MainActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
if(username.equals(foo))
{
Intent nextActivity2 = new Intent(getApplicationContext(),SecondActivity.class);
nextActivity2.putExtra("Second",username);
startActivity(nextActivity2);
}
else if(username.equals(foo2)) {
Intent nextActivity3 = new Intent(getBaseContext(),ThirdActivity.class);
nextActivity3.putExtra("Third",username);
startActivity(nextActivity3);
}
else if(username.equals(foo3))
{
Intent nextActivity4 = new Intent(getBaseContext(),FourthActivity.class);
nextActivity4.putExtra("Fourth",username);
startActivity(nextActivity4);
}
else if(username.equals(foo4)) {
Intent nextActivity5 = new Intent(getBaseContext(),FifthActivity.class);
nextActivity5.putExtra("Fifth",username);
startActivity(nextActivity5);
}
else if(username.equals(foo5)) {
Intent nextActivity6 = new Intent(getBaseContext(),SixthActivity.class);
nextActivity6.putExtra("Sixth",username);
startActivity(nextActivity6);
}
else {
Toast.makeText(MainActivity.this,"Result does not exist! Try later!!", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Button btreg = (Button)findViewById(R.id.button2);
btreg.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent nextActivity = new Intent(getApplicationContext(),Register.class);
startActivity(nextActivity);
}
});
}
}
SecondActivity.java
public class SecondActivity extends Activity {
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
}
All other activities are coded similar to the above.
Here is my logcat.
10-28 14:53:10.688: E/AndroidRuntime(1196): Process: com.skcetresults, PID: 1196
10-28 14:53:10.688: E/AndroidRuntime(1196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skcetresults/com.skcetresults.SecondActivity}: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.access$700(ActivityThread.java:135)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Looper.loop(Looper.java:137)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.main(ActivityThread.java:4998)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
10-28 14:53:10.688: E/AndroidRuntime(1196): at dalvik.system.NativeStart.main(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): Caused by: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.skcetresults.SecondActivity.onCreate(SecondActivity.java:15)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Activity.performCreate(Activity.java:5243)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
10-28 14:53:10.688: E/AndroidRuntime(1196): ... 11 more
With just two intents the code worked fine, but when I'm comparing the value with strings, the app crashes, I don't know where the bug is.
Instead of getBaseContext() and getApplicationContext(), use MainActivity.this as context, will work everywhere.
You should put it like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Intent i = getIntent();
}
}
If the extra data are strings you can get it like this:
String nameString = i.getStringExtra("nameExtra");
You can't use getIntent() before onCreate(), there's simply no Intent available at that point.
In your code, I suspect that you are trying to get StringExtras from Intent, But as intent is null, it is throwing NullPointerException.
In your Second Activity you can use getIntent() in onCreate() method.
public class SecondActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
intent = getIntent();
String userName = intent.getStringExtra("Second");
...
}
}
Use little pieces of code checking, to ensure your intent behaves properly. For example, you could surround your getIntent code with an if statement. For which proper method to call, you have to wander around a bit, as this depends on what you want your app to do. Fortunately, Eclipse delivers you all the related documentation, when you write down some piece of Android resources, e.g. Intent.
I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
First of all, sorry for my bad English !
I have an Activity ( say MainActivity.java ) and a class ( say AsynkTaskClass.java ).
AsynkTaskClass.java contains an AsynkTask. I am calling this AsynkTask from MainActivity.java.
Before calling this AsynkTask, I am saving some data using SharedPreferences.
From the onPostExecute function of AsynkTask, I am calling a normal function ( say displaySharedData() )which defined in MainActivity.java. There I am trying to retrieve the data I stored using SharedPreferences. Then It shows a NullPointerException. But I can access the Shared data from anywhere other than this displaySharedData() function.
This is the Log Output:
W/dalvikvm(3896): threadid=1: thread exiting with uncaught exception
E/AndroidRuntime(3896): FATAL EXCEPTION: main
E/AndroidRuntime(3896): java.lang.NullPointerExceptionE/AndroidRuntime(3896): at com.samApp.project.samApp.ui.MainActivity.displaySharedData(MainActivity.java:52)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:264)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:1)
E/AndroidRuntime(3896): at android.os.AsyncTask.finish(AsyncTask.java:417)
E/AndroidRuntime(3896): at android.os.AsyncTask.access$300(AsyncTask.java:127)
E/AndroidRuntime(3896): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
E/AndroidRuntime(3896): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(3896): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(3896): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(3896): at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity implements TextView.OnEditorActionListener {
public SharedPreferences myData;
public String mySharedData="com.samApp.project.samApp.ui";
public SharedPreferences.Editor editor;
protected void onCreate(Bundle savedBundle) {
super.onCreate(savedBundle);
myData = PreferenceManager.getDefaultSharedPreferences(this);
editor = myData.edit();
editor.commit();
attachfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PHOTO_SELECTED);
}
});
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case PHOTO_SELECTED:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Log.d("URIsssss", String.valueOf(selectedImage));
AsynkTaskClass obj = new AsynkTaskClass ();
AsynkTaskClass.s3context=this;
obj.new UploadImage().execute(selectedImage);
}
}
}
}
protected void onResume() {
super.onResume();
editor.putString("name", "MeSSi");
editor.commit();
}
public void displaySharedData()
{
Log.d("SharedData",myData.getString("name","")); // line No : 52
}
}
AsynkTaskClass.java
public class AsynkTaskClass {
MainActivity mainActvtyObj = new MainActivity();
public static Context s3context;
protected void onPostExecute(S3TaskResult result) {
if(dialog != null)
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
AsynkTaskClass.s3context.getString(R.string.upload_failure_title),
result.getErrorMessage());
}
mainActvtyObj.displaySharedData();
}
}
So, Any Help ??
MainActivity mainActvtyObj = new MainActivity();
Never instantiate activity classes with new.
For example, their lifecycle callbacks such as onCreate() are not run. You init your myData in onCreate() and it remains null in this activity instance.
Instead, pass a reference to your activity object to the async task as a parameter.
Finally I got a working solution.
I don't know whether It is perfect! But it works well..
I replaced the displaySharedData() calling statement i.e. mainActvtyObj.displaySharedData(); to the following :
((MainActivity) s3context).displaySharedData();
Now It Works Great !!
I am new Android coder and I'm fighting with function startActivityForResult. When I click Button that starts this method I can't go inside another activity because it crashes:
So there is MainActivity.java class. Here in public void setRegisterOnClick(View v) I want to use startActivityForResult twice, sending other intents to the same activity. Intents contain int number which is delivered to Users.class and used to declare giveResponse. But each time I click button launching startActivityForResult my app crashes.
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int USERS_REQUEST_CODE=1;
private static String sActualLogin = "admin";
private static String sActualPassword = "qwerty";
private static String sContainer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setLoginOnClick(View v)
{
EditText etLogin = (EditText) findViewById(R.id.tfLogin);
EditText etPassword = (EditText) findViewById(R.id.tfPassword);
String sLogin = etLogin.getText().toString();
String sPassword = etPassword.getText().toString();
if (sLogin.equals(sActualLogin) && sPassword.equals(sActualPassword))
{
Intent intent = new Intent (this, Inside.class);
startActivity(intent);
}
else
{
Toast.makeText(this, "Invalid username or password.", Toast.LENGTH_LONG).show();
}
}
public void setRegisterOnClick(View v)
{
Intent intentLOGIN = new Intent(this, Users.class);
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, USERS_REQUEST_CODE);
sActualLogin=sContainer;
Intent intentPASSWORD= new Intent(this, Users.class);
intentPASSWORD.putExtra("Type",2);
startActivityForResult(intentPASSWORD, USERS_REQUEST_CODE);
sActualPassword=sContainer;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
sContainer = data.getStringExtra(Users.RESPONSE);
}
}
Users.class
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Users extends Activity {
public static final String RESPONSE = "Response";
EditText etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
EditText etNewPassword = (EditText) findViewById(R.id.etChangePassword);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
}
public void giveResponse(View v)
{
Intent intent = getIntent();
int iOperation = intent.getIntExtra("Type", 0);
if (iOperation == 1){
String sNewLogin = etNewLogin.getText().toString();
Intent resultIntent1 = new Intent();
resultIntent1.putExtra(RESPONSE, sNewLogin);
setResult(RESULT_OK, resultIntent1);
finish();
}
if (iOperation == 2){
String sNewPassword = etNewPassword.getText().toString();
Intent resultIntent2 = new Intent();
resultIntent2.putExtra(RESPONSE, sNewPassword);
setResult(RESULT_OK, resultIntent2);
finish();
}
}
}
Fragment of manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.login.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.login.Users"></activity>
<activity android:name="com.example.login.Inside"></activity>
</application>
Errors:
05-12 20:22:10.350: W/dalvikvm(6349): threadid=1: thread exiting with uncaught exception (group=0x40a191f8)
05-12 20:22:10.360: E/AndroidRuntime(6349): FATAL EXCEPTION: main
05-12 20:22:10.360: E/AndroidRuntime(6349): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.login/com.example.login.Users}: java.lang.NullPointerException
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.os.Looper.loop(Looper.java:137)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.main(ActivityThread.java:4429)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.reflect.Method.invokeNative(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.reflect.Method.invoke(Method.java:511)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
05-12 20:22:10.360: E/AndroidRuntime(6349): at dalvik.system.NativeStart.main(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): Caused by: java.lang.NullPointerException
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.Activity.findViewById(Activity.java:1794)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.example.login.Users.<init>(Users.java:13)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.Class.newInstanceImpl(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.Class.newInstance(Class.java:1319)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
05-12 20:22:10.360: E/AndroidRuntime(6349): ... 11 more
Well I wrote a lot for such trivial problem (I guess :P) but as I am unexperienced it takes hours to fights with it and I stil don't get it. Please guide/help me.
you must set the layout using setContentView before accessing the child widget using findViewByID
for example
private EditText etNewLogin;
private EditText etNewPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
tNewLogin = (EditText) findViewById(R.id.etChangeLogin);
tNewPassword = (EditText) findViewById(R.id.etChangePassword);
}
Also make sure that you are accesing the view using correct id
EditText etNewLogin;
EditText etNewPassword;;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
etNewPassword = (EditText) findViewById(R.id.etChangePassword);
}
You need to find the id after setting the content to the activity.
Also in setLoginOnClick of MainActivity
Intent intent = new Intent (MainActivity.this, Inside.class);// use activity context
startActivity(intent);
Same for
Toast.makeText(MainActivit.this, "Invalid username or password.", Toast.LENGTH_LONG).show();
Intent intentLOGIN = new Intent(MainActivity.this, Users.class);// use activity context
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, USERS_REQUEST_CODE);
sActualLogin=sContainer;
Intent intentPASSWORD= new Intent(MainActivity.this, Users.class);// use activity context
intentPASSWORD.putExtra("Type",2);
startActivityForResult(intentPASSWORD, USERS_REQUEST_CODE);
sActualPassword=sContainer;
Often this happens when you haven't declared an activity correctly in your AndroidManifest file, make sure the directory info is correct so your app can find the activity you are trying to get to!