android studio database - Android Studio

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;
}
}
}

Related

[Q] .9 png's and layouts.. ?

I'm having trouble replacing certain drawables, i've made a few work, some others just don't get replaced.
Here's a bit for a part that works.
Code:
package mjxl.xposed.cm11;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
public class CM11transparentstuff implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
private static String MODULE_PATH = null;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
MODULE_PATH = startupParam.modulePath;
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(MODULE_PATH, resparam.res);
resparam.res.setReplacement("android", "drawable", "overscroll_edge", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
Now i want to replace the notification_bg_normal.9.png and notification_bg_normal_pressed.9.png with my versions.
Technically i should be able to add a line like this:
resparam.res.setReplacement("android", "drawable", "notification_bg_normal", modRes.fwd(R.drawable.not_bg_normal));
And ofcourse add the drawable (notification_bg_normal_BLA.9.png) in my folder (xhdpi in my case)
Then i've tried to do it in a different class like this, which fails aswell. :/
Code:
package mjxl.xposed.cm11;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
public class CM11notifications implements IXposedHookZygoteInit {
public void initZygote(StartupParam startupParam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(startupParam.modulePath, null);
XResources.setSystemWideReplacement("android", "drawable", "notification_bg", modRes.fwd(R.drawable.notification_bg)); <<<<--- notification_bg.xml (doesnt work)
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal", modRes.fwd(R.drawable.not_bg_normal)); <<<<---- notification_bg_normal.9.png (also does not work)
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal_pressed", modRes.fwd(R.drawable.not_bg_normal_pressed));
}
}
Any help ? What am i missing ?
Just fyi, i don't have any Java programming experience.
I followed the steps on Github wiki, and i've made SOME stuff work.. Why don't these work ?
/added:
I also made this, it's in 'framework-res' aswell, but this one DOES seem to work.
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
public class ts2 implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
resparam.res.setReplacement("android", "drawable", "overscroll_glow", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
resparam.res.setReplacement("android", "drawable", "overscroll_edge", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
Trying to hook the layout where the notification_bg.xml is called as background.
Following the "Modifying Layouts" on the Github Tutorial i came up to this:
Code:
package mjxl.xposed.cm11;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
public class CM11notifications implements IXposedHookInitPackageResources {
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
resparam.res.hookLayout("android", "layout", "notification_template_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_text", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_inbox", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
resparam.res.hookLayout("android", "layout", "notification_template_big_picture", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.notification_bg);
XposedBridge.log("hey Ho");
}
});
}
}
Am i making any mistakes here ? i don't see it :/ i've tried setBackground instead of BackgroundResource, but that doesn't get accepted.. Neither does setBackgroundDrawable
edit: in initZygote with systemwideLayout
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
public class not implements IXposedHookZygoteInit {
@Override
public void initZygote(IXposedHookZygoteInit.StartupParam startupParam) throws Throwable {
XResources.hookSystemWideLayout("android", "layout", "notification_template_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_picture", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_base", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_big_text", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
XResources.hookSystemWideLayout("android", "layout", "notification_template_inbox", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
TextView notif = (TextView) liparam.view.findViewById(
liparam.res.getIdentifier("status_bar_latest_event_content", "id", "android"));
notif.setBackgroundResource(R.drawable.mjxl_bg);
XposedBridge.log("hey Ho");
}
});
}
}
How is it not working? Did you check the Xposed log to see if there are any errors there?
Did you verify the drawable you're trying to replace is also on your device (by e.g. decompiling framework-res.apk)? Some vendors remove/rename drawables that are present in AOSP and/or add their own.
I don't get any errors..
The files are there, I decompiled the files myself lol.
Also the log doesn't show either :/
This SHOULD work right?¿
(Added info, I'm working on CM11 sources)
It looks correct to me. Not sure why it wouldn't work. Maybe some of the drawables you're replacing aren't actually used where you think they're used?
GermainZ said:
It looks correct to me. Not sure why it wouldn't work. Maybe some of the drawables you're replacing aren't actually used where you think they're used?
Click to expand...
Click to collapse
I know that i need to address notification_bg.xml, which contains notification_bg_normal(_pressed).9.png (Blurred Sytem-UI by Serajr: clicky, PNG'sclicky)
I just want to replace the drawables. (either xml or the png's)
Another failed try:
Code:
package mjxl.xposed.cm11;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
public class notBG implements IXposedHookZygoteInit {
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
XposedBridge.log("y0");
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
XResources.setSystemWideReplacement("android", "drawable", "notification_bg_normal_pressed", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
return new ColorDrawable(Color.TRANSPARENT);
}
});
}
}
I will has continue.
Also i noticed, i'm replacing 'overscroll_edge' and 'overscroll_glow' (both framework-res package) in handleInitPackageResources while theoretically (according to the tutorials) it should be placed in initZygote
I did some more searching, think i might've found something. I'll keep you guys informed.
//edit: mehhh, im about to give up :/
Are your replacement 9 files 'built'?
PainToad said:
Are your replacement 9 files 'built'?
Click to expand...
Click to collapse
What exactly do you mean with 'built' ?
Also, even without the .9 files (by replacing it with a transparent 'newDrawable') it does not work :/

[Q] Retrieve HTTP POST/GET & Response

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

Gridview Display from SQLLITE DATABASE

Hi,
I would like to read data from my sqllite database. below my code but i am getting error . "Cannot resolve method maketext java.lang.exception,int)
Code:
package in.whomeninja.android_barcode_scanner;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ShowProduct extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showproduct);
GridView gvproduct=(GridView)findViewById(R.id.gvproduct);
List<String> li=new ArrayList<>();
ArrayAdapter<String> dataAdapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,li);
dataAdapter.setDropDownViewResource(R.layout.showproduct);
try {
SQLiteDatabase db=openOrCreateDatabase("coke_db",MODE_PRIVATE,null);
Cursor cr=db.rawQuery("SELECT * FROM PRODUCT_TBL",null);
if(cr!=null){
if(cr.moveToFirst()){
do{
String no=cr.getString(cr.getColumnIndex("barcodeResult"));
String name=cr.getString(cr.getColumnIndex("latitude_textview"));
String type=cr.getString(cr.getColumnIndex("longitude_textview"));
String qty=cr.getString(cr.getColumnIndex("textView1"));
String remark=cr.getString(cr.getColumnIndex("textView6"));
//li.add(no);
li.add(no);
li.add(name);
li.add(type);
li.add(qty);
li.add(remark);
gvproduct.setAdapter(dataAdapter);
}while (cr.moveToNext());
}else{
Toast.makeText(getApplicationContext(), "No Data to show", Toast.LENGTH_LONG).show();
}
}
}catch (Exception e){
Toast.makeText(ShowProduct.this, e, Toast.LENGTH_SHORT).show();
}
}
}

move service chat head with button

hello, im having trouble moving a chathead with a button, no matter how much i try it always crashes my app
here is the main activity
im using MoveHead but i dant make it to work
Code:
package example.com.chatheads;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.sip.SipAudioCall;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.Service;
import example.com.chatheads.ChatHeadService.*;
public class MainActivity extends Activity {
private final int xx = 500;
private final int yy = 500;
Button startService,stopService, moveService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
moveService=(Button)findViewById(R.id.moveService);
startService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getApplication(), ChatHeadService.class));
//startService(new Intent(getApplication(), HepUstte.class));
}
});
stopService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(getApplication(), ChatHeadService.class));
}
});
moveService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//System.out.println("Hello");
ChatHeadService inst = new ChatHeadService();
inst.UpdateEmployee();
}
});
}
and here is the chatheadservice class
Code:
package example.com.chatheads;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
public class ChatHeadService extends Service {
public WindowManager windowManager;
public ImageView chatHead;
WindowManager.LayoutParams params;
int xi ;
int yi ;
@Override
public void onCreate() {
super.onCreate();
System.out.println("Hello2");
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.face1);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
chatHead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
params.x = xi;
params.y = yi;
windowManager.updateViewLayout(chatHead, params);
}
});
windowManager.addView(chatHead, params);
}
public void MoveHead(){
System.out.println("Hello");
WindowManager.LayoutParams params = (WindowManager.LayoutParams) chatHead.getLayoutParams();
params.x = 100;
params.y = 300;
windowManager.updateViewLayout(chatHead, params);
}
@Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null)
windowManager.removeView(chatHead);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

class problem

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) {
}
});
}
}

Categories

Resources