Proper way to send e-mail in managed bean - jsf

I'm using this Java code to send messages in JSF page:
import com.web.utils.SendEmail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.mail.MessagingException;
import javax.servlet.http.Part;
#Named
#ViewScoped
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
private Part file;
private String name;
private String senderEmail;
private String telephone;
private String comment;
private String result;
public Contacts()
{
}
public void sendEmail() throws IOException, MessagingException
{
String[] to =
{
"test#gmail.com"
}; // list of recipient email addresses
String subject = name + " " + senderEmail + " " + telephone;
SendEmail mail = new SendEmail();
result = mail.intiSendEmail(to, subject, comment, file);
}
public void upload()
{
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSenderEmail()
{
return senderEmail;
}
public void setSenderEmail(String senderEmail)
{
this.senderEmail = senderEmail;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getComment()
{
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public String getResult()
{
return result;
}
public void setResult(String result)
{
this.result = result;
}
public Part getFile()
{
return file;
}
public void setFile(Part file)
{
this.file = file;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.Part;
public class SendEmail implements Serializable
{
private String USER_NAME = "test";
private String PASSWORD = "test!";
public String intiSendEmail(String[] to, String subject, String body, Part file) throws IOException, MessagingException
{
String status;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", USER_NAME);
props.put("mail.smtp.password", PASSWORD);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(USER_NAME));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++)
{
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++)
{
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
/**
* If file is not attached skip setting content
*/
if (file != null)
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
ByteArrayDataSource ds = new ByteArrayDataSource(file.getInputStream(), file.getContentType());
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
Transport transport = session.getTransport("smtp");
transport.connect(host, USER_NAME, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae)
{
ae.printStackTrace();
return status = "Cannot send Message!";
}
catch (MessagingException me)
{
me.printStackTrace();
return status = "Cannot send Message!";
}
return status = "Message is send!";
}
/**
* For testing
*/
public void upload()
{
Part file = null;
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
}
I added thread pool in order to speedup page performance. But I as you can see the code execution is not properly handled when package is redeployed. What it the proper way to stop Thread pool in JSF?

Related

getDeviceId: The user 10214 does not meet the requirements to access device identifiers

I am trying to modify this app. But for the first time I have to solve the permission problem which is not happening to me. I have pasted the code and the logcat. Please tell me a solution.
getDeviceId: The user 10214 does not meet the requirements to access
device identifiers
Splah
package com.xitij.spintoearn.Activity;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.facebook.ads.AudienceNetworkAds;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.R;
import com.xitij.spintoearn.Util.Constant;
import com.xitij.spintoearn.Util.Ex;
import com.xitij.spintoearn.Util.Method;
import com.xitij.spintoearn.Util.RestAPI;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class Splash extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
private Constant constant;
private String GetDeviceID(){
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = null;
int readIMEI= ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE);
if(deviceID == null) {
if (readIMEI == PackageManager.PERMISSION_GRANTED) {
deviceID = tm.getDeviceId().toString();
}
}
return deviceID;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AudienceNetworkAds.initialize(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Constant.DeviceID = GetDeviceID();
login(Constant.DeviceID);
//Toast.makeText(Splash.this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
finish();
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.RECORD_AUDIO)
.check();
constant = new Constant(Splash.this);
Constant.DeviceID = GetDeviceID();
Ex.getIPaddress();
if(Ex.isConnectionEnable(this) && Ex.checkAndRequestPermissions(this,this)){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//login(Constant.DeviceID);
}
},SPLASH_TIME_OUT);
}
}
public void login(final String deviceid) {
String login = RestAPI.API_Device_Login + "&deviceid=" + deviceid;
AsyncHttpClient client = new AsyncHttpClient();
client.get(login, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String success = object.getString("success");
if (success.equals("1")) {
String user_id = object.getString("user_id");
String name = object.getString("name");
String sendEmail = object.getString("email");
String userPhone = object.getString("phone");
String userCode = object.getString("user_code");
constant.sharedEditor.putBoolean(constant.isLogin, true);
constant.sharedEditor.putString(constant.profileId, user_id);
constant.sharedEditor.putString(constant.userName, name);
constant.sharedEditor.putString(constant.userEmail, sendEmail);
constant.sharedEditor.putString(constant.userPhone, userPhone);
constant.sharedEditor.putString(constant.userCode, userCode);
constant.sharedEditor.commit();
LoadSettings();
Constant.user =new User("00",name,sendEmail,"000",userPhone,userCode);
Method.UserLoginLogs(user_id,"Login",Constant.DeviceID);
Intent intent=new Intent(getBaseContext(),MainActivity.class);
startActivity(intent);
finish();
} else {
Intent inst = new Intent(Splash.this, Login.class);
inst.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inst);
finish();
// Ex.okAlertBox(getResources().getString(R.string.login_failed_message));
//Toast.makeText(Login.this, getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Splash.this);
alertDialogBuilder.setTitle("Server Maintenance");
alertDialogBuilder.setMessage("System is Undergoing Maintenance. Please try again later.");
alertDialogBuilder.setPositiveButton(getApplication().getResources().getString(R.string.ok_message),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
public void LoadSettings() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(RestAPI.API_Settings, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response-ls", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String app_name = object.getString("app_name");
String app_logo = object.getString("app_logo");
String app_version = object.getString("app_version");
String app_author = object.getString("app_author");
String app_contact = object.getString("app_contact");
String app_email = object.getString("app_email");
String app_website = object.getString("app_website");
String app_description = object.getString("app_description");
String app_developed_by = object.getString("app_developed_by");
String app_faq = object.getString("app_faq");
String app_privacy_policy = object.getString("app_privacy_policy");
String publisher_id = object.getString("publisher_id");
boolean interstital_ad = Boolean.parseBoolean(object.getString("interstital_ad"));
String interstital_ad_id = object.getString("interstital_ad_id");
String interstital_ad_click = object.getString("interstital_ad_click");
boolean banner_ad = Boolean.parseBoolean(object.getString("banner_ad"));
String banner_ad_id = object.getString("banner_ad_id");
boolean rewarded_video_ads = Boolean.parseBoolean(object.getString("rewarded_video_ads"));
String rewarded_video_ads_id = object.getString("rewarded_video_ads_id");
String redeem_currency = object.getString("redeem_currency");
String redeem_points = object.getString("redeem_points");
String redeem_money = object.getString("redeem_money");
String minimum_redeem_points = object.getString("minimum_redeem_points");
String payment_method1 = object.getString("payment_method1");
String payment_method2 = object.getString("payment_method2");
String payment_method3 = object.getString("payment_method3");
String payment_method4 = object.getString("payment_method4");
String daily_spin_limit = object.getString("daily_spin_limit");
String ads_frequency_limit= object.getString("ads_frequency_limit");
String video_add_point= object.getString("video_add_point");
String app_refer_reward= object.getString("app_refer_reward");
String registration_reward= object.getString("registration_reward");
String video_ads_limit= object.getString("daily_rewarded_video_ads_limits");
Constant.settings = new Settings(app_name, app_logo, app_version, app_author, app_contact, app_email, app_website, app_description, app_developed_by,
app_faq, app_privacy_policy, publisher_id, interstital_ad_id, interstital_ad_click, banner_ad_id, rewarded_video_ads_id, redeem_currency, redeem_points,
redeem_money, minimum_redeem_points, payment_method1, payment_method2, payment_method3, payment_method4, interstital_ad, banner_ad, rewarded_video_ads,daily_spin_limit,ads_frequency_limit,video_add_point,app_refer_reward,registration_reward,video_ads_limit);
Log.d("Response-ls",ads_frequency_limit );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
Constant
package com.xitij.spintoearn.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import com.xitij.spintoearn.Models.CoinHistory;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.SpinCounter;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.Models.UserBalance;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.reward.RewardedVideoAd;
public class Constant {
public static final String AppSid="spin";
public static final int POINT_VIDEO_MIN=1;
public static final int POINT_VIDEO_MAX=100;
public static final int RATE_POINT=1000;
public static final int DAILY_CHECK=100;
public static String Total_Point;
//Enter milliseconds
public static final int Waitsecond=8000;
public static String PublicIP;
public static String DeviceID;
public static final String ReferPoint = "10";
public static final String VIDEO_AD_ID="ca-app-pub-3940256099942544/8691691433";
public static final String INSTE_AD_ID="ca-app-pub-3940256099942544/1033173712";
public static final String AD_ID= "#";
public static int AD_COUNT = 0;
public static int VIDEO_AD_COUNT= 0;
public static InterstitialAd mInterstitial;
public static RewardedVideoAd mRewardedVideoAd;
public static User user;
public static UserBalance userBalance;
public static CoinHistory coinHistory;
public static Settings settings;
public static SpinCounter spinCounter;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor sharedEditor;
private Activity activity;
private final String loginPerfm = "login";
public String isLogin = "isLogin";
private String deviceId = "deviceId";
public String profileId = "profileId";
public String userEmail = "userEmail";
public String userPassword = "userPassword";
public String userName = "userName";
public String userPhone = "userPhone";
public String userCode = "userCode";
public String Spin_Count = "Spin_Count";
#SuppressLint("CommitPrefEdits")
public Constant(Activity activity) {
this.activity = activity;
sharedPreferences = activity.getSharedPreferences(loginPerfm, 0); // 0 - for private mode
sharedEditor = sharedPreferences.edit();
}
}
logcat
2021-03-08 08:05:02.525 14296-14296/? E/itij.spintoear: Unknown bits set in runtime_flags: 0x8000
2021-03-08 08:05:04.622 14296-14296/com.xitij.spintoearn E/fdsan: attempted to close file descriptor 74, expected to be unowned, actually owned by FILE* 0x76c3b37018
2021-03-08 08:05:04.758 14296-14296/com.xitij.spintoearn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xitij.spintoearn, PID: 14296
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xitij.spintoearn/com.xitij.spintoearn.Activity.Splash}: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.os.Parcel.createException(Parcel.java:2071)
at android.os.Parcel.readException(Parcel.java:2039)
at android.os.Parcel.readException(Parcel.java:1987)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:10389)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:1620)
at com.xitij.spintoearn.Activity.Splash.GetDeviceID(Splash.java:53)
at com.xitij.spintoearn.Activity.Splash.onCreate(Splash.java:99)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3378)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:264) 
at android.app.ActivityThread.main(ActivityThread.java:7581) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980) 

How to select particular textfile

Using Apache POI to parse text documents and search for keywords inside them
I just simply create resume parser that parse each document(.doc, .docx) to find given keywords in folder or in sub-folder. Please read the Java-Doc of HWPFDocument.
Here is code
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
public class ResumeParser {
HWPFDocument document;
FileInputStream fileInputStream;
String rootFolderPath;
Map<String, List<String>> displayContent = new HashMap<String, List<String>>();
List<String> keywordList;
public ResumeParser(String rootFolderPath, List<String> keywordList) throws IOException {
this.rootFolderPath = rootFolderPath;
this.keywordList = keywordList;
startParsing();
}
public void startParsing() throws IOException {
createDisplayContent(rootFolderPath);
printContent(displayContent);
}
/**
* Creates the display content it parse the each file under given folder and
* also in sub folder. folder
*
* #param rootFolderPath
* the root folder path
*/
public void createDisplayContent(String rootFolderPath) {
File fileL = new File(rootFolderPath);
File[] fileArrL = fileL.listFiles();
for (int i = 0; i < fileArrL.length; i++) {
File fileTempL = fileArrL[i];
if (fileTempL.isFile()) {
String name = fileTempL.getName();
String extension = name.substring(name.indexOf('.') + 1, name.length()).toUpperCase();
if (extension.equals("DOC") || extension.equals("DOCX")) {
parseDocFile(fileTempL.getAbsolutePath());
}
} else if (fileTempL.isDirectory()) {
createDisplayContent(fileTempL.getAbsolutePath());
}
}
}
public void parseDocFile(String filePath) {
try {
fileInputStream = new FileInputStream(filePath);
document = new HWPFDocument(fileInputStream);
String text = document.getText().toString().toUpperCase();
Iterator<String> iteratorL = keywordList.iterator();
List<String> matchKeywordListL = new ArrayList<String>();
String keywordL = "";
while (iteratorL.hasNext()) {
keywordL = iteratorL.next().toUpperCase();
if (text.contains(keywordL)) {
matchKeywordListL.add(keywordL.toLowerCase());
}
}
displayContent.put(filePath, matchKeywordListL);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void printContent(Map<String, List<String>> displayContent) {
Iterator<String> iteratorL = displayContent.keySet().iterator();
String keyL = "";
while (iteratorL.hasNext()) {
keyL = iteratorL.next();
System.out.println("File Name: " + keyL + " Match Keywords: " + displayContent.get(keyL));
}
}
public static void main(String args[]) throws IOException {
List<String> keywordListL = new ArrayList<String>();
keywordListL.add("Java");
keywordListL.add("PHP");
keywordListL.add("Andriod");
keywordListL.add("John");
new ResumeParser("D:\\Doc", keywordListL);
}
}

Read text file and display it in Jtable?

i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.
My Text File: File Name(people.txt)
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
Names VARCHAR(500) NO
Address VARCHAR(500) NO
My Code So Far:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
static public void main(String[] arg){
JScrollPane scroll;
JTable table;
DefaultTableModel model;
String fname="people";
try
{
FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine,str = null;
//Read File Line By Line
String text = "";
Vector myVector = new Vector();
while ((strLine = br.readLine()) != null) //loop through each line
{
myVector.add(strLine );
// Print the content on the console
text +=(strLine+"\n"); // Store the text file in the string
}
in.close();//Close the input stream
int i=0;
String fline=myVector.elementAt(0).toString();
String[] sp=fline.split("\\s+");
for(String spt:sp){
System.out.println(spt);
//model = new DefaultTableModel(spt, ); // I dont know how to put the strings
into Jtable here
table = new JTable(){
public boolean isCellEditable(int row, int column){
return false;
}
};
int a=0;// for text box name
for(i=1;i<myVector.size();i++){
str=myVector.elementAt(i).toString();
String[] res =str.split("\\s+");
int k=0;
for(String st:res)
System.out.println(st);
k++;a++; }
} }
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thank You.
File Content: (Each attribute is separated by a semicolon and each line is a record.)
Hello1;123
World1;234
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class FileToJTable {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new FileToJTable().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
try {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable();
String readLine = null;
StudentTableModel tableModel = new StudentTableModel();
File file = new File(""/*Give your File Path here*/);
FileReader reader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(reader);
List<Student> studentList = new ArrayList<Student>();
while((readLine = bufReader.readLine()) != null) {
String[] splitData = readLine.split(";");
Student student = new Student();
student.setName(splitData[0]);
student.setNumber(splitData[1]);
studentList.add(student);
}
tableModel.setList(studentList);
table.setModel(tableModel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setTitle("File to JTable");
frame.pack();
frame.setVisible(true);
} catch(IOException ex) {}
}
class Student {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
class StudentTableModel extends AbstractTableModel {
private List<Student> list = new ArrayList<Student>();
private String[] columnNames = {"Name", "Number"};
public void setList(List<Student> list) {
this.list = list;
fireTableDataChanged();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return list.get(rowIndex).getName();
case 1:
return list.get(rowIndex).getNumber();
default:
return null;
}
}
}
}
Well i didnt read ur code...however i'm telling u one of the simplest way of doing this...hope this helps
Define a DefaultTableModel:
String columns[] = { //Column Names// };
JTable contactTable = new JTable();
DefaultTableModel tableModel;
// specify number of columns
tableModel = new DefaultTableModel(0,2);
tableModel.setColumnIdentifiers(columns);
contactTable.setModel(tableModel);
Reading from text file:
String line;
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null)
{
tableModel.addRow(line.split(", "));
}
reader.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
Also, if you want to allow users to edit the data, then you need to set a TableCellEditor on the cells that you want people to edit. You probably also want to start using a TableModel instead of hard coding the data in the JTable itself.
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

how to convert thread to multi thread?

I want to the following code to convert the thread to newFixedThreadpool()
how do I do it?
//saddddddddddddddddddddddddddddffgfggggggggggggggggggggggggfdhfdhfdhdhdfhjhljgjhgdadsadsafds
class client :
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.lang.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
String fileName = null;
try {
fileName = args[0];
} catch (Exception e) {
System.out.println("Enter the name of the file :");
Scanner scanner = new Scanner(System.in);
String file_name = scanner.nextLine();
File file = new File(file_name);
Socket socket = new Socket("localhost", 3332);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[Server.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
System.exit(0);
}
}
}
class server:
import java.io.FileOutputStream;
import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 100;
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(new File("/home/reza/Desktop/reza"));
} else {
throwException("Something is wrong");
}
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[])o;
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println("File transfer success");
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}
public class Server extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
new ServerWorker(s).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerWorker extends Thread {
private Socket _socket;
public ServerWorker(Socket socket) {
this._socket = socket;
}
public void run() {
saveFile(this._socket);
// Thread should terminate when run returns.
}
private void saveFile(Socket socket) throws Exception {
...
}
}

Pass String from thread to UI for display

I am new to android and java programming. I am try to write a program to read data via bluetooth.
I trying to pass a String apple which I decipher from my bluetooth input data from my thread to my UI for display CalibrationActivity.
I am using handler for the passing.
I keep getting force quit. Can anyone please advice me how can I solve this problem.
Below is my entire code of my extend Thread.
package com.android.backend.data.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.android.AutoActivity;
import com.android.CalibrationActivity;
import com.android.ui.UIManager;
public class Connection extends Thread {
final Connection tt = this;
private final String TAG = "Connection"; // Class name for logging
public boolean connected = false;
public BluetoothSocket bSocket = null;
public InputStream mmInStream = null;
public OutputStream mmOutStream = null;
public ArrayList<String> message = new ArrayList<String>();
public BluetoothDevice currentDevice = null;
public UIManager mgr;
public boolean connectFailure = false;
public boolean stopAutoConnect = false;
public String type = null;
public AutoActivity ff;
public void bsocketcancel() {
try {
bSocket.close();
} catch (IOException e) { }
}
public Connection(UIManager mgr, BluetoothDevice device, String message,
String type) {
this.mgr = mgr;
currentDevice = device;
this.message.add(message);
this.type = type;
}
public Connection(UIManager mgr, BluetoothDevice device, ArrayList<String> message,
String type) {
this.mgr = mgr;
currentDevice = device;
this.message = message;
this.type = type;
}
#Override
public void run() {
if (type.compareToIgnoreCase("Manual") == 0) {
Log.d("thread", "manual");
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
if(connected){
mgr.connectedDialog();
System.out.println("Maunal connected");
}
Log.d("thread", "hideprogressBox");
if (!connected)
mgr.showConnectionErrBox();
}
if (type.compareToIgnoreCase("auto") == 0){
Log.d("thread", "auto");
stopConnection();
int i = 0;
while (true) { //Set to 5 second
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
Log.d("thread", "hideprogressBox");
if (!connected) {
mgr.connecting();
}
if (connected) {
mgr.connectedDialog();
bsocketcancel();
System.out.println("Auto connected");
//BluetoothManager.getInstance().disconnectAll(); // cut all connection after transmit
break;
}
if(stopAutoConnect){
mgr.cancelconnecting();
break;
}
}
}
if (type.compareToIgnoreCase("calibrate") == 0) {
Log.d("thread", "calibrate");
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
if(connected){
mgr.connectedDialog();
mgr.msgsent();
System.out.println("Calibration connected");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String apple = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
apple = apple + "_" + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
apple = apple + new String(buffer, 0, bytes -1);
System.out.println("message " + apple);
//pass data to UI CalibrationActivity
System.out.println("message out " + apple);
Message msga = mhandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", apple);
msga.setData(bundle);
mhandler.sendMessage(msga);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
Log.d("thread", "hideprogressBox");
if (!connected){
mgr.showConnectionErrBox();
}
}
}
public void connect(BluetoothDevice device) {
currentDevice = device;
BluetoothSocket tmp = null;
BluetoothManager.getInstance().getBluetoothAdapter().cancelDiscovery();
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
// tmp = device
// .createRfcommSocketToServiceRecord(BluetoothManager.SerialPortServiceClass_UUID);
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, 1);
// } catch (IOException e) {
// Log.e(TAG, "create() failed", e);
// return;
} catch (Exception e) {
Log.e(TAG, "Socket connection failed", e);
return;
}
bSocket = tmp;
try {
bSocket.connect();
} catch (IOException e1) {
Log.e(TAG, "Connection err", e1);
connectFailure = true;
return;
}
if (tmp != null) {
// Get Input/output stream for Socket
try {
mmInStream = bSocket.getInputStream();
mmOutStream = bSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
return;
}
}
connected = true;
connectFailure = false;
}
private Handler mhandler;
public void read(){
Log.i(TAG, "Read is running");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String a = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
a = a + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
a = a + new String(buffer, 0, bytes -1);
System.out.println("message " + a);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
public void write(byte[] buffer) {
if (mmOutStream != null) {
try {
mmOutStream.write(buffer);
Log.d(TAG, "Message Sent");
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
} else {
//mgr.showConnectionErrBox();
}
}
public void stopConnection() {
try {
if(bSocket != null)
bSocket.close();
Log.e(TAG, "Connection closed");
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
public BluetoothDevice getCurrentDevice() {
return currentDevice;
}
public void setCurrentDevice(BluetoothDevice currentDevice) {
this.currentDevice = currentDevice;
}
public ArrayList<String> getMessage() {
return message;
}
public void setMessage(ArrayList<String> message) {
this.message = message;
}
}
Below is the affect portion
if(connected){
mgr.connectedDialog();
mgr.msgsent();
System.out.println("Calibration connected");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String apple = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
apple = apple + "_" + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
apple = apple + new String(buffer, 0, bytes -1);
System.out.println("message " + apple);
//pass data to UI CalibrationActivity
System.out.println("message out " + apple);
Message msga = mhandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", apple);
msga.setData(bundle);
mhandler.sendMessage(msga);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
Below is the code for my Calibration Activity
package com.android;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import com.android.SimpleGestureFilter.SimpleGestureListener;
import com.android.backend.data.Playlist;
import com.android.backend.data.PlaylistManager;
import com.android.backend.data.SwitchBar;
import com.android.backend.data.bluetooth.BluetoothManager;
import com.android.backend.data.bluetooth.Connection;
import com.android.ui.UIManager;
import com.android.ui.playlist.PlaylistEntryList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
//public class CalibrationActivity extends Activity{
public class CalibrationActivity extends Activity implements SimpleGestureListener{
String gotBread;
public void handleMessage(Message msg)
{ switch(msg.what){
case 2:
Bundle got = getIntent().getExtras();
gotBread = got.getString("key");
TextView aa = (TextView) this.findViewById(R.id.stringinput);
aa.setText(gotBread);
break;
}
}
private SimpleGestureFilter detector;
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
// TODO Auto-generated method stub
//final MainActivity tt = this;
String str = "";
switch (direction) {
//case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
case SimpleGestureFilter.SWIPE_RIGHT : this.finish();
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
//Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
//Do Nothing for now future development
}
private PlaylistManager playlistMgr;
private PlaylistEntryList playlistView; // Data for listview, stores current
// playlist in memory
public String createdNameList; // Indicated the name of currently Name of
// playlist that is being created
public Dialog dialog_customizePL, dialog_createPL, dialog_customizePLms; // Dialog boxes for
// Playlist creation
public UIManager uiMgr = new UIManager();
public String CONNECTED_DEVICE_MAC;
public String dialogboxtext;
public Connection Conn;
int i = 0;
protected void onPause() {
super.onPause();
//BluetoothManager.getInstance().disconnectAll();
unregisterReceiver(mRvcau); //Sequence is important
System.exit(0); // Kill off all thread to prevent connectiong lost popup
// I use system because is a calibration so I want user not to leave the activity else cannot calibrate
}
protected void onResume() { //restart bluetooth is accidently off it
super.onResume();
BluetoothManager.getInstance().init();
BluetoothManager.getInstance().getBluetoothAdapter().enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); // IntentFilter class is important to declare for below filter
registerReceiver(mRvcau,filter); // mRvcau is the location of logic, filter is message identify by android
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); // Future deveploment
registerReceiver(mRvcau,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); // Future deveploment
registerReceiver(mRvcau,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); // Future deveploment
registerReceiver(mRvcau,filter);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remotedevicecalibration);
detector = new SimpleGestureFilter(this,this); ////////////////// For Gesture
playlistMgr = PlaylistManager.getInstance();
initUI();
uiMgr.initPlayListUI(this);
}
int connect = 0; // Check connection
int disconnect = 0; // Check disconnection
int requestdisconnect = 0;
int connectstatuschanges = 0;
public BroadcastReceiver mRvcau = new BroadcastReceiver(){ // The new is instantiate the class **always read from the back
// The line from the back is creating an instantiate of this class
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//AutoActivity.this.finish();
connect = 1; // prevent activity from exiting
System.out.println("ACTION_ACL_CONNECTED " + connect);
}
else
{
connect = 0;
System.out.println("ACTION_ACL_CONNECTED " + connect);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { //future development
disconnect = 1;
System.out.println("ACTION_ACL_DISCONNECTED " + disconnect);
}
else
{
disconnect = 0;
System.out.println("ACTION_ACL_DISCONNECTED " + disconnect);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { //future development
requestdisconnect = 1;
System.out.println("ACTION_ACL_DISCONNECT_REQUESTED " + requestdisconnect);
}
else
{
requestdisconnect = 0;
System.out.println("ACTION_ACL_DISCONNECT_REQUESTED " + requestdisconnect);
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { //future development
connectstatuschanges = 1;
System.out.println("ACTION_BOND_STATE_CHANGED " + connectstatuschanges);
}
else
{
connectstatuschanges = 0;
System.out.println("ACTION_BOND_STATE_CHANGED " + connectstatuschanges);
}
}
};
/**
* Init layout component. Define Listener for Buttons and Dataset for
* ListViews
*/
#SuppressLint("ParserError")
public void initUI() {
Button Orange = (Button) findViewById(R.id.CalibrationOrange); // new method on test using image
Orange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(20);
}
});
Button Blue = (Button) findViewById(R.id.CalibrationBlue); // new method on test using image icon to on the switch
Blue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(21);
}
});
Button Green = (Button) findViewById(R.id.CalibrationGreen); // new method on test using image icon to on the switch
Green.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(22);
}
});
loadDataToMem();
}
public void activiteSingleConnection(int i) {
BluetoothManager btMgr = BluetoothManager.getInstance();
BluetoothDevice device = btMgr.getBluetoothAdapter().getRemoteDevice(
CONNECTED_DEVICE_MAC);
ArrayList<String> msg = new ArrayList<String>();
if(i == 20){
msg.add("N");
}
if(i == 21){
msg.add("J");
}
if(i == 22){
msg.add("I");
}
CharSequence fruit = null;
TextView aa = (TextView) this.findViewById(R.id.stringinput);
aa.setText(fruit);
btMgr.calibratesentMessage(uiMgr, device, msg);
}
public void loadDataToMem() {
try {
String str = "";
//StringBuffer buf = new StringBuffer();
FileInputStream input = this.openFileInput("bone.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(
input));
if (input != null) {
while ((str = reader.readLine()) != null) {
String[] buff = str.split(",");
TextView topView = (TextView) this
.findViewById(R.id.remotedevicecalibrationtextview1);
TextView bottomView = (TextView) this
.findViewById(R.id.remotedevicecalibrationtextView2);
topView.setText("Name : " + buff[0]);
bottomView.setText("Mac : " + buff[2]);
this.CONNECTED_DEVICE_MAC = buff[2];
Log.d("loadDataToMem", str);
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below are my log cat error message
09-13 10:50:33.640: W/dalvikvm(2086): threadid=9: thread exiting with uncaught exception (group=0x40015560)
09-13 10:50:33.667: E/AndroidRuntime(2086): FATAL EXCEPTION: Thread-10
09-13 10:50:33.667: E/AndroidRuntime(2086): java.lang.NullPointerException
09-13 10:50:33.667: E/AndroidRuntime(2086): at com.android.backend.data.bluetooth.Connection.run(Connection.java:196)
Hope someone can advice me how to solve. Thank You.

Resources