How to execute FB client on different Android devices? - java

I have a naive problem, but I confused: I have made application which uses Facebook SDK, and it works good on my device and emulator, and it doesn't work on customer's device. He doesn't get any error or exceptions - when he press button for authorize he will see "loading" message, but progress bar will be closed, and authorization will be canceled. What problem is it? Thank you for anything hints
private void submitExec() {
/* if (SQLiteDbWrapper.getInstance().getBookCount()==0) {
Toast.makeText(this, "A list of books is empty", Toast.LENGTH_LONG).show();
return;
}*/
SQLiteDbWrapper.getInstance().makeFacebook(this, this.getApplicationContext());
if (SQLiteDbWrapper.getInstance().getConnector().getFacebook().isSessionValid()) {
//new SubmitClass().execute();
}
else {
SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
#Override
public void onAuthSucceed() {
//MyBookDroidActivity.this.executeSubmitClass();
}
#Override
public void onAuthFail(String error) {
}
};
SessionEvents.addAuthListener(listener);
SQLiteDbWrapper.getInstance().getConnector().login();
}
}
It is function for authorizating.
public void makeFacebook(Activity activity, Context context) {
if (mConnector==null||!mConnector.getFacebook().isSessionValid()) {
mConnector=new FacebookConnector(FACEBOOK_APPID, activity, context,
new String[] {"publish_stream", "read_stream", "email"});
}
}
It is function for making FacebookConnector.

Try adding logging:
public void appendLog(String text)
{
File logFile = new File("sdcard/log.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If you can't run some kind of LogCat or collect the stacktrace on the device yourself, you may want to look into:
http://code.google.com/p/microlog4android/

Related

How to determine if the print job completed?

In my Android app, I'm trying to print a PDF document, and everything is working fine, here is my current snippet for printing the file
private void printFile(){
PrintManager printManager = (PrintManager) this.getSystemService(getApplicationContext().PRINT_SERVICE);
PrintDocumentAdapter pda = new PrintDocumentAdapter(){
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
OutputStream output = null;
try {
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = _responseBody;
output.write(buf);
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
}
#Override
public void onFinish(){
System.out.println("PRINT IS FINISHED");
}
};
PrintAttributes printAttrs = new PrintAttributes.Builder().
setMediaSize(PrintAttributes.MediaSize.ISO_A6).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PrintJob printJob = printManager.print(labelID, pda, printAttrs);
}
But when the print is completed I want to run a method for going back to a previous view of the app, so I need to catch the event it fires when the print job is completed, can somebody explain how to do it or any code snippet will be greatly appreciated.
I agree with CommonsWare comment, print job can take a long time and in some cases may stay in "blocked" state indefinitely.
For the record, the onFinish() callback should work in normal print success cases.

How to leave the program successfully

Today I write a program.It works successfully and is almost finished.But I found when I close the Socket,BufferedReaderandPrintWriter,the program always shows ANR.I feel confused about that.Is there any sequence to close the program??
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
try {
mPrintWriter.println("192.168.2.131;"+mSocket.getLocalAddress().toString().replace("/", "")+";byebye");
mPrintWriter.close();
mBufferedReader.close();
mSocket.close();
net_.interrupt(); //This is the thread to send and receive data.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my question and I want to eliminate this bug to keep my program perfect.Thanks
Read this Android - how do I investigate an ANR?
And maybe try something like that
#Override
public void onClick(DialogInterface dialog, int which) {
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
mPrintWriter.println("192.168.2.131;"+mSocket.getLocalAddress().toString().replace("/", "")+";byebye");
} catch (IOException e) {
e.printStackTrace();
} finally{
mPrintWriter.close();
mBufferedReader.close();
}
try{
net_.interrupt();
}catch (IOException e) {
e.printStackTrace();
}finally{
mSocket.close();
}
}
});
thread .start();
}
And at the end of your app you should join that thread
thread.join();

android- setAdapter on AlertDialog not working

I am making a list of the user's tumblr blogs in a pop-box. All of this happens within a Handler. Here is the code:
private class PicHandler extends Handler{
Context c;
String name;
JumblrClient client;
public PicHandler(Context context, String n, JumblrClient cl){
c=context;
name = n;
client = cl;
}
public void handleMessage(Message msg)
{
final String[] cs = preferences.getString("allBlogs", "").split(",");
for (String s : cs){
Log.d("DrawLog", s); //logs the blogs correctly
}
ListAdapter adapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_selectable_list_item, cs);
Log.d("DrawLog", (String) adapter.getItem(0)); //logs the first blog correctlys
new AlertDialog.Builder(c)
.setTitle("Choose blog")
.setMessage("Choose the blog to publish the .gif")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File( root_sd + "/Flippy/" + name) ;
if(file.exists()){
Log.d("DrawLog", "file exists"); //file exists
Log.d("DrawLog", file.getPath());
}
PhotoPost post;
try {
post = client.newPost(cs[which], PhotoPost.class);
//Photo p = new Photo();
post.setData(file);
Log.d("DrawLog" , post.toString()+"");
post.save();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(NullPointerException e){
Log.d("DrawLog", "null pointer wtf");
}
}
}).create().show();
}
}
All the logs log the right things... It's just when the alert displays there is no list. Any ideas why?
You can either use setMessage() or setAdapter(). They are mutually exclusive. If you use both, the message wins. A solution would be to remove setMessage() and use setTitle() instead.

NetworkOnMainThreadException- Have tried making a new Thread and also ASynchTask

I've been trying to get this to work for a while. I'm trying to send a message from my phone to a simple server on my laptop. I keep getting the NetworkOnMainThreadException, I've tried making a new Thread(new Runnable() etc. and an ASynchTask but I am still getting the error and the app is force closing. I have read through 3 or 4 of the questions similar to this but none have worked for me. Here is my code:
final Button post2 = (Button) findViewById(R.id.postbutton2);
post2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
// TODO Auto-generated method stub
#Override
public void run() {
// TODO Auto-generated method stub
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
try {
clientSocket = new Socket("10.0.0.2", 4445);
printWriter = new PrintWriter(clientSocket
.getOutputStream(), true);
printWriter.write(message);
printWriter.flush();
printWriter.close();
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}).start();
}
});
try removing the following part from your code.
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
It does not look right to do this in this thread.
You must do YourActivity.this.runOnUiThread(new Runnable() { public void run() { /* show your toast here */ });

Working with delay in Java

I'm trying to create a speech recognition app where the app recieves voice and sends out stuff. I'd like everything that the onEndOfSpeech method to be called to wait a second and then do the entire voice recognition intent to start over again.
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
Not sure that I am doing this correctly.
Thanks!
This is how it should be
try {
Thread.sleep(3000);
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} catch (InterruptedException e) {
// it depends on your app logic what to do with InterruptedException, you can process it or rethrow or restore interrupted flag
}
Try this code
protected boolean _active = true;
// time to display the splash screen in ms
protected int _splashTime = 1000;
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
e.printStackTrace();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}

Categories