android- setAdapter on AlertDialog not working - java

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.

Related

trying to write to read and write to a text file in eclipse

I am trying to write and read to a text file name students but I am having all kinds of hassles I am very new to android programming so I am trying this out for the first time. I have looked at code here and there to try and figure out what I am doing wrong but I cant find one specific thing to help, this question has probably been asked a couple of times, so I am sorry for asking it again. Please see my different .xml and .java files below. The actual question is to be able to write data to a textfile and from the main screen click on a textfield which will take you to the edit screen, where you get to edit that specific field and save it to a text file (this however has not been done yet as I am still struggling to figure out why my writing and reading to the textfile is not working, I hope my poor attempt at coding will shed some light on the matter.
Please don't crucify me for my bad coding I am super new to android
/////////////////////////////add screen.java///////////////////////////////
public class AddNew extends Activity {
private static final String newLine = System.getProperty("line.separator");
TextView txtText;
EditText Modules;
EditText Types;
#Override
protected void onCreate(Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.add);
txtText = (TextView)findViewById(R.id.textView1);
Modules = (EditText)findViewById(R.id.etMod);
Types = (EditText)findViewById(R.id.etType);
Button backMan = (Button)findViewById(R.id.btnBackMain);
backMan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(AddNew.this, MainActivity.class));
}
}); //end back Button
//get the day, month & year from the Date picker
DatePicker myDPicker = (DatePicker)findViewById(R.id.dpDate);
Integer Year = myDPicker.getYear();
Integer Month = myDPicker.getMonth();
Integer Day = myDPicker.getDayOfMonth();
StringBuilder sb = new StringBuilder();
sb.append(Year.toString()).append("-").append(Month.toString()).append
("-").append(Day.toString());
final String dobStr=sb.toString();
txtText.setText("TEST");
Button Save = (Button)findViewById(R.id.btnSaveAdded);
Save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
try {
writeToFile(Modules.getText().toString(),
Types.getText().toString(),dobStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void writeToFile(String Mod, String AsType, String dobDate) throws
IOException {
// TODO Auto-generated method stub
//String textTofile;
StringBuilder sbText = new StringBuilder();
sbText.append(Mod + "," + dobStr + "," + AsType);
//textTofile=sbText.toString();
String fileName = "student";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName,
true));
printWriter.write(newLine ); //+textTofile);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
}); //end back Button
}
}
`public class MainActivity extends Activity {
TextView fDisplay;
TextView fTest;
int numItems=0; //use it later to keep track of the number of items.
String inText; //use this variable for the information read in from the textfile.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but1=(Button)findViewById(R.id.btnAdd);
but1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, AddNew.class));
}
}); //end but1
Button but2 = (Button)findViewById(R.id.btnEditCur);
but2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, EditCur.class));
}
}); //end of button 2
fDisplay = (TextView)findViewById(R.id.tvAssign1);
try {
readFromFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void readFromFile() throws IOException {
// TODO Auto-generated method stub
// String ret="";
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("student");
br = new BufferedReader(fr);
String line = br.readLine();
while (null != line) {
fDisplay.append(line);
fDisplay.append("\n");
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fr) {
try {
fr.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
`
For writting on a file I have used this
String filename;
String content;
filename = "PATH_AND_FILE";
content = "CONTENT ON THE FILE"
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write(myString.toString());
out.flush();
out.close();
And for reading I have this function:
public static String readFileAsString() {
String result = "";
String filename;
filename = "PATH_AND_FILE";
File file = new File(filename);
if ( file.exists() ) {
FileInputStream fis = null;
try { fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
// System.out.println("DEBUG Exception String :"+ e.toString());
} finally {
if (fis != null)
{ try {
fis.close();
} catch (IOException ignored) {
}}
else {// System.out.println("DEBUG Exception String NULL");
}
}
return result;
}
else
{
return "DEFAULT CONTENT";
}
}
In Android, the file' directory is different then that on a PC, like :the files are stored in a directory related to your App, the accessing permissions are different.
This link might be helpful:
How To Read/Write String From A File In Android
Two simple functions (Java) to read and write:
private static void writeToFile(String path, String text) {
PrintWriter writer;
try {
writer = new PrintWriter(path, "UTF-8");
writer.print(text);
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFileContent(String filename){
String everything = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
everything = sb.toString();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return everything;
}

VideoView Playing a file while it is received via socket

I have an App that is receiving a video file from another App that is working as a Server. While the App is saving the file received on the socket, the video stream starts playing the file (which is under construction). In the code sample, after I press the btnStream, I press the btnPlay and App runs successfully. However, if the playing rate is greater than the download rate, an error will occur. I want to avoid this case. So I need to have a listener on the Video Playing that will pause the videoview when it predicts that this error will occur. I know a solution where if I know the video size, I can counter the bytes received and monitor how many seconds have been buffered and see if the videoview should pause or not. However, is it possible to do it without knowing the video file size? Or having two threads that depends on each other? Thanks.
Note: the VideoView used is a custom one where it can play FileDescriptor.
btnStream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = etURL.getText().toString();
String ip = "10.0.0.24";
int port = 7878;
mct= new VideoDownloadTask(ip,port);
mct.execute();
}});
final MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(mVideoView);
Button btnPlay = (Button) findViewById(R.id.button2);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mVideoView.setVideoFD((new FileInputStream(new File("/sdcard/tempVideo.mp4")).getFD()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mVideoView.seekTo(0);
mVideoView.start();
}
});
}
public class VideoDownloadTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
Socket socket=null;
VideoDownloadTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(InetAddress.getByName(dstAddress), dstPort);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
if(socket!=null)socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
File f = new File("/sdcard/tempVideo.mp4");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in=null;
try {
in = new DataInputStream (socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream videoFile = null;
try {
videoFile = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int len;
byte buffer[] = new byte[8192];
try {
while((len = in.read(buffer)) != -1) {
videoFile.write(buffer, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
videoFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Done Downloading File",
Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
}
I applied a simple solution that resolved the problem. I am sharing it if anyone is having the same problem. The solution was simply to add an error listener to the videoView that will block the error popups and pauses the video.
mVideoView.setOnErrorListener(new OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
statusText.setText("ERROR PLAYING VIDEO");
mVideoView.pause();
return true;
}
});
pDialog = new ProgressDialog(PlayVideoActivity.this);
pDialog.setTitle("Gajacharitra");
pDialog.setMessage("Buffering video...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
try {
// Start the MediaController
mediacontroller.setAnchorView(mVideoView);
// Get the URL from String VideoURL
Uri video = Uri.parse(mVideoURL);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(video);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
mVideoView.pause();
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
return true;
}
});
} catch (Exception e) {
/*Log.e("Error", e.getMessage());
e.printStackTrace();*/
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
}

How to add Alertdialog to my Android app?

I want to add a Yes/No dialog box to my Android app, I tried the solution in this answer but I couldn't manage to make it work with my code, any help please?
This is my code in which I want to write a text from EditText.
public void buttonSelect( View v ) {
View view = null;
String mac1 = "mac1";
String mac2 = "mac2";
TextView tv1, tv2;
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
switch (v.getId()) {
case (R.id.Write_MAC1):
writeData(view, mac1); //I need to confirm writing the data
break;
case (R.id.Write_MAC2):
writeData(view, mac2); //I need to confirm writing the data
break;
}
}
//---------------------------- Writing MACs addresses Function --------------------------------------------
public void writeData(View view, String macNum)
{
BufferedWriter bufferWriter =null;
try {
FileOutputStream fileOutputStream = openFileOutput(macNum, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
if (macNum.equals("mac1")){
bufferWriter.write(((EditText)this.findViewById(R.id.editText1)).getText().toString());}
if (macNum.equals("mac2")){
bufferWriter.write(((EditText)this.findViewById(R.id.editText2)).getText().toString());}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
bufferWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to use this:
AlertDialog.Builder alertbox = new AlertDialog.Builder(LauncherActivity.this);
alertbox.setTitle("Are you sure?");
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(LauncherActivity.this, "You Choose Yes!!", Toast.LENGTH_LONG).show();
}
});
alertbox.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(LauncherActivity.this, "You Choose Nooo!!", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
See this git repo
Also a custom alertdialog example is exist in this repo.

How to fetch linkedin connection details(birthday etc) in android

I am unable to fetch linkedin connection details;i am able to fetch only default details like first and last name,id etc.but i want to fetch connections dob,email etc..
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
linkedInLogin();
}
});
// share on linkedin
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);
LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName()+"DOB"+p.getDateOfBirth());
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);
userConnections();
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
private void userConnections() {
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
**ProfileField.DATE_OF_BIRTH,**
ProfileField.PHONE_NUMBERS
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
System.out.println("connections name"+person.getFirstName()+" "+person.getLastName()+":"+**person.getDateOfBirth()**+person.getId());
itemslist.add(person);
}
System.out.println("person arraylist count of my connections"+itemslist.size());
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
I tried to fetch date of birth of my connections,but its showing null in the position..
D.O.B. isn't a field you can get for a connection. Please read the documentation - "For 1st degree connections, you may only retrieve profile fields available with the r_basicprofile member permission"
https://developers.linkedin.com/documents/connections-api

How to execute FB client on different Android devices?

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/

Categories