While run this code Async fatal error occurs.
I am making an application which will control computer on remote distance like Team viewer.
package pk.edu.cust.fyp.nobeen.sameer.umair.pccontroller;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
Button connectBtn;
EditText ipAddressEditTxt;
String ipAddress;
int port=4444;
boolean connectionResult = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectBtn = (Button) findViewById(R.id.connect);
ipAddressEditTxt = (EditText) findViewById(R.id.ipEditText);
ipAddress = ipAddressEditTxt.getText().toString();
connectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClientConnection clientConnection = new ClientConnection();
clientConnection.execute(ipAddress);
if(connectionResult == true) {
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
Intent intent;
intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
else
Toast.makeText(getApplicationContext(),"Connection Failed",Toast.LENGTH_SHORT).show();
}
});
}
class ClientConnection extends AsyncTask <String,String,String>
{
Socket socket;
DataInputStream dataInputStream;
DataOutputStream dataOutputStream;
Context context;
String TAG ="Client Connection";
#Override
protected String doInBackground(String... params) {
Toast.makeText(getApplicationContext(),"doInBackground run", Toast.LENGTH_SHORT).show();
try {
socket = new Socket(params.toString(), port);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Toast.makeText(getApplicationContext(),"Connection is succesfully "+dataInputStream.readUTF(),Toast.LENGTH_SHORT).show();
if(socket.isConnected())
{
connectionResult=true;
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(),"Exception occur: "+ex,Toast.LENGTH_SHORT).show();
//Log.e(TAG,ex.toString());
connectionResult = false;
}
return null;
}
protected void onPreExecute()
{
super.onPreExecute();
}
protected void onPostExecute(String s){
Toast.makeText(getApplicationContext(),"OnPost"+connectionResult,Toast.LENGTH_SHORT).show();
//super.onPostExecute(s);
}
}
}
Issue: you are showing Toast in background which not run UI thread. Remove both Toast messages from doInBackground() method
If you wanna show toasts, show them in onPreExecute() and onPostExecute() methods as those are called in UI thread but doInBackground() is being called in separate thread.
Related
I have a project, controlling a jetski from a far with a android application using Bluetooth.
I have made 2 files:
Here is the "Peripherique.java" (the Bluetooth thing):
package com.example.btjetski;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class Peripherique extends AppCompatActivity {
Button btnPaired;
ListView devicelist;
private BluetoothAdapter myBluetooth;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPaired = findViewById(R.id.button);
devicelist = findViewById(R.id.listView);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if (myBluetooth == null) {
Toast.makeText(getApplicationContext(), "Périphérique Bluetooth non disponible", Toast.LENGTH_LONG).show();
finish();
} else if (!myBluetooth.isEnabled()) {
Intent turnBTon = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list();
}
});
}
private void list() { // écouter les périphériques BT
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size() > 0) {
for (BluetoothDevice bt : pairedDevices) {
list.add(bt.getName() + "\n" + bt.getAddress());
}
} else {
Toast.makeText(getApplicationContext(), "Aucun des appareils trouvés", Toast.LENGTH_LONG).show();
}
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
}
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Intent i = new Intent(Peripherique.this, jetControl.class);
i.putExtra(EXTRA_ADDRESS, address);
startActivity(i);
}
}
Here is jetControl.java
package com.example.btjetski;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.util.UUID;
public class jetControl extends AppCompatActivity {
Button buttonON1, buttonOFF1;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(Peripherique.EXTRA_ADDRESS); //recevoir l'adresse du périphérique BT
setContentView(R.layout.activity_jet_control);
//WIDGETS
Button buttonON1 = findViewById(R.id.buttonON1);
Button buttonOFF1 = findViewById(R.id.buttonOFF1);
setOnClickListener();
}
private void setOnClickListener() {
buttonON1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllumerJetski1();
}
});
buttonOFF1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EteindreJetski1();
}
});
}
private void AllumerJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("A".toString().getBytes());
} catch (IOException e) {
}
}
}
private void EteindreJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("a".toString().getBytes());
} catch (IOException e) {
}
}
}
}
When the app starts, i can connect to my ESP32 but nothing happens, i should have an overlay that shows up with two buttons "ON/OFF" but nothing seems to work properly.
I thank you so much for your help.
package com.example.fitness;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.biometric.BiometricPrompt;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.Executor;
public class MainActivity extends AppCompatActivity {
Button auth_button;
TextView status;
private BiometricPrompt biometricPrompt;
private BiometricPrompt.PromptInfo promptInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth_button = findViewById(R.id.btn2);
status = findViewById(R.id.status);
Executor executor = ContextCompat.getMainExecutor(this);
biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new
BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
Toast.makeText(MainActivity.this,"Error:"+errString,
Toast.LENGTH_SHORT).show();
}
#Override
public void onAuthenticationSucceeded(#NonNull
BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(MainActivity.this,"Authorized", Toast.LENGTH_SHORT).show();
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
Toast.makeText(MainActivity.this,"failed to authorize",
Toast.LENGTH_SHORT).show();
}
});
promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle("Biometric
Authorization").setSubtitle("login using Finger print")
.setNegativeButtonText("Cancel").build();
auth_button.setOnClickListener(v -> biometricPrompt.authenticate(promptInfo));
}
}
I want the function to go to the new layout if the authentication is successful.
But whenever I try using intent with looping statements the code breaks and goes in an infinite
loop.
How do I overcome this problem such that the code reaches the next layout like on successful authentication.
I have a .sql database which I edit using PHPmyadmin and a android app that retrieves the login credentials from the database and tries to login to the app according to the user's credentials. But it keeps showing "Unable to login" error in the app even though I use the correct credentials from the database, which in this case is phoneno and password. The Login_Activity.JAVA is as below. Why is the app not logging in properly?
Login_Activity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
in the onCreate of activit-main i make an inistance of a class named XMPPConectio
at the constructor of the XMMPPConnection i take inistance of the activity-main and therefor i execute an Asychtask. in the progressUpdate i call triger function of activity-main. i the triger function i want to send inistance of XMPPconnectio to other activity by intent.putExtra but i get the error
Parcelable encountered IOException writing serializable object
the aim of doing all these is to have connection (when it is connected) to other activity.
please give me some sample code thank you
XMPPConectio class which implements Serializable:
public class XMPPConnectio implements Serializable {
XMPPTCPConnection connection;
String connectionMessages="";
connectionXMPP connectionXMPPAsynch;
MainActivity mainActivity;
public XMPPTCPConnection getXMPPConnectio ()
{
return connection;
}
public XMPPConnectio(MainActivity mainActivity)
{
this.mainActivity=mainActivity;
try
{
connectionXMPPAsynch =new connectionXMPP();
connectionXMPPAsynch.execute();
}
catch (Exception e)
{
}
}
class connectionXMPP extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
connection = new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
.setServiceName("192.168.1.6")
.setUsernameAndPassword("ehsan", "123")
.setPort(9090)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setDebuggerEnabled(true)
.setCompressionEnabled(false).build());
connection.setUseStreamManagement(true);
connection.addConnectionListener(new ConnectionListener()
{
#Override
public void connected(XMPPConnection connection) {
Log.d("connected", "yes connected successfully : ");
publishProgress();
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("connected","yes authenticated successfully : ");
}
#Override
public void connectionClosed() {
Log.d("connected","yes connectionClosed successfully : ");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("connected","yes connectionClosedOnError : ");
}
#Override
public void reconnectionSuccessful() {
Log.d("connected","yes reconnection successfully : ");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("connected","yes reconnectingIn : ");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("connected","yes reconnectionFailed : ");
}
});
connect();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
mainActivity.triger();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("","onPostExecute");
}
private void connect()
{
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
}
the Activity which make instance of XMPPConectio and cause Asychtask execution
package passargad.ehsan;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
public class MainActivity extends ActionBarActivity implements Serializable {
private Socket socket;
private String serverIpAddress = "192.168.1.6";
XMPPConnectio xmppConnectio;
XMPPTCPConnection connection;
private static final int REDIRECTED_SERVERPORT = 6789;
FastFood fastFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,SocketService.class);
startService(intent);
fastFood =new FastFood(this);
xmppConnectio=new XMPPConnectio(this);
}
// this is the function which is called (when connection is done ) by //onProgressUpdate of Asychtask
public void triger()
{
try {
Intent intent= new Intent(this,chat.class);
intent.putExtra("XMPP",xmppConnectio);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this is the activity which i want to have XMPPConnectio in there but the execution never reach to this
package passargad.ehsan;
import android.app.Application;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.IOException;
public class chat extends ActionBarActivity {
XMPPConnectio xmppConnectio;
XMPPTCPConnection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
xmppConnectio=(XMPPConnectio)getIntent().getSerializableExtra("XMPP");
Log.d("","done");
}
}
i tried to make the question crystal clear by giving all the code. as i said the goal is to have the connection in all activities when connection is connected.
thank you .
if i want to have connection object accessible in every activities one of the solutions is using bundle and send the bundle with intent. but the actual problem is not having bundle option in API level 10 (android 2.3). the other problem was ,not having the option to use serializing and putExtra for intent because XMPPTCPConnection does not implemet serializable. so i used the third option which was defining the object static.
so i changed the class XMPPConectio to this
import android.app.Application;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import java.io.IOException;
import java.io.Serializable;
public class XMPPConnectio {
XMPPTCPConnection connection;
String connectionMessages="";
connectionXMPP connectionXMPPAsynch;
MainActivity mainActivity;
public XMPPTCPConnection getXMPPConnectio ()
{
return connection;
}
public XMPPConnectio(MainActivity mainActivity)
{
this.mainActivity=mainActivity;
try
{
connectionXMPPAsynch =new connectionXMPP();
connectionXMPPAsynch.execute();
}
catch (Exception e)
{
}
}
class connectionXMPP extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
connection = new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
.setServiceName("192.168.1.6")
.setUsernameAndPassword("ehsan", "123")
.setPort(9090)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setDebuggerEnabled(true)
.setCompressionEnabled(false).build());
connection.setUseStreamManagement(true);
connection.addConnectionListener(new ConnectionListener()
{
#Override
public void connected(XMPPConnection connection) {
Log.d("connected","yes connected successfully : ");
publishProgress();
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("connected","yes authenticated successfully : ");
}
#Override
public void connectionClosed() {
Log.d("connected","yes connectionClosed successfully : ");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("connected","yes connectionClosedOnError : ");
}
#Override
public void reconnectionSuccessful() {
Log.d("connected","yes reconnection successfully : ");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("connected","yes reconnectingIn : ");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("connected","yes reconnectionFailed : ");
}
});
connect();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
mainActivity.triger();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("","onPostExecute");
}
private void connect()
{
try {
connection.connect();
// connection.login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
}
the Activity which make instance of XMPPConectio and cause Asychtask execution
package passargad.ehsan;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
public class MainActivity extends ActionBarActivity {
private Socket socket;
private String serverIpAddress = "192.168.1.6";
XMPPConnectio xmppConnectio;
public static XMPPTCPConnection connection;
private static final int REDIRECTED_SERVERPORT = 6789;
FastFood fastFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,SocketService.class);
startService(intent);
fastFood =new FastFood(this);
//this is
xmppConnectio=new XMPPConnectio(this);
}
public void triger()
{
connection=xmppConnectio.getXMPPConnectio();
Intent intent= new Intent(this,chat.class);
startActivity(intent);
}
}
this is the activity which we can access the connection there
package passargad.ehsan;
import android.app.Application;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.IOException;
public class chat extends ActionBarActivity {
XMPPTCPConnection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
//this is
connection=MainActivity.connection;
connection.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
Log.d("","connected");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("","6");
}
#Override
public void connectionClosed() {
Log.d("","5");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("","4");
}
#Override
public void reconnectionSuccessful() {
Log.d("","3");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("","2");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("","1");
}
});
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a simple app that has an unlock feature in it. When a user purchases this they can unlock more content in the app.
When I debug the app I don't get any errors, but I am unable to retrieve a list of products using the google billing services.
On my main activity I would like to check if the user has all ready purchased the "upgrade" if they have do something with that information.
I have been following the api documentation but its not really helping.
In App Billing Reference
Implementation
Testing
I have 1 item in my In-app products, I have followed the testing document and added an apk to my Alpha testing. The problem here is that apk cant have debugging enabled, so when I use the debugger in android studio the app may perform differently??
I think my code is OK,but any help or guidance in how to test this would be great.
MainActivity.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
IInAppBillingService mService;
ServiceConnection connection;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button start = (Button) findViewById(R.id.startgame);
Button settings = (Button) findViewById(R.id.about);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StartGame.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Settings.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
/// check for pro unlock
serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
// first this
connection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("BILLING", "Connected");
//purchse info
mService = IInAppBillingService.Stub.asInterface(service);
checkPurchaseInfo();
}
};
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
}
private void checkPurchaseInfo() {
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
int responseCode = ownedItems.getInt("RESPONSE_CODE");
Log.d("BILLING","Request Code: " + responseCode);
if(responseCode == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.d("OWNED",ownedSkus.toString());
Log.d("purcahseList",purchaseDataList.toString());
Log.d("SIGNLIST",signatureList.toString());
/////////
//all of these arrays come back as empty []
////////
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);
}
}
}