App crashes saying 'Unfortunately, app has stopped' while using asmack - xmpp

Here is my code for connecting to OpenFire through aSmack API. I am getting an error saying 'unfortunately app has stopped' when trying to run the app on my phone. When i remove the code of aSmack, the app is working fine with creating one button. I also have added the jars into the classpath. Please help me.
package com.example.demo;
import java.io.File;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
String username = "swapnil", password = "swapnil", host = "192.168.0.4", service = "mirana";
int port = 5222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button1);
final EditText et =(EditText)findViewById(R.id.editText1);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// et.setText("Test");
XMPPConnection xmpp = null;
ConnectionConfiguration xmppConfig = new ConnectionConfiguration("192.168.0.4", 5222,"mirana");
xmppConfig.setSASLAuthenticationEnabled(true);
xmppConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
if (xmppConfig == null)
throw new NullPointerException("XMPPService must be configured before it can connect!");
try {
if (xmpp == null) {
xmpp = new XMPPConnection(xmppConfig);
}
xmpp.connect();
} catch (XMPPException ex) {
et.setText("ERROR !");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
And here is the manifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.demo.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>
</application>
</manifest>

Without log, after watching your code,what I can guess is that, you are running smack methods on Main Thread.. The exception should be of NetworkOnMainThreadException.
You should do the task, in your button click, on background threads. You might want to create AsyncTask for this.
Also, you dont have Internet permission. So please fix that too..
While implementing Smack, you need to take care of maintaining sessions of Smack Connections and related ones.. For this, you can refer the following the GitHub demo app: Smack Android Demo

You have to add Internet permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
And you need to add below code in onCreate() method.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Related

Unable to save data on heroku in android studio

I deployed Parse Server example (https://github.com/ParsePlatform/parse-server-example) to Heroku. After following many tutorials, I tried to save a simple data onto the MongoDB add-on in Heroku but I get a Save Failed message according to my code i demanded Save Failed or Save Succeeded. I also checked it on the Parse-Dashboard locally as well as from the MongoDB website, but i got nothing over there.
Here is my Code:
MainActivity.java
package com.example.parsedemo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.ParseAnalytics;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
StarterApplication.java:
package com.example.parsedemo;
import android.app.Application;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("instagram666666")
.clientKey(null)
.server("http://instagram666666.herokuapp.com/parse/")
.build()
);
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.i("Parse", "Save Failed");
}
}
});
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
Gradle.build :
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.example.parsedemo"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile files('libs/bolts-tasks-1.4.0.jar')
compile files('libs/parse-android-1.13.1.jar')
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.parsedemo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:name= '.StarterApplication'>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I also imported required libraries as required, but still unable to Save data on the DB. I've been stuck here for around a week!
I am using version 1.5 of Android Studio.
You need to link the database to your application using the Heroku command line interface.
Follow these steps:
Download and install or open the Heroku CLI if already installed.
Type heroku login and press enter to open a browser and login with your Heroku credentials.
The CLI should now say "logged in as YourHerokuUsername#YourEmail.com"
Copy the mongoDB link (db_link) from your apps' settings on Heroku dashboard
Now type in heroku config:set DATABASE_URI=db_link -a app_name where app_name is the name of the application you want to link with your database.
Run your project again & your log should now say "Save Succeeded."
Open your database using the Heroku dashboard for the app you just linked with the database to see your ParseObject stored under collections.

Call an activity using Alarm Manager & Broadcast Receiver

I'm trying to create an app that automatically make phone calls after regular intervals to a specified number. I'm using Alarm Manager and Broadcast Receiver for this purpose. Alarm Manager can't initiate PHONE CALL activity and application terminates giving an error.
Here's my code. I am new in this Dev this.
*MainActivity.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView label;
private EditText phoneNum;
private PendingIntent pendingIntent;
private AlarmManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
label=(TextView)findViewById(R.id.entertextlabel);
phoneNum=(EditText)findViewById(R.id.phonenofield);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
//pendingIntent = PendingIntent.getActivity(this,1,alarmIntent,0);
}
public void startAlarm(View view) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(View view) {
if (manager != null) {
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
}
*AlarmReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
/**
* Created by Saud on 05/11/2015.
*/
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
Intent in = new Intent(Intent.ACTION_CALL);
in.setData(Uri.parse("tel:03324310929"));
context.startActivity(in);
}
}
I'm getting error "Call requires user permission...."
at
context.startActivity(in);
*mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter the Mobile number"
android:id="#+id/entertextlabel"
android:layout_centerHorizontal="true"
android:layout_marginTop="79dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Alarm"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/callBtn"
android:layout_marginBottom="81dp"
android:onClick="startAlarm"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel Alarm"
android:id="#+id/button2"
android:layout_alignTop="#+id/button"
android:layout_toEndOf="#+id/callBtn"
android:onClick="cancelAlarm"/>
</RelativeLayout>
*Mantifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saud.nexustelecom" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<receiver android:name=".AlarmReceiver"></receiver>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The issue is resolved.
I used the Flag "FLAG_ACTIVITY_NEW_TASK" with with the intent in AlarmReceiver class.
New code is as follows
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
/**
* Created by Saud on 05/11/2015.
*/
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
// Intent in = new Intent(Intent.ACTION_CALL);
//in.setData(Uri.parse("tel:03324310929"));
Intent in = new Intent(Intent.ACTION_CALL);
in.setData(Uri.parse("tel:03324310929"));
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in);
}
}

NewActivity not resolving in base class - should/how do I get the base class to recognize it?

Using Eclipse on OSX:
I'm trying to start my first new activity from an Intent. The error seems to be here:
Intent newButton = new Intent(v.getContext(),RandomActivity.class);
startActivity(RandomActivity);
RandomActivity isn't getting resolved. I think I have it correct in my Manifest file. I think my imports are correct. Do I need to declare it somewhere in my base Activity? That doesn't seem to work. It's like the code doesn't recognize the existence of the new class, but I can't see where to fix that.
The rest of my code:
package course.examples.UI.Button;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import course.examples.UI.Button.R;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import course.examples.UI.Button.RandomActivity;
public class ButtonActivity extends Activity {
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent newButton = new Intent(v.getContext(),RandomActivity.class);
startActivity(RandomActivity);
^Multiple markers at this line
brandNewButton cannot be resolved to a type
RandomActivity cannot be resolved to a variable
Note: brandNewButton WAS a class, but I deleted it, then went File->New->Class to create RandomActivity.java.
}
});
}
}
My XML code is below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button
android:id="#+id/button"
android:text="Press Me!"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
>
</Button>
</RelativeLayout>
And here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="course.examples.UI.Button"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<application
android:allowBackup="false"
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name=".ButtonActivity"
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=".RandomActivity">
</activity>
</application>
</manifest>
Thanks in advance everyone, it's great to have such a community of support here for us noobies.
You don't really need to do :
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent newButton = new Intent(v.getContext(),RandomActivity.class);
Here's the issue: You are trying to start activity with different intent name ??
"startActivity(RandomActivity);" // Wrong intent name
Check your intent!
Instead, just try using this :
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent newButton = new Intent(ButtonActivity.this, RandomActivity.class);
startActivity(newButtom);//This is right
Also.. if your RandomActivity is not from your same package, register it with full path like:
<activity android:name="your packagename where random activity is.RandomActivity" />
Hope this helps.

Start Activity Intent from Android Application

I have an activity that holds a handler that I need to be running for the whole app. What I need to do is call the handler activity whenever main activity starts up, then upon executing a function at handler activity, handler activity should start the intent into second activity.
This is my code:
public class MyApp extends Application {
public void onCreate() {
h = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Log.d("tag",b.getString("msg"));
//THIS IS WHERE I WANT TO OPEN SECONDACTIVITY
}
};
}
}
MyApp is a global Application class I use to run a socket connection across the whole app. It needs to be alive as long as the app is running.
Its simple
Intent intent = new Intent(YourActivityClass.this, SECONDACTIVITY.class);
startActivity(intent);
public class MyApp extends Application {
public void onCreate() {
h = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Log.d("tag",b.getString("msg"));
Intent myIntent = new Intent(this, YourSecondActivity.class);
startActivity(myIntent);
}
};
}
}
Also add this to your manifest file
<activity android:name=".YourSecondActivity" />
Well, It turns out that I need to add: i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent i = new Intent(MyApp.this, SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Because From MainActivity, I called MyApp (An class to maintain global application state). Then in MyApp, I process something and then I call SecondActivity.
First You add the activity information in AndroidManifest.xml LIKE
<activity
android:name="com.assignment.matchnumber.PlayActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.assignment.matchnumber.PLAY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Then put this in your MyApp activity where you want.
Intent openPlayActivity = new Intent("com.assignment.matchnumber.PLAY");
startActivity(openPlayActivity);
thanks
--Sajib

PayPal Error - Please make sure all fields have been entered

I have a problem in creating a working PayPal button in Sandbox environment.
After entering my email and password in the sandbox environment.
This is what I see.
Here are my codes
AndroidManifest.xml
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MypaypalActivity"
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.paypal.android.MEP.PayPalActivity"
android:configChanges="keyboardHidden|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</manifest>
MypaypalActivity
public class MypaypalActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout MainLayout= new LinearLayout(this);
setContentView(R.layout.main);
PayPal pp = PayPal.initWithAppID(this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
LinearLayout layoutSimplePayment = new LinearLayout(this);
layoutSimplePayment.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);
CheckoutButton COButton = pp.getCheckoutButton(this, PayPal.BUTTON_118x24, CheckoutButton.TEXT_PAY);
COButton.setOnClickListener(this);
layoutSimplePayment.addView(COButton);
MainLayout.addView(layoutSimplePayment);
setContentView(MainLayout);
}
public void onClick(View v) {
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal("10"));
payment.setCurrencyType("USD");
payment.setRecipient("becozofeuu_92#hotmail.com");
// payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
startActivityForResult(checkoutIntent, 1);
}
I faced same problem, finally I solve it using this code to
pass integer value to Bigdecimal
payment.setSubtotal(new BigDecimal("10"));
instead of using:
payment.setSubtotal(new BigDecimal(10));
e.g.:
public void onClick(View v) {
PayPalPayment payment = new PayPalPayment();
payment.setSubtotal(new BigDecimal("10"));
payment.setCurrencyType("USD");
payment.setRecipient("becozofeuu_92#hotmail.com");
// payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
startActivityForResult(checkoutIntent, 1);
}