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>
Related
I tried to upload a file on firebase cloud from MainActivity, i made when application is destoryed it start background services and make a file contains StorageReference.toString()
and in background service i used getReferenceFromUrl(string)
To complete the uploading and i used after it
List<UploadTask> tasks = storage.getActiveTasks();
and i used Toast.makeText(this, "tasks: " + tasks.size(), 0).show();
and it shows tasks = 0
Why? And the upload doesnt complete yet
MainActivity
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.AppBarLayout;
import com.google.firebase.FirebaseApp;
import com.google.firebase.storage.UploadTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public final int REQ_CD_IM = 101;
private Toolbar _toolbar;
private AppBarLayout _app_bar;
private CoordinatorLayout _coordinator;
private String image = "";
private UploadSaveed upload;
private String url = "";
private ImageView imageview1;
private Button button1;
private ProgressBar progressbar1;
private TextView textview1;
private AlertDialog.Builder d;
private Intent im = new Intent(Intent.ACTION_GET_CONTENT);
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.main);
initialize(_savedInstanceState);
upload = new UploadSaveed(getApplicationContext());
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1000);
} else {
initializeLogic();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1000) {
initializeLogic();
}
}
private void initialize(Bundle _savedInstanceState) {
_app_bar = findViewById(R.id._app_bar);
_coordinator = findViewById(R.id._coordinator);
_toolbar = findViewById(R.id._toolbar);
setSupportActionBar(_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
_toolbar.setNavigationOnClickListener((view) -> {
onBackPressed();
});
imageview1 = findViewById(R.id.imageview1);
button1 = findViewById(R.id.button1);
progressbar1 = findViewById(R.id.progressbar1);
textview1 = findViewById(R.id.textview1);
d = new AlertDialog.Builder(this);
im.setType("*/*");
im.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
imageview1.setOnClickListener((view) -> {
startActivityForResult(im, REQ_CD_IM);
});
button1.setOnClickListener((view) -> {
upload.setUploadListener(new UploadSaveed.UploadSavedListener() {
#Override
public void onFailureListener(Exception e) {
SketchwareUtil.showMessage(getApplicationContext(), e.toString());
}
#Override
public void onProgressListener(UploadTask.TaskSnapshot task) {
double progress = (100 * task.getBytesTransferred()) / task.getTotalByteCount();
progressbar1.setProgress((int) progress);
double bytes = task.getBytesTransferred();
SketchwareUtil.showMessage(getApplicationContext(), "transferred : " + bytes);
if (upload.getUploadUrl() != null) {
url = upload.getUploadUrl();
}
}
#Override
public void onPausedListener(UploadTask.TaskSnapshot task) {
SketchwareUtil.showMessage(getApplicationContext(), "your uploading was paused");
}
#Override
public void onSuccessListener(UploadTask.TaskSnapshot task) {
Task<Uri> taskk = task.getStorage().getDownloadUrl();
while (!taskk.isSuccessful())
;
textview1.setText(taskk.getResult().toString());
SketchwareUtil.showMessage(getApplicationContext(), "finished");
}
});
upload.UploadFile(image);
});
}
private void initializeLogic() {
if (!isMyServiceRunning(UploadService.class)) {
} else {
stopService(new Intent(getApplicationContext(), UploadService.class));
stopService(new Intent(getApplicationContext(), UploadSaveed.class));
}
d.setTitle("AutoStart");
d.setMessage("You must enable autostart for application to Work in background.");
d.setPositiveButton("enable", (dialog, which) -> {
try {
final Intent intent = new Intent();
String manufacturer = Build.MANUFACTURER.toLowerCase();
if ("xiaomi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"));
} else if ("oppo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"));
// intent.setComponent(new ComponentName("com.coloros.oppoguardelf",
// "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity"));
} else if ("vivo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
} else if ("huawei".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager",
"com.huawei.systemmanager.optimize.process.ProtectActivity"));
} else if ("Letv".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.letv.android.letvsafe",
"com.letv.android.letvsafe.AutobootManageActivity"));
} else if ("Honor".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager",
"com.huawei.systemmanager.optimize.process.ProtectActivity"));
} else {
return;
}
startActivity(intent);
SketchwareUtil.showMessage(getApplicationContext(),
"please enable auto start to background application");
} catch (Exception e) {
e.printStackTrace();
}
});
d.setNegativeButton("I already enabled it", (dialog, which) -> {
});
d.create().show();
}
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode) {
case REQ_CD_IM:
if (_resultCode == Activity.RESULT_OK) {
ArrayList<String> _filePath = new ArrayList<>();
if (_data != null) {
if (_data.getClipData() != null) {
for (int _index = 0; _index < _data.getClipData().getItemCount(); _index++) {
ClipData.Item _item = _data.getClipData().getItemAt(_index);
_filePath.add(FileUtil.convertUriToFilePath(getApplicationContext(), _item.getUri()));
}
} else {
_filePath.add(FileUtil.convertUriToFilePath(getApplicationContext(), _data.getData()));
}
}
image = _filePath.get((int) (0));
} else {
}
break;
default:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "saved.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(url);
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
upload.PauseUploading();
startService(new Intent(this, UploadService.class));
startService(new Intent(getApplicationContext(), UploadSaveed.class));
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
UploadService
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Task;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class UploadService extends Service {
public static final String TAG = "UploadService";
private UploadSaveed upload;
#Nullable
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
upload = new UploadSaveed(getApplicationContext());
upload.setUploadListener(new UploadSaveed.UploadSavedListener() {
#Override
public void onFailureListener(Exception e) {
simpleNotifaction(1, "Upload Faild", "Upload Faild !");
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "errors.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(e.toString());
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
}
#Override
public void onProgressListener(UploadTask.TaskSnapshot task) {
double progress = (100 * task.getBytesTransferred()) / task.getTotalByteCount();
notiProgress(1, "Uploading", "Your file is Uploading..", progress);
}
#Override
public void onPausedListener(UploadTask.TaskSnapshot task) {
SketchwareUtil.showMessage(getApplicationContext(), "your uploading is paused");
}
#Override
public void onSuccessListener(UploadTask.TaskSnapshot task) {
Task<Uri> taskk = task.getStorage().getDownloadUrl();
while (!taskk.isSuccessful())
;
simpleNotifaction(1, "Uploaded", "Url: " + taskk.getResult().toString());
stopSelf();
}
});
upload.UploadFormUrl(upload.getUploadUrl2());
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent i) {
startService(new Intent(this, UploadService.class));
super.onTaskRemoved(i);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
private void notiProgress(final double _id, final String _title, final String _text, final double _progress) {
final Context context = getApplicationContext();
android.app.NotificationManager notificationManager = (android.app.NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
androidx.core.app.NotificationCompat.Builder builder;
int notificationId = (int) _id;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
android.app.NotificationChannel mChannel = new android.app.NotificationChannel(channelId, channelName,
importance);
notificationManager.createNotificationChannel(mChannel);
}
androidx.core.app.NotificationCompat.Builder mBuilder = new androidx.core.app.NotificationCompat.Builder(
context, channelId).setSmallIcon(android.R.drawable.stat_sys_upload).setTicker("")
.setContentTitle(_title).setContentText(_text).setProgress((int) 100, (int) _progress, false);
notificationManager.notify(notificationId, mBuilder.build());
}
private void simpleNotifaction(int id2, String title, String description) {
androidx.core.app.NotificationCompat.Builder builder = new androidx.core.app.NotificationCompat.Builder(this,
"channel-01")
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setSound(android.media.RingtoneManager
.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(title).setContentText(description)
.setPriority(androidx.core.app.NotificationCompat.PRIORITY_MAX).setAutoCancel(true);
androidx.core.app.NotificationManagerCompat notificationManager = androidx.core.app.NotificationManagerCompat
.from(this);
notificationManager.notify(id2, builder.build());
}
}
UploadSaveed
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;
public class UploadSaveed extends Service {
public static final String TAG = "UploadSaveed";
private FirebaseApp app;
private StorageReference storagee, path;
private UploadTask path2;
private List<UploadTask> tasks;
private String urll;
#Nullable
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
return START_STICKY;
}
public interface UploadSavedListener {
void onProgressListener(#NonNull UploadTask.TaskSnapshot task);
void onFailureListener(#NonNull Exception e);
void onSuccessListener(#NonNull UploadTask.TaskSnapshot task);
void onPausedListener(#NonNull UploadTask.TaskSnapshot task);
}
private UploadSavedListener listener;
public void setUploadListener(UploadSavedListener listener) {
this.listener = listener;
}
public UploadSaveed() {
}
public UploadSaveed(Context c) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:982483603219:android:ce7ef5f660652cdca054e6")
.setApiKey("AIzaSyAhffAnCI7dG0d3NucUAjPM6oWaX6mVSHk")
.setDatabaseUrl("trav-chat-2-default-rtdb.firebaseio.com").setStorageBucket("trav-chat-2.appspot.com")
.build();
try {
FirebaseApp.initializeApp(c, options, "firebasedb");
app = FirebaseApp.getInstance("firebasedb");
} catch (Exception e) {
e.printStackTrace();
FirebaseApp.initializeApp(c, options);
app = FirebaseApp.getInstance("firebasedb");
}
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "ssaved.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(app.toString());
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
}
public void UploadFile(String file) {
Uri file2 = Uri.parse(file);
Uri file3 = Uri.fromFile(new File(file));
storagee = FirebaseStorage.getInstance(app).getReference();
path = storagee.child("test image").child(file2.getLastPathSegment());
path2 = path.putFile(file3);
if (listener != null) {
path2.addOnFailureListener((e) -> {
listener.onFailureListener(e);
}).addOnPausedListener((task) -> {
listener.onPausedListener(task);
}).addOnProgressListener((task) -> {
listener.onProgressListener(task);
}).addOnSuccessListener((task) -> {
listener.onSuccessListener(task);
});
} else if (listener == null) {
throw new IllegalArgumentException("listener cannot be null");
}
}
/*
public void UploadFormUrl(String url) {
storagee = FirebaseStorage.getInstance(app).getReferenceFromUrl(url);
tasks = storagee.getActiveUploadTasks();
if (tasks.size() > 0) {
if (listener != null) {
path2 = tasks.get(0);
ResumeUploading();
SketchwareUtil.showMessage(this, "lol");
path2.addOnFailureListener((e) -> {
listener.onFailureListener(e);
}).addOnPausedListener((task) -> {
listener.onPausedListener(task);
}).addOnProgressListener((task) -> {
listener.onProgressListener(task);
}).addOnSuccessListener((task) -> {
listener.onSuccessListener(task);
});
} else {
throw new IllegalArgumentException("listener cannot be null");
}
} else {
throw new IllegalArgumentException("tasks cannot be equal 0 or less");
}
}
*/
public String getUploadUrl() {
if (path != null) {
return path.toString();
} else if (storagee != null) {
return storagee.toString();
} else {
throw new IllegalArgumentException("Storage Reference is null");
}
}
public void CancelUploading() {
path2.cancel();
}
public void PauseUploading() {
path2.pause();
}
public void ResumeUploading() {
path2.resume();
}
public String getUploadUrl2() {
urll = FileUtil.readFile(Environment.getExternalStorageDirectory().toString() + "/saved/saved.txt");
return urll;
}
#Override
public void onTaskRemoved(Intent i) {
startService(new Intent(this, UploadSaveed.class));
super.onTaskRemoved(i);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
}
Try to use intent
Try this code:
val intent = Intent(this, Main2Activity::class.java)
startActivity(intent)
I am looking to list the friends who are Facebook contacts and also have the app. It has shown a couple of times, but usually doesn't work.
I have no idea why. When I run the debugger, it says that I have a NullPointerException error on the following line:
friendslist = new JSONArray(jsondata);
I have tried a lot to work this out, so if you can let me know where my code goes wrong, I'll be very grateful.
I have included important pages below:
LoginActivity:
package com.phinder.phinder;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
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.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.phinder.phinder.utils.ApiServices;
import com.phinder.phinder.utils.Constants;
import com.phinder.phinder.utils.MyLinks;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class LoginActivity extends AppCompatActivity /*implements View.OnClickListener*/ {
private final int REQUEST_READ_WRITE_PERMISSION = 3, REQUEST_CAMERA_PERMISSION = 4;
CallbackManager callbackManager;
AccessToken accessToken;
Retrofit retrofit;
ApiServices apiServices;
AppCompatActivity activity;
SharedPreferences.Editor editor;
LoginButton loginButton;
Toolbar toolbar;
private String profileUri = "", id = "", name = "", email = "";
private Constants constants;
private MyLinks myLinks;
private ProgressDialog progressDialog;
private boolean isReadWritePermitted = false, isCameraPermitted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookSDKInitialize();
setContentView(R.layout.activity_login);
Constants.loginSharedPreferences = getSharedPreferences(Constants.LoginPref, MODE_PRIVATE);
activity = LoginActivity.this;
myLinks = new MyLinks(activity);
constants = new Constants();
editor = Constants.loginSharedPreferences.edit();
toolbar = (Toolbar) findViewById(R.id.toolbar_activity_login);
setSupportActionBar(toolbar);
printKeyHash();
List<String> permission = new ArrayList<String>();
permission.add("email");
permission.add("public_profile");
permission.add("user_location");
permission.add("user_birthday");
permission.add("user_friends");
progressDialog = new ProgressDialog(activity);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(myLinks.DEFAULT_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiServices = retrofit.create(ApiServices.class);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(permission);
getLoginDetails(loginButton);
}
private void requestPermission() {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
isReadWritePermitted = true;
} else {
// Show rationale and request permission.
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_WRITE_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_READ_WRITE_PERMISSION) {
if (permissions.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isReadWritePermitted = true;
getLoginDetails(loginButton);
} else {
isReadWritePermitted = false;
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void facebookSDKInitialize() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
private void getLoginDetails(final LoginButton loginButton) {
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginButton.setVisibility(View.INVISIBLE);
progressDialog.show();
Log.d("msg", "Facebook");
accessToken = AccessToken.getCurrentAccessToken();
SharedPreferences.Editor editor = Constants.loginSharedPreferences
.edit();
editor.putString(constants.LoginId, accessToken.getUserId());
editor.apply();
Log.d("msg", "fbid : " + accessToken.getUserId());
onSuccessFullLogIn(accessToken);
GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(
loginResult.getAccessToken(),
//AccessToken.getCurrentAccessToken(),
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
try {
JSONArray rawName = response.getJSONObject().getJSONArray("data");
intent.putExtra("jsondata", rawName.toString());
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
public void onSuccessFullLogIn(final AccessToken accessToken) {
Bundle params = new Bundle();
params.putString("fields", "id,name,location,email,picture.type(large)");
new GraphRequest(accessToken, "me", params, HttpMethod.GET, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
Log.d("msg", "Fb data1 : " + response.toString() + "");
JSONObject data = response.getJSONObject();
Log.d("msg", "Fb data : " + data.toString() + "");
SharedPreferences.Editor editor = Constants.loginSharedPreferences
.edit();
if (data.has("picture")) {
profileUri = data.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
if (profileUri.startsWith("http://")
|| profileUri
.startsWith("https://")) {
profileUri = profileUri.replace(
"http://", "").trim();
profileUri = profileUri.replace(
"https://", "").trim();
}
editor.putString(constants.LoginImage, profileUri);
}
if (data.has("name")) {
editor.putString(constants.LoginName, data.getString("name"));
}
//if (data.has("email")) {
// Log.d("email", data.getString("email"));
// editor.putString(constants.LoginEmail, data.getString("email"));
//}
//if (data.has("location")) {
// editor.putString("city", data
// .getJSONObject("location")
// .getString("name"));
//}
editor.putBoolean(constants.LoginStatus, true);
editor.apply();
LoginManager.getInstance().logOut();
} catch (Exception e) {
e.printStackTrace();
} finally {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
progressDialog.dismiss();
// final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
// progressDialog.show();
// Call<ResponseBody> call = apiServices.socialCall(Constants.loginSharedPreferences.getString(constants.LoginName, ""),
// Constants.loginSharedPreferences.getString(constants.LoginId, ""),
// Constants.loginSharedPreferences.getString(constants.LoginEmail, ""),
// Constants.loginSharedPreferences.getString(constants.LoginImage, "")
// );
//
// call.enqueue(new Callback<ResponseBody>() {
// #Override
// public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
// try {
//
// String result = response.body().string();
//
// Log.d("msg", "Result : " + result);
//
//
// JSONObject jsonObject = new JSONObject(result);
//// progressDialog.dismiss();
//
//
// if (jsonObject != null && jsonObject.length() > 0) {
//
// JSONArray jsonArray = jsonObject.getJSONArray("response");
//
// Log.d("msg", "Json : " + jsonArray.toString());
//
// if (jsonArray != null && jsonArray.length() > 0) {
//
// for (int i = 0; i < jsonArray.length(); i++) {
//
// JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//
// String status = jsonObject1.getString("status");
// String id = jsonObject1.getString("id");
//
// SharedPreferences.Editor editor = Constants.loginSharedPreferences.edit();
// editor.putString(constants.UserId, id);
// editor.apply();
//
// if (status.equals("one") || status.equals("zero")) {
// startActivity(new Intent(activity, MainActivity.class));
// finish();
//
// } else {
// Toast.makeText(activity, "Invalid login", Toast.LENGTH_LONG).show();
// }
// }
// }
// }
//
// } catch (IOException e) {
// e.getStackTrace();
//
// Log.d("msg", "IO " + e.getMessage());
// progressDialog.dismiss();
// } catch (JSONException e) {
//
// e.printStackTrace();
// Log.d("msg", "JSON " + e.getMessage());
// progressDialog.dismiss();
// }
// }
//
// #Override
// public void onFailure(Call<ResponseBody> call, Throwable t) {
// Log.d("msg", "JSON " + t.getMessage());
//
// progressDialog.dismiss();
// }
// });
}
}
}
}).executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
// Log.d("data",data.toString());
}
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(LoginActivity.this, "369622066719726");
}
#Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(LoginActivity.this, "369622066719726");
}
public String printKeyHash() {
PackageInfo packageInfo;
String key = null;
try {
//getting application package name, as defined in manifest
String packageName = getApplicationContext().getPackageName();
//Retriving package info
packageInfo = getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
Log.d("Package Name=", getApplicationContext().getPackageName());
for (Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
key = new String(Base64.encode(md.digest(), 0));
// String key = new String(Base64.encodeBytes(md.digest()));
Log.d("Key Hash=", key);
// ST4ot689mPBUodJzQxMIutXIkKw=
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("Name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.d("No such an algorithm", e.toString());
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return key;
}
}
MainActivity:
package com.phinder.phinder;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ImageView imageView_picture_profile;
TextView textview_nameprofile,textview_emailprofile;
public com.phinder.phinder.utils.Constants constants;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// User Information
constants = new com.phinder.phinder.utils.Constants();
imageView_picture_profile = (ImageView)findViewById(R.id.imageView_picture_profile);
//textview_emailprofile = (TextView) findViewById(R.id.textview_emailprofile);
textview_nameprofile = (TextView)findViewById(R.id.textview_nameprofile);
//textview_emailprofile.setText(constants.loginSharedPreferences.getString(constants.LoginEmail, ""));
textview_nameprofile.setText(constants.loginSharedPreferences.getString(constants.LoginName, ""));
try {
Glide.with(getApplicationContext())
.load("http://" + constants.loginSharedPreferences.getString(constants.LoginImage, ""))
.placeholder(R.mipmap.ic_launcher)
.thumbnail(.1F)
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(imageView_picture_profile);
} catch (Exception e) {
e.getStackTrace();
Log.d("msg", "Photo " + e.getMessage());
}
//ListView Facebook Friends
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
JSONArray friendslist;
ArrayList<String> friends = new ArrayList<String>();
try {
friendslist = new JSONArray(jsondata);
for (int l=0; l < friendslist.length(); l++) {
friends.add(friendslist.getJSONObject(l).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, friends); // simple textview for list item
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
Okay guys, I was playing about with it and I found out what the issue was, finally!
I had a duplicate token access request in LoginActivity.java which was causing this issue.
onSuccessFullLogIn(accessToken);
when I commented this out, it worked perfectly
I know I'm answering my own question here, but I noticed this issue is around the internet a lot, with no real answer, so I hope it's useful for some people!
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.
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);
}
}
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