link listview to another activity - android-listview

package com.example.libtracker;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private LibactivityMainActivity studentDBoperation;
private TextView editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentDBoperation = new LibactivityMainActivity(this);
studentDBoperation.open();
List values = studentDBoperation.getAllTriptakerActivity();
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
// connecting listview to another activity
try {
setContentView(R.layout.activity_main);
ListView mlistView = (ListView) findViewById(R.id.editText1);
mlistView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new String[] {"activity_main"}));
mlistView.setOnClickListener(new OnClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
String sText = ((TextView) view).getText().toString();
Intent intent = null;
if(sText.equals("activity_main"))
intent = new Intent(getBaseContext(),TriploggerActivity.class);
//else if(sText.equals("Help")) ..........
if(intent != null)
startActivity(intent);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end of connecting listview to another actovity
public void addUser(View view)
{
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
EditText text = (EditText) findViewById(R.id.editText1);
TriptakerActivity stud = studentDBoperation.addTriptakerActivity(text.getText().toString());
adapter.add(stud);
}
public void deleteFirstUser(View view) {
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
TriptakerActivity stud = null;
if (getListAdapter().getCount() > 0)
{
stud = (TriptakerActivity) getListAdapter().getItem(0);
studentDBoperation.deleteTriptakerActivity(stud);
adapter.remove(stud);
}
}
#Override
protected void onResume() {
studentDBoperation.open();
super.onResume();
}
#Override
protected void onPause() {
studentDBoperation.close();
super.onPause();
// public void linkclickview(View v)
//// {
//Intent i = new Intent(this,TriploggerActivity.class );
//startActivity(i);
}
}
`
This is the code that I want to use to connect or link to another activity, but it is not working.
Please kindly help me out. Thanks

Related

Not getting user Facebook feed using Facebook SDK 4.10.0 Android

I am using Facebook Login in my Android App. I have successfully login with Facebook but I am not getting particular user`s feed. i.e posts which are posted by that user on Facebook.
What I have tried is like below...
package com.cloudant_db_demo.android02.insightnewapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.ibm.watson.developer_cloud.personality_insights.v2.PersonalityInsights;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Profile;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import com.twitter.sdk.android.core.models.Tweet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.fabric.sdk.android.Fabric;
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "twitter_key";
private static final String TWITTER_SECRET = "twitter_secret";
CallbackManager callbackManager;
private TwitterLoginButton twitterLoginButton;
TwitterSession twitterSession;
LoginButton fb_login_button;
AccessToken mAccessToken;
public static String social_email = "", social_id = "", social_feed = "", social_name = "", social = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
List<String> permissions = new ArrayList<String>();
permissions.add("user_posts");
fb_login_button = (LoginButton) findViewById(R.id.login_button);
fb_login_button.setReadPermissions(permissions);
//Facebook CallBack
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_status", "user_posts"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mAccessToken = loginResult.getAccessToken();
social_id = mAccessToken.getUserId();
social = "fb";
Bundle params = new Bundle();
params.putString("fields", "user_posts");
/* make the API call for Feed */
new GraphRequest(AccessToken.getCurrentAccessToken(), "/" + social_id + "/feed/", null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("Fb Feed: ", response.toString());
social_feed = social_feed + " " + response.toString() + " ";
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
callWatsonAPI(social);
}
});
thread.start();
}
}).executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
//Twitter CallBack
twitterLoginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
twitterLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
twitterSession = result.data;
social_id = Long.toString(twitterSession.getUserId());
social_name = twitterSession.getUserName();
getUserTweets();
}
#Override
public void failure(TwitterException e) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
twitterLoginButton.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
void getUserTweets() {
TwitterCore.getInstance().getApiClient(twitterSession).getStatusesService()
.userTimeline(null,
social_name,
null,
null,
null,
null,
null,
null,
null,
new Callback<List<Tweet>>() {
#Override
public void success(final Result<List<Tweet>> result) {
new Thread(new Runnable() {
#Override
public void run() {
try {
for (Tweet t : result.data) {
social_feed = social_feed + " " + t.text.toString() + " ";
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
callWatsonAPI(social);
}
});
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
#Override
public void failure(TwitterException exception) {
android.util.Log.d("twittercommunity", "exception " + exception);
}
});
}
void callWatsonAPI(String social) {
PersonalityInsights service = new PersonalityInsights();
service.setUsernameAndPassword("27324e40-6c74-44f0-a3b9-9659cf5b4ed5", "eGXEQ8EGpVTl");
service.setEndPoint("https://gateway.watsonplatform.net/personality-insights/api");
Profile profile = service.getProfile(social_feed);
/*Log.e("Watson Response: ", "" + profile);*/
if (social.equals("fb")) {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("watson_res", profile.toString());
intent.putExtra("Fb Feed", social_feed);
startActivity(intent);
} else {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("watson_res", profile.toString());
intent.putExtra("Twitter Feed", social_feed);
startActivity(intent);
}
}
}
I am getting Invalid JSON Response for One particular Facebook account. In that account I have set security to public. But for my personal Facebook account I am getting {"data":[]}. i.e null in response.
I have used compile 'com.facebook.android:facebook-android-sdk:4.10.0' in dependencies in build.gradle file.
Thanks in advance.
I have found the feeds from Facebook. What I have done is like below.
When your app is in developer mode Facebook give option to add Testers accounts through which you can test Facebook's different functionality. Below two images can give you better IDEA about it. Take a look at that.
Hope this will help to someone.

Image from clipboard not correctly displayed in JavaFX 8 application

This program shall paste an image from clipboard into an ImageView (on Windows 10). Unfortunately the image is not correctly displayed.
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Clipboard cb = Clipboard.getSystemClipboard();
if (cb.hasImage()) {
Image image = cb.getImage();
imageView.setImage(image);
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
}
Steps to reproduce:
Start cmd.exe
Press ALT-Print to copy the cmd window into the clipboard
Start program PasteImageFromClipboard
Press "Paste" button in PasteImageFromClipboard
This result is displayed on my computer:
It should be like this:
Is there more code required to draw the image correctly?
found this solution by the help of
https://community.oracle.com/thread/2238566
package com.wilutions.jiraddin;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
java.awt.Image image = getImageFromClipboard();
if (image != null) {
javafx.scene.image.Image fimage = awtImageToFX(image);
imageView.setImage(fimage);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
private java.awt.Image getImageFromClipboard() {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
try {
return (java.awt.Image) transferable.getTransferData(DataFlavor.imageFlavor);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static javafx.scene.image.Image awtImageToFX(java.awt.Image image) throws Exception {
if (!(image instanceof RenderedImage)) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = bufferedImage;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) image, "png", out);
out.flush();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return new javafx.scene.image.Image(in);
}
}

How to read all apps notification in my app when my app is closed?

package com.example.notificationlistener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn)
{
Log.i("From service","onNotificationPosted");
String pack = sbn.getPackageName();
// if("com.twitter.android".equalsIgnoreCase(pack))
// if("com.google.android.gm".equalsIgnoreCase(pack))
{
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn)
{
Log.i("Msg","Notification Removed");
}
}
this is my service class
package com.example.notificationlistener;
import java.util.Locale;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener{
TableLayout tableLayout;
TextToSpeech textToSpeech;
String text = "noText";
String title = "noTitle";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableLayout = (TableLayout)findViewById(R.id.tab);
textToSpeech = new TextToSpeech(this, null);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
Log.w("From MainActivity", "broadcast receiver is called");
String pack = intent.getStringExtra("package");
String ticker = intent.getStringExtra("ticker");
title = intent.getStringExtra("title");
text = intent.getStringExtra("text");
Log.d("mainActivity_pack", pack);
Log.d("mainActivity_title", title);
Log.d("mainActivity_text", text);
Log.d("mainActivity_ticker", ticker);
// Log.d("mainActivity", sender);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis()+5000);
notification.setLatestEventInfo(context, title, text, null);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notificationManager.notify(2, notification);
speak();
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT,1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack +"<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tableLayout.addView(tr);
}
};
protected void onDestroy()
{
super.onDestroy();
if (textToSpeech != null)
{
textToSpeech.stop();
textToSpeech.shutdown();
}
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else
{
speak();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speak()
{
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}`enter code here`
}
this is my activity. i am trying to read notification and resend them through my app so done this and i am able to get the notifications but when my app is closed its not working so please suggest me some changes or suggestions...thanks
Put your broadcast receiver into a service. Activities don't run when the app is closed. Services do. Start your services from your activity. Then they will continue to run even after closing the app.

GWT RPC - Why the results from database are printed twice ?

I am writing a simple app to enter a user into database & display list of users using GWT RPC, Hibernate in Eclipse. The problem I am getting is that the list of users is printed twice.
Here is my code where I call insert user & display users list methods.
package rpctest.client;
import java.util.ArrayList;
import rpctest.shared.User;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
//final Label label1 = new Label("First Name");
//final Label label2 = new Label("Last Name");
private FlexTable userFlexTable = new FlexTable();
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync callService = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
userFlexTable.setText(0, 0, "User ID");
userFlexTable.setText(0, 1, "First Name");
userFlexTable.setText(0, 2, "Second Name");
userFlexTable.setText(0, 3, "Remove");
//add input boxes to panel
addpanel1.add(firstName);
addpanel1.add(lastName);
firstName.setFocus(true);
//add input/result panels
mainpanel.add(userFlexTable);
mainpanel.add(addpanel1);
addpanel1.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addStock();
}
});
lastName.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
RootPanel.get().add(mainpanel);
getUser();
}
private void addStock(){
String name1 = firstName.getValue();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
/*if (!name1.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
firstName.selectAll();
return;
}*/
firstName.setValue("");
String name2 = lastName.getValue();
/*if (!name2.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
lastName.selectAll();
return;
}*/
lastName.setValue("");
firstName.setFocus(true);
callService.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
// Add the user to the table.
// int row = userFlexTable.getRowCount();
// userFlexTable.setText(row, 1, result);
getUser();
}
});
}
private void getUser(){
callService.getUser(new AsyncCallback<User[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("Problem in database connection");
}
#Override
public void onSuccess(User[] result) {
// TODO Auto-generated method stub
for(int i = 0; i < result.length; i ++)
{
//String s = result[i].getFirstName();
int row = userFlexTable.getRowCount();
userFlexTable.setText(row, 0, result[i].getId().toString());
userFlexTable.setText(row, 1, result[i].getFirstName());
userFlexTable.setText(row, 2, result[i].getLastName());
}
}
});
}
}
Man did you notice that you are calling getUser twice if the entered Name is valid and the call to the service is successfull??
You have to remove one of them!
getUser is called on every new entry & all data is entered again into table.

capturing the image using android camera [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling camera from an activity, capturing an image and uploading to a server
i am very new to android, i am trying to capture the image after that i placed that image into image view,its working on emulator but in device it crashes it shows the message force close even it cannot open the camera activity.the following is my code.
please help me how to solve this problem.thank you.
package com.gss.android;
package com.gss.android;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Pictures extends Activity{
Button btnsave,btnnewpic;
protected ImageView image;
protected String _path;
File sdImageMainDirectory;
private static final int IMAGE_CAPTURE = 0;
protected boolean _taken = true;
private Uri imageUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAMERA_PIC_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pictures);
btnsave=(Button)findViewById(R.id.btnsave);
btnnewpic=(Button)findViewById(R.id.btnnewpic);
btnnewpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCameraActivity2();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode == CAMERA_PIC_REQUEST){
if (resultCode == RESULT_OK){
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
Log.e("file path", "stiring file") ;
} catch (Exception e) {
e.printStackTrace();
}
finish();
}
}
} else if ( requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Log.d("ANDRO_CAMERA","Picture taken!!!");
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageURI(imageUri);
}
}
}
protected void startCameraActivity2()
{
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testphoto.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(Pictures.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(Pictures.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
Log.e("file dir",imageDir.toString());
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think this is a problem related to the emulator and not the physical device.
I used this code and I got a bitmap:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
imageView = (ImageView)findViewById(R.id.image);
destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
//Bitmap userImage = (Bitmap)data.getExtras().get("data");
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10; //Downsample 10x
Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
imageView.setImageBitmap(userImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Add extra to save full-image somewhere
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
Toast.makeText(JMABarcodeScannerActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(intent, REQUEST_IMAGE);
}
};
}
Main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"
/>
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerInside"
/>
</LinearLayout>