Button Not Making Activity Launch - java

Right now I am getting a force close on my android emulator.
Upon finishing this app, I will want to put a custom field in instead of just test, but for now I just want test to show up from the http activity.
Any help would be great!
MainActivity:
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.main.MESSAGE";
/*#SuppressLint("ParserError")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private Button searchBtn;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
searchBtn = (Button) findViewById(R.id.button1);
searchBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(null, http.class);
startActivity(intent);
}
});
}
}
Http:
public class http extends Activity {
public http(){
httpMethod();
}
public void httpMethod(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api.site.com/api/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
;
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String test = "hello";
TextView myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText(test);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.main.DisplayMessageActivity"/>
<activity android:name="com.example.main.http"/>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

There are whole lot of issues in the code:
1) Intent intent = new Intent(null, http.class);
Use first parameter as MainActivity.class instead of null
2) httpActivity should have onCreate (or) onResume life cycle activity methods to create activity for startActivity
Not but the least, please spend some time on reading documentation and doing example programs instead of just type-in something and post on SO. By going through all your questions it is something like SO community did your app for you.

You have to initialize Intent like this
Intent intent = new Intent(MainActivity.this, http.class);
You need to pass Context as first parameter not null.

start as:
searchBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, http.class);
startActivity(intent);
}
});
instead of passing null as First parameter in Intent Constructor
for more information see here
http://developer.android.com/reference/android/content/Intent.html

I trully advice you to read some Android basics beacause you have some issues in the code:
You have a null context when you're initializing the intent at the button's listener. You should have: Intent intent = new Intent(getApplicationContext(), http.class); or Intent intent = new Intent(MainActivity.this, http.class);
You need to create your ativity and set it's content. You must override at least the onCreate method.
It's not so important, but its a good practice to write code that anyone might understand instead of write code for the machine! I'm telling this because you have *activity_main* sml file where you define your main activity layout and menu. I suggest you to refractor these file names to something like main.xml, for the layout, and *main_mnu.xml*.

Related

How can I pass data to the activity in my app?

If I press the share button that appears by long pressing the text, I want to send the text to other activities of my app. I move to another activity, but the text I want is not delivered. What is the problem?
This is the code of the activity that writes the text I want to deliver.
public class MainActivity extends AppCompatActivity {
EditText editText;
Intent sendIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendIntent.putExtra("TEXT", editText.getText().toString());
sendIntent.setType("text/*");
}
});
}
}
This is the intent-filter of my xml code.
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType = "text/*"/>
</intent-filter>
This is the part that receives the intent of the activity that I want to receive data from.
Intent receiveIntent = getIntent();
url = receiveIntent.getStringExtra("TEXT");
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
This is the intent-filter part of the xml code of the activity where I want to receive data.
<activity android:name=".MyWebBrowser"
android:label="MyWebBrowser">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/*"/>
</intent-filter>
Here is a simple example for you:
Instead of long press on editText I simply use a button, but nevertheless, the logic stays almost the same:
// MainActivity. From here we send the text from EditText to SecondActivity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
EditText editText = findViewById(R.id.editText);
Intent intent = new Intent(this, SecondActivity.class);
intent.setAction("MyIntentAction");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent.putExtra("TEXT", editText.getText().toString());
startActivity(intent);
finish();
}
});
}
}
// SecondActivity. Receives and displays text from MainActivity.
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView = findViewById(R.id.textView);
Intent intent = getIntent();
if(intent.getAction().equals("MyIntentAction")) {
String str = intent.getStringExtra("TEXT");
textView.setText(str);
}
}
}
// For Long Click detection add the following code to MainActivity:
editText.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
intent.putExtra("TEXT", editText.getText().toString());
startActivity(intent);
finish();
return true;
}
});
I see that you are using two activity has LAUNCHER with the MAIN in your manifest. Please use only one in your manifest.
To pass the data to another activity in your app, you can try to use startActivity and put your data in the intent data:
On action to open the MyWebBrowser:
val intent = Intent(context, MyWebBrowser::class.java)
intent.putExtra("TEXT", yourtext)
startActivity(intent)
Get the Text in your MyWebBrowser:
override fun onCreate(savedInstanceState: Bundle?) {
...
val TEXT = intent.getStringExtra("TEXT")
textView.text = TEXT
}

Wrong activity displayed when implicit intent received from another app with Action.SEND

I have an app with two activities: MainActivity, which contains a URL entry field where the user can enter a YouTube video URL and press a submit button, to start the second activity, VideoActivity, which displays some information about this video (fetched from another web server).
The app also has a feature to receive intent via the Youtube application. When user presses the share button within the Youtube app, my app appears in the share list. Upon pressing share from the Youtube app, MainActivity should be brought to the front, and the URL should be posted within the MainActivity's URL field.
However, this only happens correctly on the first share. If the app is in the background when user shares from Youtube app, they are taken to whatever the last visible activity was, whether it is MainActivity or VideoActivity, (and even if it is MainActivity, the URL is not posted into the URL field, but the field is left in whatever state it was in when the app was last visible).
Here is my current AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youcmt.youdmcapp">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity
android:name=".VideoActivity"
android:parentActivityName=".MainActivity"/>
<service
android:name=".FetchVideoService"
android:exported="false"/>
</application>
</manifest>
Here is my MainActivity.java code:
public class MainActivity extends AppCompatActivity {
private ResponseReceiver mReceiver;
private EditText mUrlEditText;
private Button mSearchButton;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
mUrlEditText = findViewById(R.id.url_search_et);
Intent intent = getIntent();
if (intent.getType()!=null &&
intent.getType().equals("text/plain")) {
Bundle extras = getIntent().getExtras();
String value = extras.getString(Intent.EXTRA_TEXT);
if(value!=null)
{
mUrlEditText.setText(value);
}
}
mProgressBar = findViewById(R.id.progress_bar);
mSearchButton = findViewById(R.id.search_button);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
askForVideo(mUrlEditText.getText().toString());
mSearchButton.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} catch (Exception e) {
mUrlEditText.setText("");
mUrlEditText.setHint(e.getMessage());
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
//register the ResponseReceiver
mReceiver = new ResponseReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FETCH_VIDEO_INFO);
registerReceiver(mReceiver, intentFilter);
}
private void askForVideo (String url) throws Exception {
try {
Intent intent = FetchVideoService.newIntent(this, url);
startService(intent);
} catch (Exception e) {
mUrlEditText.setText(e.getMessage());
}
}
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_VIDEO_STATUS, FAIL);
mProgressBar.setVisibility(View.INVISIBLE);
mSearchButton.setVisibility(View.VISIBLE);
if(status==FAIL)
{
mUrlEditText.setText("");
mUrlEditText.setHint("Error retrieving video!");
}
else if(status==SUCCESS) {
Video video = intent.getParcelableExtra(EXTRA_VIDEO);
Intent videoActivityIntent =
VideoActivity.newIntent(getApplicationContext(), video);
startActivity(videoActivityIntent);
}
}
}
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
I do not think any of the other files will be useful in understanding the problem. Although this seems like something many app creators should have to deal with, I can find no answers to this problem. Please comment if you feel I should add any additional information and thank you in advance for any help!
Update: testing demonstrates that after the first use of "Share" from YouTube (and considering app remains in the background), the MainActivity no longer receives any new intent on further shares. However, my app is still brought to the foreground somehow. This is very confusing to me.
When you share from another app, your MainActivity is brought to the front and onNewIntent() is called on it. You don't override onNewIntent() so you never see the share Intent.

onkeyDown / onBackPressed are not working with intent?

This is a simple operation and seems to be working until I've changed my minSdk = 8 to 9 , and targetSdk remains 21 in my manifest.
Problem is that i have an activity A , and i am going to activity B when a button is pressed in activity A . Now on activity B whenever someone press back button i want to clear the activity stack and transfer my activity B to activity C . but instead it finish activity B and go to Activity A , so far i have tried onKeyDown , onBackPressed , nothing seems to work , kindly help.
Activity A (in onClick method):
Intent in = new Intent(A.this,
B.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(in);
[UPDATED]Activity B :
#Override
public void onBackPressed() {
Intent in = new Intent(this, C.class);
Bundle bundle = new Bundle();
bundle.putSerializable("Scores", score);
in.putExtras(bundle);
startActivity(in);
}
Activity C:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.C);
ScoreSaver scores = (ScoreSaver) getIntent().getExtras().getSerializable("Scores");
}
Add android:noHistory="true" to both Activity A and B in your manifest file. This way these activities won't be in your back stack.
In Activity B you have to override the behavior of onBackPressed().
It has to look like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(this, ActivityC.class);
startActivity(intent);
}
If you leave super.onBackPressed() in your method, the default behavior will happen, i.e. Activity B will be closed and you jump back to Activity A.
Issue was with Serializable object which was using storing context which will be null in next activity , which causes exception , that crashes my activity. so i removed it everything works fine. Thanks #Chris Fox
Unfortunately I do not have a Git Account, so I post the files' content here. (The app's theme inherits from Theme.AppCompat.Light.DarkActionBar)
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fox.chris.activitytest">
<application android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:theme="#style/AppTheme">
<activity
android:name=".ActivityA"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ActivityB"
android:noHistory="true">
</activity>
<activity android:name=".ActivityC">
</activity>
</application>
</manifest>
Activity A:
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
});
}
}
Activity B:
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, ActivityC.class);
startActivity(intent);
}
}
Activity C:
public class ActivityC extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c);
}
}

Correctly addressing Intents to fix ActivityNotFoundException

I get an ActivityNotFoundException when I use this code:
public void addListenerOnButton3(){
button3 = (Button) findViewById(R.id.btnSettings);
button3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intentSettings = new Intent("net.stuffilike.kanaflash.Settings");
showToast("Settings clicked,");
try{
startActivity(intentSettings);
}
catch(Exception e){
showToastL("Exception" + e);
}
return;
}
});
}
Fair enough, except I can't tell how it wants me to tell it where the Activity is. Here is the relevant section of the Manifest:
<activity
android:name="net.stuffilike.kanaflash.Settings"
android:label="#string/settings" >
<intent-filter>
<action android:name="android.intent.action.SETTINGS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
How can I be sure the compiler finds my Settings.java file?
Oh, my package is named
package net.stuffilike.kanaflash;
try this
#Override
public void onClick(View arg0) {
Intent intentSettings = new Intent(X.this,Settings.class);
showToast("Settings clicked,");
try{
startActivity(intentSettings);
}
catch(Exception e){
showToastL("Exception" + e);
}
return;
}
});
replace X with your current activity name ..
The constructor for new Intent(String action) takes action as paramter.
As per your manifest, the action you are using is android.intent.action.SETTINGS,
1.So your Intent should be as below
Intent intentSettings = new Intent("android.intent.action.SETTINGS");
or
2.You can directly invoke the activity by using the Activity name,
Intent intentSettings = new Intent(this, Settings.class);
or
3.You can also define a custom action like net.stuffilike.intent.action.SETTINGS and then use this to create your Intent like
Intent intentSettings = new Intent("net.stuffilike.intent.action.SETTINGS");
There's 2 ways you can do this.
Use the action String to let the system see what Activitys can resolve the action on the Intent. If there is more than one Activity that can resolve the action, the user will get an option to pick which one they want.
Intent intentSettings = new Intent("android.intent.action.SETTINGS");
Open the Activity using its class directly (can only be done if both Activitys are in the same app).
Intent intentSettings = new Intent(this, Settings.class);

Switch between activities in Android

I want the user to be able to tap a button and be taken to a different activity. I've used similar code before in another app, but every time I press the button now the app crashes. In the main menu I have:
Button testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("de.vogella.android.c2dm.simpleclient.TEST"));
}
});
In the manifest:
<activity
android:name=".TestClass"
android:label="#string/app_name" >
<intent-filter>
<action android:name="de.vogella.android.c2dm.simpleclient.TEST" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
TestClass.java is:
package de.vogella.android.c2dm.simpleclient;
import android.app.Activity;
import android.os.Bundle;
public class TestClass extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Try this: In the onClick modify your first class to this:
Button testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
final ClassName changeAct = this;
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
i.setClass(changeAct, TEST.class); //Change TEST.class to the name of the class you want it to go to.
startActivity(i);
stop();
}
});
Intent intent = new Intent (CurrentActivity.this, TestClass.class);
startActivity(intent);
If your TestClass is in another package just put your package in front.
Intent intent = new Intent (CurrentActivity.this, de.vogella.android.c2dm.simpleclient.TestClass.class);
startActivity(intent);
Declare the activity in manifest like this:
<activity
android:name="de.vogella.android.c2dm.simpleclient.TestClass"
</activity>

Categories

Resources