MailJava in a new Thread - multithreading

I try to get emails from csv file and start mailing process. Everything works fine if I do it in the main thread. But if I start a new thread and try to do it threre it gives me NullPointer on this line:
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
For some reason it cannot get a list of emails.
Full code is here:
package com.company;
import javax.mail.MessagingException;
import javax.swing.*;
import static com.company.MainFormAppearance.mailingSubject;
import static com.company.MainFormAppearance.mailingText;
public class NewThead implements Runnable {
public JTextArea jTextAreaStatus;
public Reader readerEmail;
private boolean doStop = false;
public synchronized void doStop() {
this.doStop = true;
}
private synchronized boolean keepRunning() {
return this.doStop == false;
}
#Override
public void run() {
while (keepRunning()){
Email email = new Email();
try {
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
} catch (MessagingException e) {
e.printStackTrace();
}
}
jTextAreaStatus.setText("completed");
}
}
Main class:
public class MainFormAppearance {
private JTextArea jTextAreaText;
private JTextArea jTextAreaSubject;
private JTextArea jTextAreaEmail;
private JTextArea jTextAreaStatus;
private JLabel blueLabel;
private JLabel copyRightLabel;
public JButton parceButton;
private JButton mailButton;
private JButton stopButton;
private String FILE_PATH_TEXT = "c:/Users/R2D2/Desktop/Main.txt";
private String FILE_PATH_SUBJECT = "c:/Users/R2D2/Desktop/Subject.txt";
public String CsvEmailsPath = "C:\\Users\\R2D2\\Desktop\\Emailstest.csv";
public String CsvBusinessesPath = "C:\\Users\\R2D2\\Desktop\\Businessestest.csv";
public static String mailingText = null;
public static String mailingSubject = null;
public Reader readerEmail;
public Reader readerBusiness;
public JPanel createContentPanel() {
JPanel totalGui = new JPanel();
totalGui.setLayout(null);
totalGui.setBackground(new Color(72, 209, 204));
jTextAreaText = new JTextArea();
jTextAreaSubject = new JTextArea();
jTextAreaEmail = new JTextArea();
jTextAreaStatus = new JTextArea();
blueLabel = new JLabel("Java Mailing Program");
copyRightLabel = new JLabel("\u00a9" + " Alex B - 2018");
parceButton = new JButton("Upload");
mailButton = new JButton("!Start!");
stopButton = new JButton("Stop");
readerEmail = new Reader();
readerBusiness = new Reader();
NewThead newThead = new NewThead();
Thread thread = new Thread(newThead);
//set program label
copyRightLabel.setLocation(10, 230);
copyRightLabel.setSize(400, 20);
copyRightLabel.setFont(new Font("Courier New", Font.ITALIC, 12));
copyRightLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(copyRightLabel);
//set program label
blueLabel.setLocation(10, 10);
blueLabel.setSize(400, 20);
blueLabel.setFont(new Font("Courier New", Font.ITALIC, 15));
blueLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(blueLabel);
//set Button 1 and click
parceButton.setLocation(270, 50);
parceButton.setSize(100, 30);
totalGui.add(parceButton);
parceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//parce data from files to Strings
mailingText = readLineByLineJava8(FILE_PATH_TEXT);
mailingSubject = readLineByLineJava8(FILE_PATH_SUBJECT);
try {
readerEmail.readCsvFile(CsvEmailsPath);
readerBusiness.readCsvFile(CsvBusinessesPath);
} catch (IOException e1) {
e1.printStackTrace();
}
if (isNullOrEmpty(mailingText)) {
jTextAreaText.setText("Text is empty! Check it!!!");
} else {
jTextAreaText.setText("***Text is Ready***");
}
if (isNullOrEmpty(mailingSubject)) {
jTextAreaSubject.setText("Subject is empty! Check it!!!");
} else {
jTextAreaSubject.setText("***Subject is Ready***");
}
}
});
//set Button 2 and click
mailButton.setLocation(270, 100);
mailButton.setSize(100, 30);
totalGui.add(mailButton);
mailButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
newThead.doStop();
jTextAreaStatus.setText("Stopped");
}
});
stopButton.setLocation(270, 150);
stopButton.setSize(100, 30);
totalGui.add(stopButton);
jTextAreaText.setLocation(20, 52);
jTextAreaText.setSize(200, 16);
jTextAreaText.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaText.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaText);
jTextAreaSubject.setLocation(20, 82);
jTextAreaSubject.setSize(200, 16);
jTextAreaSubject.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaSubject.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaSubject);
jTextAreaEmail.setLocation(20, 112);
jTextAreaEmail.setSize(200, 16);
jTextAreaEmail.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaEmail.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaEmail);
jTextAreaStatus.setLocation(20, 182);
jTextAreaStatus.setSize(200, 16);
jTextAreaStatus.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaStatus.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaStatus);
totalGui.setOpaque(true);
return totalGui;
}
public static boolean isNullOrEmpty(String str) {
if (str != null && !str.isEmpty())
return false;
return true;
}
}
Class that reads emails from csv (should be correct):
package com.company;
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Reader {
public CSVReader reader;
public LinkedList myList;
public void readCsvFile(String path) throws IOException {
try {
reader = new CSVReader(new FileReader(path));
String[] column;
myList = new LinkedList<>();
LinkedList <String> map;
while ((column = reader.readNext()) != null) {
map = new LinkedList<String>();
map.add(column[0]);
myList.add(String.valueOf(map).replace("[","").replace("]",""));
//myList.add(String.valueOf(map));
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why i do it in another thread? Because I want to have a chance to stopp mailing process by clicking in stop button and killing a new thread.

Related

Loading image from URL to ListView

I am trying to make a list view. I did it successfully without the photos loading from url without using a custom array adapter. However how can I implement loading images from url without using a custom array adapter?
I am trying to use the working codes from this thread but it is giving an error for holder.
Error Part
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
DoctorsActivity.java
public class DoctorsActivity extends AppCompatActivity {
private JSONArray arrayAdapter;
private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";
String cancel_req_tag = "login";
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctors);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_doctors);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_BALANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray contacts = jObj.getJSONArray("user");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String doctorTitle = c.getString("title");
String doctorName = c.getString("first_name");
String doctorSurname = c.getString("last_name");
String doctorPhoto = c.getString("photo"); //image URL
String doctorMobile = c.getString("mobile");
String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("photo", icon);
contact.put("doctor", doctorFullName);
contact.put("mobile", doctorMobile);
// adding contact to contact list
contactList.add(contact);
}
ListAdapter adapter = new SimpleAdapter(
DoctorsActivity.this, contactList,
R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
"mobile"}, new int[]{R.id.photo,
R.id.doctor, R.id.mobile});
lv.setAdapter(adapter);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", pid);
params.put("lang", Locale.getDefault().getDisplayLanguage());
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
}
Why not use a 3rd party lib like https://github.com/bumptech/glide?
Relevant code:
// ...
new Glide
.with(convertView.getContext())
.load(url)
.centerCrop()
.placeholder(R.drawable.noimage)
.crossFade()
.into(bmImage);
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
For everyone who wants to have listView with images this my corrected working Custom Adapter:
public class DoctorAdapter extends ArrayAdapter<Doctors>{
ArrayList<Doctors> doctorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
doctorList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.photo);
holder.tvName = (TextView) v.findViewById(R.id.doctor);
holder.tvMobile = (TextView) v.findViewById(R.id.mobile);
holder.callButton = (Button) v.findViewById(R.id.btnCall);
holder.callButton.setTag(holder);
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String message= viewHolder.tvMobile.getText().toString();
Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
}
});
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvMobile;
public Button callButton;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

Redisplaying recordstore into a LWUIT list after exit from app

I have written a LWUIT application that involves two RecordStores recordStore and
recordStore2.
Two methods method getRecordData for retrieving all records of recordStore, method getRecordData2 for retrieving all records of recordStore2. Two Radiobuttons rb and rb2 are added 'ButtonGroup' called group A.TextField called 'tf'.
Additionally, a button for adding a record for either recordstore or recordstore2 after rb or rb2 is selected; text which must written into tf TextField as a record
Two lists mylist and mylist2:
mylist to display all records of recordstore
mylist2 to display all records of recordstore2
All button to display all records of recordstore and recordstore2
Simple problem faces me:
After I exit from the application return back to it and press All button mylist and mylist2 are null (No record displayed)!
Example code:
import java.util.*;
import com.sun.lwuit.table.*;
import com.sun.lwuit.table.DefaultTableModel;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotOpenException;
import javax.microedition.rms .*;
import com.sun.lwuit.layouts.*;
import com.sun.lwuit.*;
import javax.microedition.lcdui.Canvas;
import com.sun.lwuit.events.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.geom.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
public class HelloLWUITMidlet3 extends MIDlet implements Runnable, ActionListener {
private RecordStore recordStore,recordStore2;
String team,team2;
public String [] getRecordData()
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
str = new String[recordStore.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public String [] getRecordData2()
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = recordStore2.enumerateRecords(null, null, false);
str = new String[recordStore2.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public void startApp()
{
com.sun.lwuit.Display.init(this);
int bgColor =0x0066CC;
final ButtonGroup group = new ButtonGroup();
final RadioButton rb = new RadioButton("First Team");
final RadioButton rb2 = new RadioButton("Second Team");
group.add(rb);
group.add(rb2);
//TableModel model = new DefaultTableModel(new String[]{"Column 1", "Column 2"});
final f1 g = new f1();
final com.sun.lwuit.List mylist = new com.sun.lwuit.List();
final com.sun.lwuit.List mylist2 = new com.sun.lwuit.List();
final form6 my = new form6();
final com.sun.lwuit.Form f = new com.sun.lwuit.Form("Football");
f.getStyle().setBgColor(0X99CCFF);
BoxLayout boxlayout =new BoxLayout(BoxLayout.X_AXIS);
// com.sun.lwuit.Command exitCommand = new com.sun.lwuit.Command("????");
final Button goals = new Button("See goals");
final Button button = new Button("Goals Record");
final com.sun.lwuit.TextField tf =new com.sun.lwuit.TextField();
final com.sun.lwuit.TextField txtfield5 =new com.sun.lwuit.TextField();
final com.sun.lwuit.TextField txtfield6 =new com.sun.lwuit.TextField();
final Button addition = new Button("Add Goals");
final Button All = new Button("All Goals");
addition.getStyle().setBgColor(0X0066CC);
com.sun.lwuit.Command back = new com.sun.lwuit.Command("Main_Screen");
final form6 ff = new form6();
button.getStyle().setBgColor(0X0066CC);
goals.getStyle().setBgColor(0X0066CC);
All.getStyle().setBgColor(0X0066CC);
Style g_style5 = g.getSelectedStyle() ;
f.addComponent(button);
ff.addCommand(back);
//g.addComponent(main_screen);
g.addComponent(tf);
g.addComponent(addition);
g.addComponent(rb);
g.addComponent(rb2);
g.addComponent(All);
g.getStyle().setBgColor(0X99CCFF);
g.addCommand(back);
g.addCommandListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
f.show();
}
}
);
ff.addCommandListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
f.show();
}
}
);
ff.getStyle().setBgColor(0X99CCFF);
try{
recordStore2 = RecordStore.openRecordStore("My Record Store2", true);
}
catch(Exception ex)
{ }
try
{
recordStore = RecordStore.openRecordStore("My Record Store", true);
}
catch(Exception ex)
{ }
All.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try
{
com.sun.lwuit.Label l = new com.sun.lwuit.Label("First Team Goals") ;
ff.addComponent(l);
String [] record= getRecordData();
int j1;
String valueToBeInserted2="";
for( j1=0;j1< getRecordData().length;j1++)
{
valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
if(j1==getRecordData().length)
{
mylist.addItem(record[j1]);
}
}
ff.addComponent(mylist);
com.sun.lwuit.Label ll = new com.sun.lwuit.Label("Second Team Goals") ;
ff.addComponent(ll);
String [] record2= getRecordData2();
int j2;
String valueToBeInserted="";
for( j1=0;j1< getRecordData().length;j1++)
{
valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
if(j1==getRecordData().length)
{
mylist.addItem(record[j1]);
}
}
ff.addComponent(mylist2);
}
catch(java.lang.IllegalArgumentException e){}
finally {
ff.show();
}
}
}
);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
g.show();
}
}
);
goals.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
}
}
);
final Thread th = new Thread(this);
addition.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
String s =tf.getText();
if(rb.isSelected())
{
if(s!=null && s.length() > 0)
{
try{
String kk =tf.getText();
mylist.addItem(kk);
byte bytestream[] = kk.getBytes() ;
int i = recordStore.addRecord(bytestream, 0, bytestream.length);
}
catch(Exception ex) { }
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("A new goal has been added"+"" );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}
}
else if (rb2.isSelected())
{
if(s!=null && s.length() > 0)
{
try{
String kk =tf.getText();
mylist2.addItem(kk);
byte bytestream[] = kk.getBytes() ;
int i = recordStore2.addRecord(bytestream, 0, bytestream.length);
}
catch(Exception ex) { }
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the al newert text here
textArea.setFocusable(false);
textArea.setText("A new Goal has been added"+"" );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}
}
else if((rb.isSelected()==false&&rb.isSelected()==false)||(s==null && s.length()<= 0))
{
Dialog validDialo = new Dialog(" ");
validDialo.setScrollable(false);
validDialo.getDialogStyle().setBgColor(0x0066CC);
validDialo.setTimeout(5000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("please enter scorer name and choose his team");
validDialo.addComponent(textArea);
//validDialo.getStyle().set3DText(true, true);
validDialo.show(50, 50, 50, 50, true);
txtfield6.clear();
}
}
}
);
f.show();
}
public void run ()
{
while(true)
{
String get[] = getRecordData();
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setTimeout(5000);
validDialog.setScrollable(true);
validDialog.setLayout(null);
validDialog.setTimeout(5000);
TextArea textArea = new TextArea( );
for(int ii=0;ii<getRecordData().length;ii++ )
{
textArea.setColumns(getRecordData().length);
validDialog.addComponent(textArea);
validDialog.show(10, 10, 10, 10, true);
System.out.println(get[ii]+"\n");
System.out.println(textArea.getColumns()+"\n");
}
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
notifyDestroyed();
}
public class f1 extends com.sun.lwuit.Form
{
com.sun.lwuit.TextField tf;
public f1()
{
com.sun.lwuit.Form f1 = new com.sun.lwuit.Form("Goals Records");
tf =new com.sun.lwuit.TextField();
}
}
public class form6 extends com.sun.lwuit.Form
{
com.sun.lwuit.TextField txtfield3;
com.sun.lwuit.TextField tf3;
public form6()
{
com.sun.lwuit.Form mylist = new com.sun.lwuit.Form("Goals List");
}
}
}

RecordControl with platformRequest could they work?

My goal is to produce an application that dial a phone number then record the conservation.
I have tested this code which record voice and then play it on my 5310 correctly.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VoiceRecordMidlet extends MIDlet {
private Display display;
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(new VoiceRecordForm());
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
}
class VoiceRecordForm extends Form implements CommandListener {
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.OK, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
System.getProperty("audio.encodings");
System.getProperty("supports.audio.capture");
System.getProperty("supports.recording");
t.start();
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/amr");
p2.prefetch();
p2.start();
}
catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
Thread t = new Thread() {
public void run() {
try {
System.getProperty("audio.encodings");
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
};
};
}
Then I made some changes in my code to record conservations
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VoiceRecordMidlet extends MIDlet {
private Display display;
Form f = new VoiceRecordForm();
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
class VoiceRecordForm extends Form implements CommandListener {
private MIDlet m;
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
private TextField phoneField;
private String n;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.SCREEN, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.phoneField =new TextField("number","",20,phoneField.PHONENUMBER);
append(phoneField);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
System.getProperty("audio.encodings");
System.getProperty("supports.audio.capture");
System.getProperty("supports.recording");
t.start();
try
{
n=phoneField.getString().trim();
platformRequest("tel:"+n);
}
catch(javax.microedition.io.ConnectionNotFoundException e)
{
e.printStackTrace();
}
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/amr");
p2.prefetch();
p2.start();
}
catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
Thread t = new Thread() {
public void run() {
try {
System.getProperty("audio.encodings");
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
};
};
}}
But when pressing record command following error getted
**Error: javax.microedition.media.MediaException: RecordControl**
Any help please?

Camera snapshot in J2ME Null Pointer Exception

I've spent long on this but no success yet. In my application to capture image and send to the server, I get NullPointerException below;
java.lang.NullPointerException: 0
at Files.CameraMIDlet.snap(CameraMIDlet.java:120)
at Files.CameraForm.commandAction(CameraForm.java:116)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=173
at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=78
at com.sun.midp.chameleon.CWindow.keyInput(), bci=38
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=17
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
The errors happen at byte[] image = videoControl.getSnapshot("encoding = jpeg"); in the CameraMIDlet and also at midlet.snap(); in the CameraForm, in the code below.
The code for CameraForm is here:
package Files;
import javax.microedition.media.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.control.*;
import java.io.IOException;
class CameraForm extends Form implements CommandListener {
private final CameraMIDlet midlet;
private final Command exitCommand;
private Command captureCommand = null;
private Command showImageCommand = null;
private Player player = null;
private static VideoControl videoControl = null;
private boolean active = false;
private StringItem messageItem;
public CameraForm(CameraMIDlet midlet) {
super("Camera");
this.midlet = midlet;
messageItem = new StringItem("Message", "start");
append(messageItem);
exitCommand = new Command("EXIT", Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
try {
//creates a new player and set it to realize
player = Manager.createPlayer("capture://video");
player.realize();
//Grap the Video control and set it to the current display
videoControl = (VideoControl) (player.getControl("VideoControl"));
if (videoControl != null) {
append((Item) (videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null)));
captureCommand = new Command("CAPTURE", Command.SCREEN, 1);
addCommand(captureCommand);
messageItem.setText("OK");
} else {
messageItem.setText("No video control");
}
} catch (IOException ioe) {
messageItem.setText("IOException: " + ioe.getMessage());
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
}
* the video should be visualized on the sreen
* therefore you have to start the player and set the videoControl visible
synchronized void start() {
if (!active) {
try {
if (player != null) {
player.start();
}
if (videoControl != null) {
videoControl.setVisible(true);
//midlet.snap();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
active = true;
}
}
* to stop the player. First the videoControl has to be set invisible
* than the player can be stopped
synchronized void stop() {
if (active) {
try {
if (videoControl != null) {
videoControl.setVisible(false);
}
if (player != null) {
player.stop();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
active = false;
}
}
* on the captureCommand a picture is taken and transmited to the server
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
midlet.cameraFormExit();
} else {
if (c == captureCommand) {
midlet.snap();
}
}
}
}
The code for CameraMIDlet is below:
package Files;
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.media.control.*;
import java.io.IOException;
import javax.microedition.media.MediaException;
public class CameraMIDlet extends MIDlet {
private CameraForm cameraSave = null;
private DisplayImage displayImage = null;
CameraForm captureThread;
private static VideoControl videoControl;
private StringItem messageItem;
public CameraMIDlet() {
}
/*
* startApp()
* starts the MIDlet and generates cameraSave, displayImage, database
*
**/
public void startApp() {
Displayable current = Display.getDisplay(this).getCurrent();
if (current == null) {
//first call
cameraSave = new CameraForm(this);
displayImage = new DisplayImage(this);
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
} else {
//returning from pauseApp
if (current == cameraSave) {
cameraSave.start();
}
Display.getDisplay(this).setCurrent(current);
}
}
public void pauseApp() {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
public void destroyApp(boolean unconditional) {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
private void exitRequested() {
destroyApp(false);
notifyDestroyed();
}
void cameraFormExit() {
exitRequested();
}
/**
* restart the camera again
*
*/
void displayCanvasBack() {
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
}
/**
* the byte[] of the image should be transmitted to a server
*
**/
void buildHTTPConnection(byte[] byteImage) {
displayImage.setImage(byteImage);
Display.getDisplay(this).setCurrent(displayImage);
HttpConnection hc = null;
OutputStream out = null;
try {
//enode the image data by the Base64 algorithm
String stringImage = Base64.encode(byteImage);
// URL of the Sevlet
String url = new String(
"http://ip-adress:8080/C:/Users/HASENDE/Documents/NetBeansProjects/Mobile/pics");
// Obtain an HTTPConnection
hc = (HttpConnection) Connector.open(url);
// Modifying the headers of the request
hc.setRequestMethod(HttpConnection.POST);
// Obtain the output stream for the HttpConnection
out = hc.openOutputStream();
out.write(stringImage.getBytes());
} catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
} finally {
try {
if (out != null)
out.close();
if (hc != null)
hc.close();
} catch (IOException ioe) {
}
}
// ** end network
}
/**
* stop the camera, show the captured image and transmit the image to a server
**/
void transmitImage(byte[] image) {
cameraSave.stop();
Display.getDisplay(this).setCurrent(displayImage);
buildHTTPConnection(image);
}
public void snap(){
try {
byte[] image = videoControl.getSnapshot("encoding = jpeg");
transmitImage(image);
messageItem.setText("Ok");
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
}
}
By identifying the statement that throws NPE you get 99% close to finding the bug:
byte[] image = videoControl.getSnapshot("encoding = jpeg");
NPE in above statement means videoControl is null. Now if you look at it closer, you may notice that in CameraMIDlet, videoControl is initialized with null and never changes to anything else - that's why you are getting NPE. By the way, from CameraForm code it looks like you intended to use videoControl object that is defined there, didn't you.
Side note. CameraForm seems to be designed to used in multiple threads (there are synchronized modifiers) - if this is the case, you better make sure that videoControl is also obtained from it in a synchronized way. Also in that case, add volatile modifier in definition of active flag:
private volatile boolean active = false; // in CameraForm
For Capturing photo use canvas instead of Form,
Check follwing code for Photo Capture
public class ImageCaptureCanvas extends Canvas {
UrMidlet midlet;
VideoControl videoControl;
Player player;
SnapShotCanvas snap;
private Display display;
public ImageCaptureCanvas(UrMidlet midlet) throws MediaException {
this.midlet = midlet;
this.display = Display.getDisplay(midlet);
this.setFullScreenMode(true);
try {
player = Manager.createPlayer("capture://image");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
} catch (Exception e) {
dm(e.getClass().getName());
}
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(0,0);
videoControl.setDisplaySize(getWidth(), getHeight());
} catch (MediaException me) {
try {
videoControl.setDisplayFullScreen(true);
} catch (MediaException me2) {
}
}
dm("icc10");
videoControl.setVisible(true);
dm("icc11");
player.start();
this.display.setCurrent(this);
}
public void dm(String message) {
Form form = new Form("Error");
form.append(message);
display.setCurrent(form);
}
public void paint(Graphics g) {
}
protected void keyPressed(int keyCode) {
boolean prv=false;
int actn=getGameAction(keyCode);
switch (keyCode) {
case KEY_NUM5:
prv=true;
Thread t = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t.start();
break;
}
if(!prv){
switch (actn) {
case Canvas.FIRE:
Thread t1 = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t1.start();
break;
}
}
}
}
SnapShotCanvas Code here
class SnapShotCanvas extends Canvas {
private Image image;
public SnapShotCanvas(Image image) {
this.image = image;
setFullScreenMode(true);
}
public void paint(Graphics g) {
g.drawImage(image, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
}
}

Fail to run the J2ME program after I appended the checkbox's index

Why the program is failed to run after I appended the checkbox's index.
agreeIndex = mainForm.append(agree);
import javax.microedition.midlet.*;
import java.util.*;
import javax.microedition.lcdui.*;
public class MainPage extends MIDlet implements CommandListener, ItemStateListener{
Ticker header;
Display display;
Form mainForm;
TextField name, num, phone, email, age;
ChoiceGroup gender;
private int choiceGroupIndex;
Command nextCom, clearCom, exitCom;
Page1 p1;
ChoiceGroup agree = new ChoiceGroup("Please read the terms and conditions from menu."
, Choice.MULTIPLE);
int agreeIndex;
public MainPage(){
header = new Ticker("**ABC Restraurant**Customer Survey**");
mainForm = new Form("Personal Information");
name = new TextField("User name: ", "", 20, TextField.ANY);
num = new TextField("User id: ", "", 10, TextField.NUMERIC);
phone = new TextField("Phone no.: ", "", 10, TextField.PHONENUMBER);
email = new TextField("E-mail: ", "", 20, TextField.ANY);
age = new TextField("Age: ", "", 3, TextField.NUMERIC);
gender = new ChoiceGroup("Gender: ", Choice.EXCLUSIVE);
nextCom = new Command("Next", Command.SCREEN, 1);
clearCom = new Command("Clear", Command.SCREEN, 2);
exitCom = new Command("Exit", Command.EXIT, 3);
p1 = new Page1(this);
mainForm.setTicker(header);
mainForm.append(name);
mainForm.append(num);
gender.append("Male", null);
gender.append("Female", null);
choiceGroupIndex = mainForm.append(gender);
mainForm.append(age);
mainForm.append(phone);
mainForm.append(email);
//agree.append("I agree with the terms and conditions.", null);
mainForm.append(agree);
mainForm.addCommand(nextCom);
mainForm.addCommand(clearCom);
mainForm.addCommand(exitCom);
mainForm.setCommandListener(this);
}
public void commandAction(Command c, Displayable s) {
if (c == exitCom)
{
try {
destroyApp(false);
} catch (MIDletStateChangeException e) {
e.printStackTrace();
}
notifyDestroyed();
} else if (c == clearCom) {
resetTransferInformation();
} else if (c == nextCom) {
display.setCurrent(p1.list);
//System.out.print(agreeIndex);
}
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
display.setCurrent(mainForm);
agree.append("I agree with the terms and conditions.", null);
agreeIndex = mainForm.append(agree);
}
public void itemStateChanged(Item item)
{
}
public void resetTransferInformation() {
name.setString("");
num.setString("");
phone.setString("");
email.setString("");
age.setString("");
}
public void back() {
display.setCurrent(mainForm);
}
}
You try to append agree to mainForm twice. (in constructor and in startApp)
It's incorrect

Resources