Android - Starting activity, can't reach OnCreate with extra - android

I'm trying to pass a serialized array of objects from one activity to another. However, I'm unable to reach OnCreate in the second activity if I attach the extra to the intent. Can anyone see what I'm doing wrong?
From the first activity:
public void onDisplayImages(View view){
Intent intent = new Intent(MainActivity.this, ImagesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(IMAGE_LIST,mImagesList);
intent.putExtras(bundle);
MainActivity.this.startActivity(intent);
}
This way doesn't work either:
public void onDisplayImages(View view){
Intent intent = new Intent(MainActivity.this, ImagesActivity.class);
intent.putExtra(IMAGE_LIST,mImagesList);
MainActivity.this.startActivity(intent);
}
mImageList is an ArrayList of ImageData objects where ImageData extends Serializable. When I don't attempt to attach the extra, I make it to the second activity.
ImageData:
public class ImageData implements Serializable {
public Bitmap mImage;
public String mName;
public ImageData(String fileName, Context context){
mName = fileName;
File filePath = context.getFileStreamPath(fileName);
try {
FileInputStream fi = new FileInputStream(filePath);
mImage = BitmapFactory.decodeStream(fi);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I am getting this error
Error:
05-28 16:50:40.540 2731-2731/[myPackageName]/AndroidRuntime﹕ FATAL EXCEPTION: main Process: [myPackageName], PID: 2731 java.lang.IllegalStateException: Could not execute method of the activity –

Related

update the UI of fragment from onPostExecute called from onActivityResult

In my application I launch an intent with ACTION_OPEN_DOCUMENT on a button click to pick a document.
private static final int READ_REQUEST_CODE = 42;
public void performFileSearch() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
// browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimeTypes = {
"image/*",
"text/plain",
"application/pdf"
};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
startActivityForResult(intent, READ_REQUEST_CODE);
}
After that, I fetch the Uri of the document selected by the user in onActivityResult and pass it on to an AsyncTask where the selected document is zipped.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
dialog = new ProgressDialog(getActivity());
dialog.setMessage(getString(R.string.upload_dialog));
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
new ZipFile().execute(data.getData());
}
}
}
Below is my AsyncTask class:
private class ZipFile extends AsyncTask<Uri, Void, String> {
#Override
protected String doInBackground(Uri... uris) {
Uri uri = uris[0];
String fileName = null;
try {
fileName = zm.createPath("user");
zm.zipFromUri(uri, fileName, commonMethods.getFileName(uri));
} catch (NullPointerException | IOException e) {
e.printStackTrace();
}
return fileName;
}
#Override
protected void onPostExecute(String fileName) {
dialog.dismiss();
if (fileName != null) {
renderView(view);
}
}
}
In the renderView function, I display a snackbar and update the UI of my fragment.
private void renderView(View view) {
CoordinatorLayout fileSnackbarView = view.findViewById(R.id.filesCoordinatorLayout);
//Exception at this line
fileSnackbar = Snackbar.make(fileSnackbarView, String.format(getResources().getString(R.string.snackbarMessage), FILE_COUNT), Snackbar.LENGTH_INDEFINITE)
.setAction(getResources().getString(R.string.snackbarAction), new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ViewSelectedFilesActivity.class);
Bundle bundle = new Bundle();
ArrayList<String> selectedFileName = new ArrayList<>();
selectedFileName.add(commonMethods.getFromPreferences(Constants.originalFileNameKey, "string"));
bundle.putStringArrayList("fileList", selectedFileName);
intent.putExtras(bundle);
startActivity(intent);
}
});
... code
}
However, my application crashes with the exception Fragment not attached to a context. Below is the complete stack trace:
03-08 12:09:20.647 11490-11490/com.zeetim.zeeprintmobile.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zeetim.zeeprintmobile.android, PID: 11490
java.lang.IllegalStateException: Fragment HomeFragment{674af0} not attached to a context.
at android.support.v4.app.Fragment.requireContext(Fragment.java:611)
at android.support.v4.app.Fragment.getResources(Fragment.java:675)
at com.zeetim.zeeprintmobile.fragment.HomeFragment.renderView(HomeFragment.java:287)
at com.zeetim.zeeprintmobile.fragment.HomeFragment.access$700(HomeFragment.java:51)
at com.zeetim.zeeprintmobile.fragment.HomeFragment$ZipFile.onPostExecute(HomeFragment.java:595)
at com.zeetim.zeeprintmobile.fragment.HomeFragment$ZipFile.onPostExecute(HomeFragment.java:563)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
On some debugging, I found that isAdded() returns false and getActivity(), getContext() are null.
The flow seems very straight forward, but it's not working. So is there anything that I am missing in this?
How can I update the UI of my fragment from onPostExecute which is called from onActivityResult?
Thank you.
Try this in onPostExecute
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//if(isAdded()) {
if (fileName != null) {
renderView(view);
}
}
// }
},300);
A hack of sorts:
Since your code passes this:
CoordinatorLayout fileSnackbarView = view.findViewById(R.id.filesCoordinatorLayout);
you can use view to access resources:
view.getContext().getResources() instead of getResources()
The real issue is that your HomeFragment lost contact with the Activity.
I don't think the error is in the code you provided. More likely:
something wrong happens to your activity (although I doubt it)
something wrong happens to your fragment (more like it)
It may be that during the doInBackground another part of your code replaces your fragment with another, or removes it.

android data passing to another class by a button click

Im trying to pass data from my TestSearch class to GoogleSearch class. I assigned the values of the tEdit test to a string variable and I want to pass that to GoogleSearch class. But my app get crash when I run it.
Button disp=(Button)findViewById(R.id.btn_Search);
disp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText inputTxt = (EditText) findViewById(R.id.editText1);
String str = inputTxt.getText().toString().toLowerCase().trim();
ArrayList<HashMap<String, String>> userList = controller.searchBook(str);
if (userList.size() != 0) {
//Do something
}
else
{
Intent intent = new Intent("com.example.captchalib.GoogleSearch");
intent.putExtra("message", str);
startActivity(intent);
}
}
});
In my GoogleSearch Class I used Below Code to catch the Intent
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_menu);
Intent intent = getIntent();
String message = intent.getStringExtra("message");
((TextView)findViewById(R.id.Receive)).setText(message);
}
why this is happening and how to solve it ?
Logcat
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.captchalib.GoogleSearch (has extras) }
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
Change this line:
Intent intent = new Intent("com.example.captchalib.GoogleSearch");
To:
Intent intent = new Intent(TestSearch.this, GoogleSearch.class);

Android Intent with NullPointerException

There are many many questions about starting new Intent from another Intent but i'm unable to find solutions of mine. In my main Activity i started an Activity this way
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
and trying to get extra String value this way
public class DownloadManagerSettings extends Activity {
private Button dmOk;
private Bundle extra;
private String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dm_settings);
extra = getIntent().getExtras();
dmOk = (Button) findViewById(R.id.dm_settings_ok);
final Bundle strExtra = extra;
dmOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
try {
Intent intent = new Intent(DownloadManagerSettings.this, Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
But in my LogCat shows following error
08-28 14:19:33.777: E/AndroidRuntime(17837): java.lang.NullPointerException08-28 14:19:33.777: E/AndroidRuntime(17837): at com.downloadmanager.settings.DownloadManagerSettings$1.onClick(DownloadManagerSettings.java:101)
Here 101 Line is
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
UPDATE
new error
08-28 14:55:11.237: E/AndroidRuntime(24623): Caused by: java.lang.NullPointerException 08-28 14:55:11.237: E/AndroidRuntime(24623): at com.downloadmanager.settings.DownloadManagerSettings.onCreate(DownloadManagerSettings.java:66)
66 Line is
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
NEW UPDATE1
Now
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
Another Activity
className = getIntent().getStringExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY");
final String newClass = className;
Log.d("DM_AAAAAAAA", className);
dmOk.setOnClickListener(new View.OnClickListener() {
Find in LogCat
08-28 15:09:14.670: E/AndroidRuntime(27291): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.addon.downloadmanager/com.downloadmanager.settings.DownloadManagerSettings}: java.lang.NullPointerException: println needs a message
Thanks in advance
try this:
public class DownloadManagerSettings extends Activity {
private Button dmOk;
private Bundle extra;
private String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dm_settings);
extra = getIntent().getExtras();
dmOk = (Button) findViewById(R.id.dm_settings_ok);
final Bundle strExtra = extra;
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
dmOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method
try {
Intent intent = new Intent(DownloadManagerSettings.this, Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
Get the String data in onCreate first and then use it in onClick.
Update :
seems you'll have to add your package name as the prefix, see this. After that, use getStringExtra/getCharSequenceExtra to get the string data.(note we don't use Bundle any more). This should work.
update 1:
The following code work on my device.
Intent newIntent = new Intent(getApplicationContext().getPackageName());
newIntent.setClass(this, SecondActivity.class);
newIntent.putExtra(getApplicationContext().getPackageName()+".abc", "test");
startActivity(newIntent);
and in the other activity:
String data = getIntent().getStringExtra(getIntent().getAction()+".abc");
From the javadoc of Intent.putExtra(String,String) :
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
So try this :
intent.putExtra(getPackageManager().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
and later:
className = strExtra.getString(getPackageManager().getPackageName()+".DM_SETTINGS_ACTIVITY");
Use getStringExtra() instead of getExtra()
or you can also do in from other side during intenet creation
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
Bundle extras = new Bundle();
extras.putString("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
Try this way,hope this will help you to solve your problem.
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
className = className = getIntent().getStringExtra("DM_SETTINGS_ACTIVITY");
OR
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
Bundle bundle = new Bundle();
bundle.putString("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
className = className = getIntent().getBundleExtra().getString("DM_SETTINGS_ACTIVITY");
The problem in your code is here,
intent.putExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
Just replace this line with
intent.putExtra("MainActivity",getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY");
Check this code :
1. **MainActivity.java**
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("MY TEXT", getApplicationContext().getPackageName()+".TestActivity");
startActivity(intent);
2. **MainActivity2.java**
Intent i = getIntent();
final String className = i.getStringExtra("MY TEXT");
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity2.this,Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
This is worked on my device.

Android OnActivityResult passing data to another form and getting array result from it

I want to send some Data to another activity say SecondActivity and then getting Array data from That SecondActivity to Main activity using OnActivityResult
This is a app like when i press upload button i already have path i want to send that path to another activity and then getting the result in array from another activity to same mainactivity and then want to view that array in textview
CSVUpload
public class CSVUploader extends Activity {
Button btnUpload;
EditText txtName;
EditText txtMessageName;
Bundle extras = getIntent().getExtras();
String FullPath = extras.getString("FullPath");
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
File csvfile = new File(FullPath);
FileInputStream csvStream = new FileInputStream(csvfile);
BufferedReader in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] name = null;
String[] number = null;
int iCount=0;
while ((line = in.readLine()) != null){
String[] RowData = line.split(",");
name[iCount] = RowData[0];
number[iCount] = RowData[1];
iCount++;
/* ContentValues values = new ContentValues();
values.put(key, value);
values.put(CsvProvider.NUMBER, number);
values.put("status",status);
getContentResolver().insert(CsvProvider.CONTENT_URI, values);
*/ }
in.close();
Bundle b =new Bundle();
Intent intent = new Intent();
b.putStringArray("name", name);
b.putStringArray("number", number);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
FirstActivity
public void uploadfile(View view){
edittext = (EditText)findViewById(R.id.txtFile);
Toast.makeText(NewMessage.this, FullPath, 2000).show();
if(FullPath != null)
{
Intent intent1 = new Intent(this, CSVUploader.class);
intent1.putExtra("FullPath", FullPath);
startActivityForResult(intent1, 2);
}
else
{
Toast.makeText(NewMessage.this, "No File Selected", 2000).show();
}
}
// Listen for results.
public void onActivityResult(int requestCode, int resultCode, Intent data){
// See which child activity is calling us back.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
curPathName = data.getStringExtra("GetPath");
curFileName = data.getStringExtra("GetFileName");
FullPath = curPathName+"/"+curFileName;
edittext.setText(curFileName);
/* Toast.makeText(NewMessage.this, resId, duration);*/
}
}
if (requestCode==2){
if (resultCode == RESULT_OK) {
Bundle b=this.getIntent().getExtras();
String[] name=b.getStringArray("name");
String[] number=b.getStringArray("number");
String[] status;
}
}
try to use this code. I am not sure this will work properly
MainActivity.java
public void uploadfile(View view){
Intent intent1 = new Intent(this, CSVUploader.class);
intent1.putExtra("FullPath", FullPath);
startActivity(intent1);
}
Replace your code likewise
CSVUploader.java
Bundle b=new Bundle();
Intent i = new Intent(this,MainActivity.class);
b.putStringArray("name",name);
b.putStringArray("number",number)
i.putExtras(b);
startActivity(i);
You can retrive it in MainActivity.java as
Bundle b=this.getIntent().getExtras();
String[] name=b.getStringArray("name");
String[] number=b.getStringArray("number");
You need to put the retrieving code into onCreate instead of where you have it now.
#Override
protected void onCreate(Bundle savedInstanceState) {
String FullPath = getIntent().getStringExtra("FullPath");
By the way why you want to use another activity to do the task. Why dont you do it in the same activity.

How to send Intent Extra?

I am a beginner of Android. I want to pass the result from FirstActivity to the SecondActivity as below. How to remove results in intent extra? Or any way to pass the result to SecondActivity and show on the TextView?
(I have make a mistake and replace, my main question is how to delete the result, because i want to set another new result in it.)
FirstActivity.java
public class FirstActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//code...
try {
myDbHelper.createDatabase();
}
catch (IOException ioe) {
Log.d("Error","Error while createing Database");
ioe.printStackTrace();
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
Log.d("Error","Error while Opening Database");
sqle.printStackTrace();
throw sqle;
}
send.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
//...code
//checking for slection
results = queryData(table, type);
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
}
public String queryData(String table, String type){
//...
//do somthing to get result
return result;
}
}
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_item);
TextView tv;
tv = (TextView)findViewById(R.id.tv);
Bundle extras=getIntent().getExtras();
String value1=extras.getString("results");
tv.setText("Result\n" + value1);
}
}
You can do in 2 ways:
1. You can use startActivityForResult(), onActivityResult() from the Activity A, to pass the data on to Activity B, then after some computation, passing the result back to Activity A.
2. Now if you want to just send some data from Activity A to Activity B, and then display it in TextView, then use putExtra() and getExtras()...
Sending from Activity A to B:
Intent i = new Intent(Activity_A.this, Activity_B.class);
i.putExtra("name",Name);
startActivity(i);
Receiving the value on Activity B:
Intent i = getIntent();
String n = i.getExtras().getString("name");
change startActivityForResult(intent, 0) to startActivity(intent);
like this
private void showResult() {
results = queryData(table, type);
Intent intent = new Intent(firstActivity.this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
}
Make new intent and pass
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
You were done your way of method that pass the data to next Activity is right. But, you made a mistake with starting the activity. Starting an Activity in your code should be like below -
private void showResult() {
//...code
//checking for slection
results = queryData(table, type);
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent); // This is the way to start a new Activity which is in seperate class
}
And, just have a look at below -
How do I pass data between Activities in Android application?
Passing data between activities in Android

Categories

Resources