'How to open a activity when a Qr code is scan?
I'm developing an Android application using Android Studio and Java. In this app I implemented a Qr code scanner using Scannercode. I have a qr code containing a url. When this specific url is scanned, I would like my application to automatically open another activity. Is it something possible? I tried this code but my application is crashing whenever a qr code is scan.
CameraFragment.java
public class CameraFragment extends Fragment {
String contents;
private CodeScanner mCodeScanner;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
final Activity activity = getActivity();
View root = inflater.inflate(R.layout.fragment_camera, container, false);
CodeScannerView scannerView = root.findViewById(R.id.scanner_view);
mCodeScanner = new CodeScanner(activity, scannerView);
mCodeScanner.setDecodeCallback(new DecodeCallback() {
@Override
public void onDecoded(@NonNull final Result result) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(Patterns.WEB_URL.matcher(result.getText()).equals("https://youtu.be/M2c")) {
startActivity(new Intent(getContext(), MilleActivity.class));
}
}
});
}
});
scannerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCodeScanner.startPreview();
}
});
return root;
}
@Override
public void onResume() {
super.onResume();
mCodeScanner.startPreview();
}
@Override
public void onPause() {
mCodeScanner.releaseResources();
super.onPause();
}
}
Solution 1:[1]
Why not? What seems to be the problem? In which file is your scan result located/ do you have access to the Context?
As normal just use
Intent intent = new Intent(MyActivity.this, StartThisActivity.class);
startActivity(intent);
Solution 2:[2]
Swing is not thread and is single threaded.
This means that you should not update the UI (or some state the UI depends on) from outside the context of the Event Dispatching Thread and you should not perform any long running or blocking operations from within the context of the EDT.
Start by having a look at Concurrency in Swing for more details.
Once solution might be to use a SwingWorker. This allows you to perform long running or blocking operations within the context of their own threads, but provides a simple way to signal to the UI that changes have occurred safely. See Worker Threads and SwingWorker for more details.
The following is a VERY basic example. It's self contained, so the the code can act as either the client or server. This is tied to localhost, so you will need to run two instances locally.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private ReadMessageWorker readWorker;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private ServerSocket serverSocket;
private Socket socket;
private JTextField messageField;
private JTextArea messageArea;
private JButton startServerButton;
private JButton startClientButton;
private JButton shutDownButton;
public TestPane() {
setLayout(new BorderLayout());
messageField = new JTextField(10);
messageArea = new JTextArea(10, 20);
messageField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String text = messageField.getText();
outputStream.writeUTF(text);
appendMessage(text);
messageField.setText(null);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(TestPane.this, "Could not send message", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
add(new JScrollPane(messageArea));
add(messageField, BorderLayout.NORTH);
startServerButton = new JButton("Start server");
startClientButton = new JButton("Start client");
shutDownButton = new JButton("Shutdown");
shutDownButton.setEnabled(false);
JPanel actionsPanel = new JPanel();
actionsPanel.add(startServerButton);
actionsPanel.add(startClientButton);
actionsPanel.add(shutDownButton);
add(actionsPanel, BorderLayout.SOUTH);
startServerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
createServer();
}
}).start();
}
});
startClientButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
createClient();
}
}).start();
}
});
shutDownButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shutdown();
}
});
}
protected void didStartServer() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
didStartServer();
}
});
return;
}
startServerButton.setEnabled(false);
startClientButton.setEnabled(false);
shutDownButton.setEnabled(true);
}
protected void didStartClient() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
didStartClient();
}
});
return;
}
startServerButton.setEnabled(false);
startClientButton.setEnabled(false);
shutDownButton.setEnabled(true);
}
protected void didShutdown() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
didShutdown();
}
});
return;
}
startServerButton.setEnabled(true);
startClientButton.setEnabled(true);
shutDownButton.setEnabled(false);
}
protected void createClient() {
try {
didStartClient();
appendMessage("Connecting to server");
socket = new Socket("localhost", 8080);
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
appendMessage("Connected to server\n");
createMessageWorker();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "Could not create client socket", "Error", JOptionPane.ERROR_MESSAGE);
}
}
protected void createServer() {
try {
didStartServer();
appendMessage("Starting server");
serverSocket = new ServerSocket(8080);
appendMessage("Waiting for client");
Socket socket = serverSocket.accept();
appendMessage("Client connected client\n");
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
createMessageWorker();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "Could not create server socket", "Error", JOptionPane.ERROR_MESSAGE);
}
}
protected void createMessageWorker() {
readWorker = new ReadMessageWorker(inputStream, new ReadMessageWorker.MessageListener() {
@Override
public void didRecieveMessage(String message) {
appendMessage(message);
}
});
readWorker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(readWorker.getState());
if (readWorker.getState() == SwingWorker.StateValue.DONE) {
try {
readWorker.get();
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(TestPane.this, "Stopped reading due to error", "Error", JOptionPane.ERROR_MESSAGE);
}
shutdown();
}
}
});
readWorker.execute();
}
protected void appendMessage(String message) {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
appendMessage(message);
}
});
return;
}
messageArea.append(message + "\n");
}
protected void shutdown() {
shutdownServer();
shutdownSocket();
appendMessage("\nShutdown completed\n");
didShutdown();
}
protected void shutdownSocket() {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
}
}
}
protected void shutdownServer() {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
}
}
}
}
public class ReadMessageWorker extends SwingWorker<Void, String> {
public interface MessageListener {
public void didRecieveMessage(String message);
}
private DataInputStream dataInputStream;
private AtomicBoolean continueReading;
private MessageListener listener;
public ReadMessageWorker(DataInputStream dataInputStream, MessageListener listener) {
this.dataInputStream = dataInputStream;
this.listener = listener;
continueReading = new AtomicBoolean(true);
}
@Override
protected void process(List<String> chunks) {
for (String message : chunks) {
listener.didRecieveMessage(message);
}
}
public void stopReading() {
continueReading.set(false);
try {
dataInputStream.close();
} catch (IOException ex) {
}
}
@Override
protected Void doInBackground() throws Exception {
while (continueReading.get()) {
String text = dataInputStream.readUTF();
publish(text);
}
System.out.println("Read is now down...");
return null;
}
}
}
Further enhancements might include setting up two SwingWorkers, one acting as the server and one acting as the client. This would encapsulate the functionality of the createXxx methods.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S_i_l_e_n_t C_o_d_e_r |
| Solution 2 | MadProgrammer |
