This is my main class
package FSM;
import java.io.IOException;
import FSM.view.PersonEditDetailsControler;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import FSM.model.Person;
import FSM.view.PersonOverviewController;
public class Main extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Person> personData= FXCollections.observableArrayList();
public Main() {
// Add some sample data
System.out.println("1 prit");
personData.add(new Person("Hans", "Muster"));
personData.add(new Person("Ruth", "Mueller"));
personData.add(new Person("Heinz", "Kurz"));
personData.add(new Person("Cornelia", "Meier"));
personData.add(new Person("Werner", "Meyer"));
personData.add(new Person("Lydia", "Kunz"));
personData.add(new Person("Anna", "Best"));
personData.add(new Person("Stefan", "Meier"));
personData.add(new Person("Martin", "Mueller"));
}
public ObservableList<Person> getPersonData() {
return personData;
}
#Override
public void start(Stage primaryStage) throws Exception{
System.out.println("2 print");
this.primaryStage = primaryStage;
primaryStage.setTitle("AddressApp");
initRootLayout();
showPersonOverview();
}
public void initRootLayout() {
try {
// Load root layout from fxml file.
System.out.println("rootLayout");
FXMLLoader loader = new FXMLLoader();
System.out.println("geting rootlayout");
loader.setLocation(Main.class.getResource("/FSM/view/RootLayout.fxml"));
System.out.println("setting borderPane");
rootLayout = (BorderPane) loader.load();
System.out.println("loaded");
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
System.out.println("new scene 1");
primaryStage.setScene(scene);
System.out.println("set scene");
primaryStage.show();
System.out.println("rootLayout End 1");
} catch (IOException e) {
System.out.println("rootLayout Exception");
e.printStackTrace();
}
}
public void showPersonOverview() {
try {
System.out.println("3 Print");
// Load person overview.
FXMLLoader loader = new FXMLLoader();
System.out.println("getting Resouurce");
loader.setLocation(Main.class.getResource("/FSM/view/PersonOverview.fxml"));
System.out.println("got Resouurce");
AnchorPane personOverview = (AnchorPane) loader.load();
System.out.println("loading Anchor");
// Set person overview into the center of root layout.
rootLayout.setCenter(personOverview);
System.out.println("setting person overview");
PersonOverviewController controller = loader.getController();
controller.setMain(this);
} catch (IOException e) {
e.printStackTrace();
System.out.println("3 Print exception");
}
}
public boolean showPersonEditDialog(Person person){
try {
System.out.println("4 print");
FXMLLoader loader=new FXMLLoader();
loader.setLocation(Main.class.getResource("/FSM/view/PersonEditDetails.fxml"));
AnchorPane anchorPane=(AnchorPane)loader.load();
rootLayout.setCenter(anchorPane);
Stage dialogStage = new Stage();
dialogStage.setTitle("Edit Person");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(anchorPane);
dialogStage.setScene(scene);
PersonEditDetailsControler controllerr = loader.getController();
controllerr.setDialogStage(dialogStage);
controllerr.setPerson(person);
dialogStage.showAndWait();
return controllerr.isOKClicked();
}catch (Exception e){
e.printStackTrace();
System.out.println("4th print");
return false;
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
And this is PersonOverViewController class
package FSM.view;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import FSM.model.Person;
import FSM.Main;
import javafx.scene.web.WebEvent;
import java.lang.Object.*;
/**
* Created by mfaseem on 6/9/2015.
*/
public class PersonOverviewController {
#FXML
private TableView<Person> PersonTable;
#FXML
private TableColumn<Person,String> fnameColumn;
#FXML
private TableColumn<Person, String> lnameColumn;
#FXML
private Label fnameLabel;
#FXML
private Label lnameLabel;
#FXML
private Label streetLabel;
#FXML
private Label postelCodeLabel;
#FXML
private Label CityLabel;
#FXML
private Label dobLabel;
private Main main;
public PersonOverviewController(){
}
#FXML
private void initialize(){
fnameColumn.setCellValueFactory(CellData -> CellData.getValue().fnameProperties());
lnameColumn.setCellValueFactory(CellData -> CellData.getValue().lnameProperties());
showPersonDetails(null);
PersonTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) ->showPersonDetails(newValue));
}
#FXML
private void deleteHandler(){
int selectedIndex=PersonTable.getSelectionModel().getSelectedIndex();
if(selectedIndex>=0){
PersonTable.getItems().remove(selectedIndex);
}else {
// ALERT alert = new Alert(AlertType.WARNING);
//alert.initOwner(mainApp.getPrimaryStage());
// alert.setTitle("No Selection");
// alert.setHeaderText("No Person Selected");
// alert.setContentText("Please select a person in the table.");
// alert.showAndWait();
}
}
#FXML
private void handleNewPerson() {
Person tempPerson = new Person();
boolean okClicked = main.showPersonEditDialog(tempPerson);
if (okClicked) {
main.getPersonData().add(tempPerson);
}
}
#FXML
private void handleEditPerson() {
Person selectedPerson = PersonTable.getSelectionModel().getSelectedItem();
if (selectedPerson != null) {
boolean okClicked = main.showPersonEditDialog(selectedPerson);
if (okClicked) {
showPersonDetails(selectedPerson);
}
} else {
/* Nothing selected.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No Person Selected");
alert.setContentText("Please select a person in the table.");
alert.showAndWait();
*/
}
}
public void setMain(Main main){
this.main=main;
PersonTable.setItems(main.getPersonData());
}
private void showPersonDetails(Person person){
if(person !=null){
fnameLabel.setText(person.getFname());
lnameLabel.setText(person.getLname());
streetLabel.setText(person.getStreet());
CityLabel.setText(person.getCity());
dobLabel.setText(person.getBirthDate().toString());
postelCodeLabel.setText(String.valueOf(person.getPostalCode()));
}else{
fnameLabel.setText("");
lnameLabel.setText("");
streetLabel.setText("");
CityLabel.setText("");
dobLabel.setText("");
postelCodeLabel.setText("");
}
}
}
And the out put is
Device "Intel(R) Q45/Q43 Express Chipset" (\\.\DISPLAY1) initialization failed :
WARNING: bad driver version detected, device disabled. Please update your driver to at least version 8.15.10.2302
1 prit
2 print
rootLayout
geting rootlayout
setting borderPane
loaded
new scene 1
set scene
javafx.fxml.LoadException: /C:/Users/mfaseem/IdeaProjects/AddressApp/out/production/AddressApp/FSM/view/PersonOverview.fxml:7
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:104)
Can any one help me thanks in advance
Related
I have a list application what uses Recyclerview. All line have an checkbox, 2pcs TextView and a button. These are declarated in the RecyclerView class.
The application has got an other class what handles the data for example SharedPreferences, and calculations and so on...
How is it possible that I reach the objects what are in RecyclerView from the other class.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public TextView myTextView, subtext;
public Button add;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
myTextView.setText(meta_data);
subtext.setText(meta_subdata +" "+ meta_subdata2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done =itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
and Here is the list class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
adapter.done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.done.isChecked()) Toast.makeText(ToDoList.this,"Something is done",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(View view, int position) {
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
String item_click =adapter.getItem(position);
String[] itemarray = item_click.split(" ",0);
myEdit = sharedPreferences.edit();
myEdit.remove(itemarray[0]);
myEdit.commit();
adapter.notifyItemRemoved(position);
items.remove(item_click);
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
The first attemption was that the objects were declarated in the ViewHolder class, but I can not reach that from the list class.
I put the objects to the RecyclerView class and now I can reach thoose because for example the adapter.done.setOnClickListener() is valid from Android Studio point of view, but I always got null object reference. I think I know why, because the layout xml what the list class uses haven't got checkbox item, but then I don't know how can I solve this.
I also try to inflate the RecyclerView layout:
final View view = mInflater.inflate(R.layout.recyclerview_row,null);
...
...
...
adapter.done = view.findViewById(R.id.done);
but then I got LayoutInflater null object reference exception.
I started to wrote app that gets input from the user (in edittext) and after pressing button it should pass the valued to another activity in custom listview.
I found a problem during the debugging that the arraylist in the adapter getting null or 0.
Here is the Adapter code and main activity.
I hope someone could help me with this issue.
Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class exampleAdapter extends RecyclerView.Adapter<exampleAdapter.ExampleViewHolder> {
private ArrayList<exampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewLine1;
public TextView mTextViewLine2;
public ImageView imageView;
public ExampleViewHolder(View itemView) {
super(itemView);
mTextViewLine1 = itemView.findViewById(R.id.textview_line1);
mTextViewLine2 = itemView.findViewById(R.id.textview_line2);
imageView = itemView.findViewById(R.id.icond);
}
}
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
this.notifyDataSetChanged();
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
exampleItem currentItem = mExampleList.get(position);
holder.mTextViewLine1.setText(currentItem.getLine1());
holder.mTextViewLine2.setText(currentItem.getLine2());
if (currentItem.getLineimg().equalsIgnoreCase("s")) {
holder.imageView.setImageResource(R.drawable.salary);
}
if (currentItem.getLineimg().equalsIgnoreCase("e")){
holder.imageView.setImageResource(R.drawable.money);
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
MainActivity2
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setInsertButton();
loadData();
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences4", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list4", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences4", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list4", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ);
final EditText lineimg = findViewById(R.id.summ);
final EditText line2 = findViewById(R.id.date2);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
insertItem(lin1, lin2, lin3);
saveData();
finish();
}
private void insertItem(String toString, String toString1, String toString2) {
mExampleList.add(new exampleItem(toString, toString2, toString1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
}
});
}
}
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<exampleItem> mExampleList = new ArrayList<>();
RecyclerView mRecyclerView;
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState1) {
super.onCreate(savedInstanceState1);
setContentView(R.layout.activity_main);
findViewById(R.id.buttoni).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
Bring out the inserItem method as separate from onClickListener and try out
private void insertItem(String toString, String toString1, String toString2) {
mExampleList.add(new exampleItem(toString, toString2, toString1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
}
you can remove this.notifydatachange() from adapter constructor
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
this.notifyDataSetChanged();
}
I am stuck when learning handlers. The following is my simple code:
public class MainActivity extends AppCompatActivity {
Thread thread;
public Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
thread = new Thread(new MyThread());
thread.start();
handler=new Handler() {
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
};
}
class MyThread implements Runnable{
#Override
public void run(){
Message message=Message.obtain();
for(int i=0;i<10000;i++){
handler.sendMessage(message);
}
}
}
}
In the MyThread class, i was trying to type sendMessage after handler. but android studio does not show any such sendMessage option. still i typed it, then it shows in red. and says cannot resolve method.
You have imported wrong handler class
import java.util.logging.Handler;
And sendMessage method does not belong to this class
Try this import android.os.Handler;
Example:
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
Thread thread;
Handler handler;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar) findViewById(R.id.progressbar1);
thread = new Thread(new MyThread());
thread.start();
handler = new Handler() {
public void handleMessage(Message msg) {
progressbar.setProgress(msg.arg1);
};
};
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();
}
});
}
class MyThread implements Runnable {
#Override
public void run() {
Message message = Message.obtain();
Log.d("message", "" + message);
for (int i = 0; i < 100; i++) {
message.arg1 = i;
handler.sendMessage(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Good day, i really need help because this is now a big headache. the code looks fine but when i click on the subscribe button, the app will crash.
this is my android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.generalsteinacoz.realmqttclient" >
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MQTTService"/>
</application>
</manifest>
this is the code for the main Activity (i.e UI)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.generalsteinacoz.realmqttclient.MQTTService;
public class FirstActivity extends Activity {
EditText edt_host, edt_port, editTopicSub;
TextView txt_message;
Button btnSub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
edt_host = (EditText) findViewById(R.id.edt_host);
edt_port = (EditText) findViewById(R.id.edt_port);
editTopicSub = (EditText) findViewById(R.id.edt_sub);
btnSub = (Button) findViewById(R.id.btnSave_sub);
txt_message = (TextView) findViewById(R.id.txt_messageBody);
onClick_Btn_Sub();
}
public void getMessage(String mess){
txt_message.setText(mess);
}
public String setTopic(){
String mainTopic = editTopicSub.getText().toString();
return mainTopic;
}
public String setbrokerPort(){
String mainBrokerPort = edt_host.getText()+":"+ edt_port.getText().toString();
return mainBrokerPort;
}
public void onClick_Btn_Sub(){
btnSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent("MQTTService"));
}
});
}
#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_first, 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);
}
}
this is the code for the service class
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import com.example.generalsteinacoz.realmqttclient.FirstActivity;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MQTTService extends Service {
FirstActivity fa = new FirstActivity();
private static final String TAG = "MQTTService";
private static boolean hasWifi = false;
private static boolean hasMmobile = false;
private Thread thread;
private ConnectivityManager mConnMan;
private volatile IMqttAsyncClient mqttClient;
private String deviceId;
class MQTTBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
IMqttToken token;
boolean hasConnectivity = false;
boolean hasChanged = false;
NetworkInfo infos[] = mConnMan.getAllNetworkInfo();
for (int i = 0; i < infos.length; i++){
if (infos[i].getTypeName().equalsIgnoreCase("MOBILE")){
if((infos[i].isConnected() != hasMmobile)){
hasChanged = true;
hasMmobile = infos[i].isConnected();
}
Log.d(TAG, infos[i].getTypeName() + " is " + infos[i].isConnected());
} else if ( infos[i].getTypeName().equalsIgnoreCase("WIFI") ){
if((infos[i].isConnected() != hasWifi)){
hasChanged = true;
hasWifi = infos[i].isConnected();
}
Log.d(TAG, infos[i].getTypeName() + " is " + infos[i].isConnected());
}
}
hasConnectivity = hasMmobile || hasWifi;
Log.v(TAG, "hasConn: " + hasConnectivity + " hasChange: " + hasChanged + " - "+(mqttClient == null || !mqttClient.isConnected()));
if (hasConnectivity && hasChanged && (mqttClient == null || !mqttClient.isConnected())) {
doConnect();
} else if (!hasConnectivity && mqttClient != null && mqttClient.isConnected()) {
Log.d(TAG, "doDisconnect()");
try {
token = mqttClient.disconnect();
token.waitForCompletion(1000);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
};
public class MQTTBinder extends Binder {
public MQTTService getService(){
return MQTTService.this;
}
}
#Override
public void onCreate() {
IntentFilter intentf = new IntentFilter();
setClientID();
intentf.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new MQTTBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "onConfigurationChanged()");
android.os.Debug.waitForDebugger();
super.onConfigurationChanged(newConfig);
}
private void setClientID(){
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
deviceId = wInfo.getMacAddress();
if(deviceId == null){
deviceId = MqttAsyncClient.generateClientId();
}
}
private void doConnect(){
Log.d(TAG, "doConnect()");
IMqttToken token;
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
try {
// mqttClient = new MqttAsyncClient(fa.setbrokerPort(), deviceId, new MemoryPersistence());
mqttClient = new MqttAsyncClient("tcp://iot.eclipse.org:1883", deviceId, new MemoryPersistence());
token = mqttClient.connect();
token.waitForCompletion(3500);
mqttClient.setCallback(new MqttEventCallback());
token = mqttClient.subscribe("#", 0);
//token = mqttClient.subscribe(fa.setTopic(), 0);
token.waitForCompletion(5000);
} catch (MqttSecurityException e) {
e.printStackTrace();
} catch (MqttException e) {
switch (e.getReasonCode()) {
case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
case MqttException.REASON_CODE_CLIENT_TIMEOUT:
case MqttException.REASON_CODE_CONNECTION_LOST:
case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
Log.v(TAG, "c" +e.getMessage());
e.printStackTrace();
break;
case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
Intent i = new Intent("RAISEALLARM");
i.putExtra("ALLARM", e);
Log.e(TAG, "b"+ e.getMessage());
break;
default:
Log.e(TAG, "a" + e.getMessage());
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand()");
return START_STICKY;
}
private class MqttEventCallback implements MqttCallback {
#Override
public void connectionLost(Throwable arg0) {
}
#Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
}
#Override
#SuppressLint("NewApi")
public void messageArrived(String topic, final MqttMessage msg) throws Exception {
Log.i(TAG, "Message arrived from topic" + topic);
Handler h = new Handler(getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Intent launchA = new Intent(MQTTService.this, FirstActivity.class);
launchA.putExtra("message", msg.getPayload());
//TODO write somethinkg that has some sense
if(Build.VERSION.SDK_INT >= 11){
launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_F RONT|Intent.FLAG_ACTIVITY_NO_ANIMATION);
} /*else {
launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}*/
startActivity(launchA);
Toast.makeText(getApplicationContext(), "MQTT Message:\n" + new String(msg.getPayload()), Toast.LENGTH_SHORT).show();
fa.getMessage(msg.getPayload().toString());
}
});
}
}
public String getThread(){
return Long.valueOf(thread.getId()).toString();
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind called");
return null;
}
}
I have made a Simple drawing application in android for the learning purpose..In that i have taken diffrent colorbuttons just like a colorpicker in horizontalscrollview,Now i need is when one of them is clicked that particular color should be chosen and pencolor od drawing pen should be changed..I have tried as below,but its not working..Please help me for the same,Thanx in advance...!
main.java
public void onClick(View v) {
switch (v.getId()) {
case R.id.black:
myplate.setVisibility(View.GONE);
mDrawView.setColor(SingleTouchView.DrawingColors.Black);
break;
case R.id.blue:
myplate.setVisibility(View.GONE);
mDrawView.setColor(SingleTouchView.DrawingColors.Blue);
break;
...so on...for other colors
MyView.java
package com.example.singletouch;
import java.util.AbstractMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import android.R.color;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;
public class SingleTouchView extends View {
public static int width;
public int height;
public Bitmap mBitmap;
public Canvas mCanvas;
public Path mPath;
public Paint mBitmapPaint;
Context context;
public Paint mPaint;
public Paint circlePaint;
public Path circlePath;
public enum DrawingPens {
PEN_1(6), PEN_2(4), PEN_3(2), PEN_4(1);
public Paint mPaint;
private DrawingPens(final int width) {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(width);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
}
Paint getPaint() {
return mPaint;
}
}
public enum DrawingColors{
Black(Color.parseColor("#000000")),Blue(Color.parseColor("#0000FF")),Cofee(Color.parseColor("#D2691E")),Cyan(Color.parseColor("#00FFFF"))
,Fuchiya(Color.parseColor("#FF00FF")),Gray(Color.parseColor("#808080")),Green(Color.parseColor("#00FF00")),Indigo(Color.parseColor("#4B0082")),
Khaki(Color.parseColor("#F0E68C")),Lavendar(Color.parseColor("#E6E6FA")),Magenta(Color.parseColor("#FF00FF")),Mango(Color.parseColor("#FF8C00"))
,Maroon(Color.parseColor("#800000")),Orange(Color.parseColor("#FFA500")),Pink(Color.parseColor("#FFC0CB")),Pista(Color.parseColor("#9ACD32")),
Purple(Color.parseColor("#800080")),Red(Color.parseColor("#FF0000")),Tan(Color.parseColor("#0000A0")),Yellow(Color.parseColor("#FFD801"));
public Paint mPaint;
private DrawingColors(final int color) {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(width);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
}
Paint getPaint() {
return mPaint;
}
}
public SingleTouchView(final Context context) {
super(context);
init(context);
}
public SingleTouchView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context);
mBitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
}
public SingleTouchView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>> mPaths = new ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>>();
private ConcurrentLinkedQueue<Map.Entry<Path, DrawingColors>> mPaths1 = new ConcurrentLinkedQueue<Map.Entry<Path, DrawingColors>>();
private Path mCurrentPath;
private void init(final Context context) {
setPen(DrawingPens.PEN_1);
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Map.Entry<Path, DrawingPens> entry : mPaths) {
canvas.drawPath(entry.getKey(), entry.getValue().getPaint());
}
}
#Override
public boolean onTouchEvent(MotionEvent me) {
float eventX = me.getX();
float eventY = me.getY();
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
mCurrentPath.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
mCurrentPath.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
break;
}
invalidate();
return true;
}
public void setPen(final DrawingPens pen) {
mCurrentPath = new Path();
mPaths.add(new AbstractMap.SimpleImmutableEntry<Path, DrawingPens>(
mCurrentPath, pen));
}
public void eraser() {
// TODO Auto-generated method stub
mPaint = new Paint();
/* Toast.makeText(getContext(), "eraser", Toast.LENGTH_LONG).show();
mPaint.setXfermode(null);
mPaint.setAlpha(0x00FFFFFF);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));*/
// invalidate();
}
public void setColor(final DrawingColors color ) {
mCurrentPath = new Path();
mPaths1.add(new AbstractMap.SimpleImmutableEntry<Path, DrawingColors>(
mCurrentPath, color));
}
}
Please help me friends..please...
still a bit unclear but I will try to give you a direction. What happens if you try the below onDraw method? I have a feeling you have not set the colors. The code is a bit messy and not clear to read. Don't worry for now about the performance, creating a new paint every time, just want to make sure it give's you the wanted result.
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
for (Map.Entry<Path, DrawingPens> entry : mPaths) {
canvas.drawPath(entry.getKey(), paint);
}
}