I'm having a class Mqtt with this code as below :
Code:
package com.example.myhome;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import java.io.UnsupportedEncodingException;
public class Mqtt {
public MqttAndroidClient mqttAndroidClient;
final String serverUri = "tcp://***";
final String clientId = "***";
final String username = "***";
final String password = "***";
public Mqtt(Context context) {
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallback() {
//@Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallback callback) {
mqttAndroidClient.setCallback(callback);
}
private void connect() {
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
//mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
// disconnectedBufferOptions.setBufferEnabled(true);
// disconnectedBufferOptions.setBufferSize(100);
//disconnectedBufferOptions.setPersistBuffer(false);
//disconnectedBufferOptions.setDeleteOldestMessages(false);
// mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic("esp/test");
//publishToTopic("esp/test","POPdd");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex) {
ex.printStackTrace();
}
}
private void subscribeToTopic(String Topic) {
try {
mqttAndroidClient.subscribe(Topic, 0, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt", "Subscribed!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exceptionst subscribed");
ex.printStackTrace();
}
}
public void publishToTopic(MqttAndroidClient client,String Topic,String MessageForTopic) {
String payload = MessageForTopic ;
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
client.publish(Topic, message,null,new IMqttActionListener() {
// @Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt", "Published!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Published fail!");
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MqttPersistenceException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
i have also a class Hoofdmenu (code below) with a layout. Here i want to send a message into the mqtt
=> MqttCommunicatie.publishToTopic(MqttCommunicatie.mqttAndroidClient,"esp/test","Message MQTT");
when i publishToTopic after the subscribe into class Mqtt the i receive the message when i ask into the class Hoofdmenu it doens't work
what do i do wrong ? Or wht can i do to to it work ?
now receive the message "MyHome is stopped Open app again"
Code:
package com.example.myhome;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.example.myhome.HoofdmenuTabs.PagerAdapter;
import com.google.android.material.tabs.TabLayout;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import java.io.UnsupportedEncodingException;
public class Hoofdmenu extends AppCompatActivity {
public Mqtt MqttCommunicatie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hoofdmenu);
TabLayout tabMenu = (TabLayout) findViewById(R.id.tabMenu);
final ViewPager viewPager = (ViewPager) findViewById(R.id.tabpager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabMenu.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabMenu));
tabMenu.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
startMqtt();
MqttCommunicatie.publishToTopic(MqttCommunicatie.mqttAndroidClient,"esp/test","Message MQTT");
}
private void startMqtt(){
MqttCommunicatie = new Mqtt(getApplicationContext());
MqttCommunicatie.setCallback(new MqttCallback() {
//@Override
public void connectComplete(boolean b, String s) {
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Debug", mqttMessage.toString());
//dataReceived.setText(mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
}
Related
I wrote a simple application to connect to a bluetooth mini keyboard but am having trouble with the BluetoothDevice.connect() call.
it gives discovery service failed. I have no problem using the bluetooth pairing and connect from the bluetooth settings menu. The same code works with a bluesnap serial to bluetooth device.
Am I missing something obvious?
I'm on galaxy tab froyo.
The code is:
Code:
package test.com;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
//import test.com.connect.ClientConnectThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class connect extends Activity {
static final int ALERT_DIALOG_ID = 1;
private BtReceiver btReceiver;
private BluetoothAdapter btAdapter;
private final Handler handler = new Handler();
private static final UUID SIMPLE_BT_APP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ClientConnectThread clientConnectThread;
private BluetoothDataCommThread bluetoothDataCommThread;
private BluetoothDevice remoteDevice;
private BluetoothSocket activeBluetoothSocket;
private final String deviceAddress="98:9A:10:12:03:6E";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btAdapter=BluetoothAdapter.getDefaultAdapter();
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "No Bluetooth Available",Toast.LENGTH_LONG ).show();
}else
{
if(!btAdapter.isEnabled())
{
Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//REQUEST_ENABLE_BT is supposed to be 2 so
startActivityForResult(enableBtIntent, 2);
}
// we need a broadcast receiver now
btReceiver = new BtReceiver();
// register for state change broadcast events
IntentFilter stateChangedFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(btReceiver, stateChangedFilter);
// register for discovery events
IntentFilter actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(btReceiver, actionFoundFilter);
// check current state
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
}
}
public void findDevicesHandler(View view){
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
Toast.makeText(getApplicationContext(), "Finding devices",Toast.LENGTH_LONG ).show();
findDevices();
}
else
{
Toast.makeText(getApplicationContext(), "Adapter is off",Toast.LENGTH_LONG ).show();
}
}
protected void onActivityResult(int request,int result,Intent data)
{
if(result==RESULT_OK)
{
Toast.makeText(getApplicationContext(), "TURNING ON BLUETOOTH",Toast.LENGTH_LONG ).show();
}
}
public class BtReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
setStatus("Broadcast: Got ACTION_STATE_CHANGED");
int currentState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
} else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
setStatus("Broadcast: Got ACTION_FOUND");
BluetoothDevice foundDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
setStatus("Device: " + foundDevice.getName() + "@" + foundDevice.getAddress());
remoteDevice=foundDevice;
if(remoteDevice.getAddress().equals(deviceAddress))
{
takeAction();
}
}
}
}
private void setStatus(String string){
Toast.makeText(getApplicationContext(), string,Toast.LENGTH_LONG ).show();
}
private void findDevices() {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevices) {
if (pairedDevice.getAddress().equals(deviceAddress)) {
setStatus("Found device: " + pairedDevice.getName() + "@" + deviceAddress);
remoteDevice = pairedDevice;
}
}
if (remoteDevice == null) {
setStatus("Starting discovery...");
if (btAdapter.startDiscovery()) {
setStatus("Discovery started...");
}
}
else
{
setStatus("Remote Device Address:"+remoteDevice.getAddress());
takeAction();
}
}
private void takeAction()
{
Toast.makeText(getApplicationContext(), "GETTING READY",Toast.LENGTH_LONG).show();
clientConnectThread = new ClientConnectThread(remoteDevice);
clientConnectThread.run();
}
@Override
protected void onDestroy() {
if (clientConnectThread != null) {
clientConnectThread.stopConnecting();
}
if (bluetoothDataCommThread != null) {
bluetoothDataCommThread.disconnect();
}
if (activeBluetoothSocket != null) {
try {
activeBluetoothSocket.close();
} catch (IOException e) {
//Log.e(DEBUG_TAG, "Failed to close socket", e);
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
btAdapter.cancelDiscovery();
this.unregisterReceiver(btReceiver);
super.onDestroy();
}
public void doStartDataCommThread() {
if (activeBluetoothSocket == null) {
setStatus("Can't start datacomm");
} else {
setStatus("Data comm thread starting");
bluetoothDataCommThread = new BluetoothDataCommThread(activeBluetoothSocket);
bluetoothDataCommThread.start();
}
}
private void setLastUsedRemoteBTDevice(String name) {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
Editor edit = prefs.edit();
edit.putString("LAST_REMOTE_DEVICE_ADDRESS", name);
edit.commit();
}
// client thread: used to make a synchronous connect call to a device
private class ClientConnectThread extends Thread {
private final BluetoothDevice remoteDevice;
private BluetoothSocket clientSocket;
public ClientConnectThread(BluetoothDevice remoteDevice) {
this.remoteDevice = remoteDevice;
clientSocket = null;
}
public void run() {
boolean success = false;
//success=true;
try {
btAdapter.cancelDiscovery();
//Method m = remoteDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createScoSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createInsecureRfcommSocket",new Class[] { int.class});
//clientSocket=(BluetoothSocket)m.invoke(remoteDevice,0);
clientSocket = remoteDevice.createRfcommSocketToServiceRecord(SIMPLE_BT_APP_UUID);
clientSocket.connect();
success = true;
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
try {
clientSocket.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(),"CLOSE:"+ e.toString(),Toast.LENGTH_LONG ).show();
}
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (NoSuchMethodException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} /*catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
}*/
final String status;
if (success) {
status = "Connected to remote device";
activeBluetoothSocket = clientSocket;
// we don't need to keep listening
//serverListenThread.stopListening();
} else {
status = "Failed to connect to remote device";
activeBluetoothSocket = null;
}
handler.post(new Runnable() {
public void run() {
setStatus(status);
setLastUsedRemoteBTDevice(remoteDevice.getAddress());
doStartDataCommThread();
}
});
}
public void stopConnecting() {
try {
clientSocket.close();
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to stop connecting", e);
Toast.makeText(getApplicationContext(), "CLOSE2:"+e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
private class BluetoothDataCommThread extends Thread {
private final BluetoothSocket dataSocket;
private final InputStream inData;
public BluetoothDataCommThread(BluetoothSocket dataSocket) {
this.dataSocket = dataSocket;
InputStream inData = null;
try {
inData = dataSocket.getInputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
this.inData = inData;
}
public void run() {
byte[] readBuffer = new byte[64];
int readSize = 0;
try {
while (true) {
readSize=inData.read(readBuffer, 0, 24);
final String inStr = new String(readBuffer, 0, readSize);
handler.post(new Runnable() {
public void run() {
doHandleReceivedCommand(inStr);
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
public void disconnect() {
try {
dataSocket.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
public void doHandleReceivedCommand(String rawCommand) {
String command = rawCommand.trim();
setStatus("Got: "+ command);
}
}
www.code.google.com
so it is right that not all bluetooth keyboard might work properly with any kind of android handheld....as yesterday i just read it in one of bluetooth keyboard
Hey guys,
I've just started experimenting with some coding, picked up a few tutorials and made some stuff work.
Now i'm stuck at a point where i want to return a modded version of a method which will replace the original method.
This is what i have so far.
Code:
package mjxl.xposed.cm11;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class CM11notifications implements IXposedHookLoadPackage {
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.android.systemui")) {
ClassLoader classLoader = lpparam.classLoader;
XC_MethodReplacement methodreplacer = new XC_MethodReplacement() {
protected Object replaceHookedMethod(
XC_MethodHook.MethodHookParam paramAnonymousMethodHookParam)
throws Throwable {
return *WHAT DO I PUT HERE?? *;
}
};
XposedHelpers.findAndHookMethod("com.android.systemui.MmsConfig", classLoader, "applyLegacyRowBackground", methodreplacer);
}
}
}
I want to return a copy of "applyLegacyRowBackground" with some edits, so it will take my layouts.
Now i know i have to return it where "Integer.valueOf(255); is, but how to ?
Can anyone guide me ?
Here's the method which i want to place there.
Code:
protected void applyLegacyRowBackground(StatusBarNotification sbn, View content) {
if (sbn.getNotification().contentView.getLayoutId() !=
R.layout.notification_template_base_mjxl) {
int version = 0;
try {
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(sbn.getPackageName(), 0);
version = info.targetSdkVersion;
} catch (NameNotFoundException ex) {
Log.e(TAG, "Failed looking up ApplicationInfo for " + sbn.getPackageName(), ex);
}
if (version > 0 && version < Build.VERSION_CODES.GINGERBREAD) {
content.setBackgroundResource(R.drawable.notification_row_legacy_bg_mjxl);
} else {
content.setBackgroundResource(R.drawable.notification_bg_mjxl);
}
}
}
Since the method you're replacing is void (it returns nothing): `return None;`.
PS. You're trying to hook `applyLegacyRowBackground()` instead of `applyLegacyRowBackground(StatusBarNotification, View)`. You should pass the arguments' classes to findAndHookMethod(…), for example:
Code:
XposedHelpers.findAndHookMethod("com.android.systemui.MmsConfig", classLoader, "applyLegacyRowBackground", StatusBarNotification.class, View.class, methodreplacer);
If you can't access the class directly (because it's not in the SDK, for example), pass its full class name as a string instead (e.g. "android.view.View" instead of `View.class`).
I am trying to log HTTP requests and answers from single apps.
Code:
import java.net.URL;
import android.util.Log;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class Module implements IXposedHookLoadPackage {
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals(Common.CLASSNAME)) {
final Class<?> httpUrlConnection = XposedHelpers.findClass(
"java.net.HttpURLConnection", lpparam.classLoader);
XposedBridge.hookAllConstructors(httpUrlConnection, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
URL url = (URL)param.args[0];
Log.d("httpLogger", "call:"+url.toString());
}
});
}
}
}
So far i can retrieve the URLs but i do not know how to advance any further from here. Can you tell a smart way to approache the problem.
now that its been a while and i did not get any closer.. *bump*
Well, just follow API.
HttpResponse response = httpclient.execute(httppost);
Click to expand...
Click to collapse
So hook "execute" method from HttpClient class.
I have two problems with that.
The first one is:
HttpClient seems to be deprecated (http://developer.android.com/reference/org/apache/http/client/HttpClient.html). I am guessing a decent application would already use java.net.URL.openConnection().
But if we keep that point asside and assume the request we are trying to hook would be done with HttpClient execute i tryed to just see any of them done:
Code:
public class Module implements IXposedHookLoadPackage {
protected static final String HTTP_TAG = "myHttpLogger";
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
final Class<?> httpUrlConnection = findClass("org.apache.http.client.HttpClient", lpparam.classLoader);
findAndHookMethod(httpUrlConnection, "execute", HttpResponse.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Log.d(HTTP_TAG, "execute");
}
});
}
}
This trows an exception
Code:
java.lang.NoSuchMethodError: org.apache.http.client.HttpClient#execute(org.apache.http.HttpResponse)#exact
Can you tell me where i went wrong or show me a different approach?
You used HttpResponse.class as method's params. But it is not right.
HttpUriRequest.class is right parameter.
To covel all "execute" methods (I see many here http://developer.android.com/reference/org/apache/http/client/HttpClient.html), use XposedBridge.hookAllmethods API
hi
Im new in android studio,
I´m trying to send to a db but it not works and i dont know why. when i click the button it does nothing.
can somebody help?
thanks
my code:
Code:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class WebService extends Activity {
private EditText dni;
private EditText nombre;
private EditText telefono;
private EditText email;
private Button insertar;
private Button mostrar;
private ImageButton mas;
private ImageButton menos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.fragment2);
dni=(EditText)findViewById(R.id.dni);
nombre=(EditText)findViewById(R.id.nombre);
telefono=(EditText)findViewById(R.id.telefono);
email=(EditText)findViewById(R.id.email);
insertar=(Button)findViewById(R.id.insertar);
insertar.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!dni.getText().toString().trim().equalsIgnoreCase("")||
!nombre.getText().toString().trim().equalsIgnoreCase("")||
!telefono.getText().toString().trim().equalsIgnoreCase("")||
!email.getText().toString().trim().equalsIgnoreCase(""))
new Insertar(WebServiceExample.this).execute();
else
Toast.makeText(WebServiceExample.this, "Hay informaci�n por rellenar", Toast.LENGTH_LONG).show();
}
});
}
private boolean insertar(){
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
HttpPost httppost;
httpclient=new DefaultHttpClient();
httppost= new HttpPost("myhost");
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("dni",dni.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("nombre",nombre.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("telefono",telefono.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("email",email.getText().toString().trim()));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
class Insertar extends AsyncTask<String,String,String>{
private Activity context;
Insertar(Activity context){
this.context=context;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(insertar())
context.runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Persona insertada con �xito", Toast.LENGTH_LONG).show();
nombre.setText("");
dni.setText("");
telefono.setText("");
email.setText("");
}
});
else
context.runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Persona no insertada con �xito", Toast.LENGTH_LONG).show();
}
});
return null;
}
}
}
Hey guys.
So, I've spent the last two days watching every tutorial about working with sqlite, but I'm doing something wrong and can't find out what.
The app is done, only needs the SQLite part, Its basicly a webapp with favorites.
Altough I have changed the code several times, this is what I ended up with:
DBManager.java
<code>
package com.rjpf.mywebapps;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager
{
private DbHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c)
{
context=c;
}
public DBManager open() throws SQLException
{
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void insert(String name, String url)
{
ContentValues contentValue = new ContentValues();
contentValue.put(DbHelper.CONTACTS_COLUMN_NAME, name);
contentValue.put(DbHelper.CONTACTS_COLUMN_URL, url);
database.insert(dbHelper.CONTACTS_TABLE_NAME, null, contentValue);
}
}
</code>
When I try to call it in the main activity with:
MainActivity.java
<code>
(...)
private LinearLayout Layout_Add;
private TextView TxT_add_nomE;
private TextView TxT_add_urL;
private Button Button_Add_to_DB;
private Button btn_BACK_Add;
DbHelper myDB;
(...)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new DbHelper(this);
(...)
Button_Add_to_DB.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Add_ItemToDb();
}
});
(...)
public void Add_ItemToDb()
{
if (TxT_add_nomE.getText().toString().trim().length() == 0 || TxT_add_urL.getText().toString().trim().length() == 0)
{
TxT_add_nomE.setText("Please don't leave fields empty!");
return;
}
else
{
String addNome = TxT_add_nomE.getText().toString();
String addUrl = TxT_add_urL.getText().toString();
// ADD TO DB
DBManager DataManager = new DBManager(this);
DataManager.insert(addNome,addUrl); // This line is what gives the error, when I click the button to add the App craches
TxT_add_nomE.setText("Name");
TxT_add_urL.setText("Url");
}
}
</code>
Thanks in advance and sorry for the long post, This is my first app and also the first time in java