I'm developing an app that accesses all the images in your device and automatically upload the images on Firebase Storage.
This is like whenever the activity starts, it automatically fetch image and upload without user's selection.
Main_Activity:
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Cursor cursor;
private int columnIndex;
GridView AllImages;
public int REQUEST_PERMISSIONS = 123;
Uri myUri;
ImageView img;
FirebaseApp firebaseApp;
FirebaseDatabase firebaseDatabase;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
Log.e("Else", "Else");
}
img = (ImageView) findViewById(R.id.images);
ArrayList<String> arrayList = getImagesPath(this);
String a = arrayList.get(6);
Toast.makeText(getApplicationContext(), "" + a.toString(), Toast.LENGTH_LONG).show();
img.setImageURI(Uri.parse(new File(a).toString()));
myUri = Uri.parse(new File(c).toString());
firebaseApp = FirebaseApp.getInstance();
firebaseStorage = FirebaseStorage.getInstance(firebaseApp);
storageReference = firebaseStorage.getReference("Pictures");
StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(myUri));
sRef.putFile(myUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(getApplicationContext(), "Can't Upload ", Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
Toast.makeText(getApplicationContext(), "Uploading ", Toast.LENGTH_LONG).show();
}
});
String[] projection = {MediaStore.Images.Thumbnails._ID};
cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Thumbnails._ID + "");
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
AllImages = (GridView) findViewById(R.id.GV_Images);
AllImageAdapter adapter = new AllImageAdapter(MainActivity.this, cursor, columnIndex);
AllImages.setAdapter(adapter);
}
public String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public static ArrayList<String> getImagesPath(Activity activity) {
Uri uri;
ArrayList<String> listOfAllImages = new ArrayList<String>();
Cursor cursor;
int column_index_data, column_index_folder_name;
String PathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
cursor = activity.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while (cursor.moveToNext()) {
PathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(PathOfImage);
}
return listOfAllImages;
}
}
Adapter Class:
public class AllImageAdapter extends BaseAdapter {
Context c;
Cursor cur;
ImageView imageView;
int columnIndex;
public AllImageAdapter(Context c, Cursor cur, int columnIndex)
{
this.c = c;
this.cur = cur;
this.columnIndex = columnIndex;
}
#Override
public int getCount() {
return cur.getCount();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Set The Image in Image View.
imageView = new ImageView(c);
cur.moveToPosition(position);
int imageID = cur.getInt(columnIndex);
imageView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
imageView.setLayoutParams(new GridView.LayoutParams(330, 330));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(4, 4, 4, 4);
//convertView.setTag(imageView);
return imageView;
}
}
In (Main Activity), for a time being, I'm just picking one picture by myself that is on index 6, to check if it works or not.
And here's
my another class:
public class Constants {
public static final String STORAGE_PATH_UPLOADS = "uploads/";
//public static final String DATABASE_PATH_UPLOADS = "uploads";
}
I'm not using Database yet.
The problem that I'm facing is, whenever the program runs, it shows exception:
StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
09-08 12:06:44.694 11024-11263/com.example.umairasher.picturestofirebase
E/StorageException: No content provider: received_1035650876484715.jpeg
java.io.FileNotFoundException: No content provider: received_1035650876484715.jpeg
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1092)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:944)
at android.content.ContentResolver.openInputStream(ContentResolver.java:664)
at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
at com.example.umairasher.picturestofirebase.MainActivity.onCreate(MainActivity.java:113)
at android.app.Activity.performCreate(Activity.java:6439)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605)
at android.app.ActivityThread.access$1100(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:179)
at android.app.ActivityThread.main(ActivityThread.java:5730)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
E/StorageException: No content provider: received_1035650876484715.jpeg
java.io.FileNotFoundException: No content provider: received_1035650876484715.jpeg
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1092)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:944)
at android.content.ContentResolver.openInputStream(ContentResolver.java:664)
at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
at com.example.umairasher.picturestofirebase.MainActivity.onCreate(MainActivity.java:113)
at android.app.Activity.performCreate(Activity.java:6439)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605)
at android.app.ActivityThread.access$1100(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:179)
at android.app.ActivityThread.main(ActivityThread.java:5730)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
Can anybody please help, I know I'm doing a mistake somewhere but just can't help it. Thanks in advance.
Related
Hi I'm following this video tutorial https://www.youtube.com/watch?v=wQN2eCO-M_Q&t=7717s (the part I suppose create this issue can be found at time 2:01:17)and I managed to make this code work without implementing the notifications, but it only works on the simulator.
When I try to debug it with my phone it gives me the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chat, PID: 7894
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to Timestamp (found in field 'timestamp')
On others real devices it works properly but on my real me 8 pro it does not
here is some code from my android studio:
ChatModel.java
package com.example.chat.model;
import com.google.firebase.Timestamp;
import java.sql.Time;
import java.util.Date;
public class ChatModel {
String message;
String user_name;
String messageID;
String user_image_url;
String chat_image;
Timestamp timestamp;
public ChatModel() {
}
public ChatModel(String message, String user_name, String messageID, String user_image_url, String chat_image, Timestamp timestamp) {
this.message = message;
this.user_name = user_name;
this.messageID = messageID;
this.user_image_url = user_image_url;
this.chat_image = chat_image;
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessageID() {
return messageID;
}
public void setMessageID(String messageID) {
this.messageID = messageID;
}
public String getUser_image_url() {
return user_image_url;
}
public void setUser_image_url(String user_image_url) {
this.user_image_url = user_image_url;
}
public String getChat_image() {
return chat_image;
}
public void setChat_image(String chat_image) {
this.chat_image = chat_image;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
}
i have tried to change Timestamp with: long, Long, Date and Number.
But i wouldn't work anyways
MainActivity.java
package com.example.chat;
import static com.example.chat.cords.FirebaseCords.MAIN_CHAT_DATABASE;
import static com.example.chat.cords.FirebaseCords.mAuth;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.chat.adapter.ChatAdapter;
import com.example.chat.cords.FirebaseCords;
import com.example.chat.model.ChatModel;
import com.example.chat.model.SaveState;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.Query;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Queue;
public class MainActivity extends AppCompatActivity {
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
startActivity(new Intent(this, LoginActivity.class));
finish();
}
chatAdapter.startListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chat_room, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
mAuth.signOut();
startActivity((new Intent(this, LoginActivity.class)));
break;
}
return super.onOptionsItemSelected(item);
}
EditText chat_box;
RecyclerView chat_list;
ChatAdapter chatAdapter;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chat_box = findViewById(R.id.chat_box);
chat_list = findViewById(R.id.chat_list);
initChatList();
}
private void initChatList() {
chat_list.setHasFixedSize(true);
chat_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
Query query = MAIN_CHAT_DATABASE.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<ChatModel> option = new FirestoreRecyclerOptions.Builder<ChatModel>()
.setQuery(query, ChatModel.class)
.build();
chatAdapter = new ChatAdapter(option);
chat_list.setAdapter(chatAdapter);
chatAdapter.startListening();
}
public void addMessage(View view) {
String message = chat_box.getText().toString();
FirebaseUser user = mAuth.getCurrentUser();
if (!TextUtils.isEmpty(message)) {
/*Generate messageID using the current date. */
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String messageID = format.format(today);
/*Getting user image from Google account*/
String user_image_url = "";
Uri photoUrl = user.getPhotoUrl();
String originalUrl = "s96-c/photo.jpg";
String resizeImageUrl = "s400-c/photo.jpg";
if (photoUrl!=null) {
String photoPath = photoUrl.toString();
user_image_url = photoPath.replace(originalUrl,resizeImageUrl);
}
HashMap<String, Object> messageObj = new HashMap<>();
messageObj.put("message", message);
messageObj.put("user_name", user.getDisplayName());
messageObj.put("timestamp",FieldValue.serverTimestamp());
messageObj.put("messageID", messageID);
messageObj.put("chat_image","");
messageObj.put("user_image_url", user_image_url);
MAIN_CHAT_DATABASE.document(messageID).set(messageObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Message send", Toast.LENGTH_SHORT).show();
chat_box.setText("");
} else {
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void OpenExplorer(View view) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
ChoseImage();
} else {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 20);
} else {
Toast.makeText(this, "Storage Permission Needed", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 20);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 20) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
ChoseImage();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void ChoseImage(){
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(MainActivity.this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Log.d("TAG", "onActivityResult:"+result);
if (resultCode == RESULT_OK) {
imageUri = result.getUri();
Log.d("TAG", "onActivityResult:"+imageUri);
startActivity(new Intent(MainActivity.this, ImageUploadPreview.class)
.putExtra("image_uri", imageUri.toString()));
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, result.getError().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
public void Finish(View view) {
long currentTime = new Date().getTime();
new SaveState(this).setClickTime(currentTime);
finish();
}
}
ChatAdapter.java
package com.example.chat.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.chat.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.example.chat.model.ChatModel;
import org.w3c.dom.Text;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatAdapter extends FirestoreRecyclerAdapter<ChatModel, ChatAdapter.ChatViewHolder> {
public ChatAdapter (#NonNull FirestoreRecyclerOptions <ChatModel> options) {
super(options);
}
#Override
protected void onBindViewHolder (#NonNull ChatViewHolder chatViewHolder, int i, #NonNull ChatModel chatModel) {
chatViewHolder.message.setText(chatModel.getMessage());
Glide.with(chatViewHolder.user_image.getContext().getApplicationContext())
.load(chatModel.getUser_image_url())
.into(chatViewHolder.user_image);
if(!chatModel.getChat_image().equals("")){
Glide.with(chatViewHolder.chat_image.getContext().getApplicationContext())
.load(chatModel.getChat_image())
.into(chatViewHolder.chat_image);
chatViewHolder.chat_image.setVisibility(View.VISIBLE);
}else{
chatViewHolder.chat_image.setVisibility(View.GONE);
}
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder (#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item,parent,false);
return new ChatViewHolder(v);
}
class ChatViewHolder extends RecyclerView.ViewHolder {
TextView message;
CircleImageView user_image;
ImageView chat_image;
public ChatViewHolder(#NonNull View itemView) {
super(itemView);
message = itemView.findViewById(R.id.message);
user_image = itemView.findViewById(R.id.user_image);
chat_image = itemView.findViewById(R.id.chat_image);
}
}
}
Screenshoot of thedatabase structure:
here
I have no idea how to solve that error can someone help me?
If you need any more information comment i will add it as soon as i see the message thanks in advance.
I am creating mp3 player unable to get audio path URI using media.uri.data is not working please help me how get path audio file path?
Here is my code. I am searching lot but did not found the answer media.uri.data is return null what should do?I am unable stuck only in this step help?
package com.monstertechno.musicplayerappui;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
private ArrayList<Song> songList;
private ListView songView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runtimpermission();
songView = (ListView) findViewById(R.id.song_list);
songList = new ArrayList<Song>();
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mediaPlayer!=null){
mediaPlayer.release();
}
}
});
}
public void runtimpermission(){
Dexter.withActivity(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override public void onPermissionGranted(PermissionGrantedResponse response) {
Toast.makeText(MainActivity.this, "Permisson Access", Toast.LENGTH_SHORT).show();
}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "Permisson Denied", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();}
}).check();
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
}
Okay you were'nt clear enough,I add a complete code in case any body needs it you only need one line of it though:
Cursor cur = cr.query(uri, null, selection, null, sortOrder);
int count = 0;
if (cur != null) {
count = cur.getCount();
if (count > 0) {
while (cur.moveToNext()) {
String album = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
String artist = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
String title =(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)));
String path = (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)));
String alumbId =(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
long duration = (cur.getLong(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)));
Cursor cursorImage = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART}, MediaStore.Audio.Albums._ID+ "=?", new String[] {String.valueOf(alumbId)}, null);
assert cursorImage != null;
if (cursorImage.moveToFirst()) {
String imagePath = cursorImage.getString(cursorImage.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
}
}
}
}
cur.close();
It works I just tested it.Just check for null for imagePath.
Hello everyone, My group for Thesis project is currently having problems on running our android app using Android Studio, The concept is Steganography and we are using an F5 Library from https://github.com/guardianproject/PixelKnot/tree/version_2/PixelKnot/src/main/java/info/guardianproject/pixelknot
Here is our user interface and whenever clicking embed button, the app closes automatically
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.angel.filepicker, PID: 2972
java.lang.NullPointerException: Attempt to invoke virtual method 'void info.guardianproject.f5android.stego.StegoProcessor.addThread(info.guardianproject.f5android.stego.StegoProcessThread, boolean)' on a null object reference
at com.example.angel.filepicker.EmbedFragment$3.onClick(EmbedFragment.java:162)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
EmbedFragment.java code
package com.example.angel.filepicker;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import info.guardianproject.f5android.plugins.f5.Embed;
import info.guardianproject.f5android.stego.*;
import info.guardianproject.f5android.plugins.PluginNotificationListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
public class EmbedFragment extends Fragment {
private static final String TAG = "EMbed";
public EmbedFragment() {
}
private Activity a;
public File finalFile;
public File msgFile;
public byte[] seed = new String("This is hopefully Temporary").getBytes();
public String baseimage;
public String secret_file;
public Intent fileIntent;
public static Activity act;
public static Context cntx;
public StegoProcessor stego_processor;
//FOR FILE BUTTON
public static final int FILE_PICKER_REQUEST_CODE = 1;
Intent intent;
Button btn_choose_image;
ImageView image;
TextView text;
//FOR IMAGE BUTTON
File photoFile = null;
static final int CAPTURE_IMAGE_REQUEST = 2;
static final int SELECT_FILE = 3;
String mCurrentPhotoPath;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.embed_fragment, container, false);
cntx = getActivity().getBaseContext();
act = getActivity();
//initialize and set intent type
fileIntent = new Intent();
fileIntent.setType("*/*");
fileIntent.setAction(Intent.ACTION_GET_CONTENT);
text = view.findViewById(R.id.textView2);
//FOR FILE BUTTON
Button pickButton = view.findViewById(R.id.pick_from_activity);
pickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checkPermissionsAndOpenFilePicker();
startActivityForResult(Intent.createChooser(fileIntent, "Select File"), FILE_PICKER_REQUEST_CODE);
}
});
//FOR IMAGE BUTTON
btn_choose_image = view.findViewById(R.id.btn_choose_image);
image = view.findViewById(R.id.imageView2);
btn_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
final Button embedButton = (Button) view.findViewById(R.id.embedButton);
embedButton.setOnClickListener(embedButtonListener);
return view;
}
View.OnClickListener embedButtonListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if(baseimage !=null)
{
if ( secret_file != null) {
//ImageSteganography Object instantiation
Embed embed = new Embed(a,baseimage , secret_file, seed) {
#Override
public void run() {
super.run();
}
};
stego_processor.addThread(embed, true);
}
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode==RESULT_OK && data != null && data.getData() != null) {
Uri uri=data.getData();
try{
msgFile=new File(uri.getPath());//get the file
secret_file = uri.getPath();
//secretFile = getPathFromUri(getActivity(),uri);
Toast.makeText(act.getBaseContext(), "Picked file: " + msgFile, Toast.LENGTH_LONG).show();
//text.setText(textx);
}catch(Exception e){}
if(msgFile.length()==0){
try{
msgFile=new File(getPathFromUri(getActivity(),uri));//get the file
// secretFile = getPathFromUri(getActivity(),uri);
Toast.makeText(act.getBaseContext(), "Picked file: " + msgFile, Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("Main","Unable to get file!");
e.printStackTrace();
}
}
}
if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == RESULT_OK) {
// baseImage = photoFile.getAbsoluteFile();
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
//PROBLEMA NITO IS YUNG PAG DISPLAY NG PIC YUNG SIZE NG PIC .
// MAY METHOD NA RESIZIND PERO TSAKA NA CGURO PAG NALAGAY NA UI
if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
// baseImage = getRealPathFromURI(getActivity(), data.getData());
Uri uri=data.getData();
try {
// mengambil gambar dari Gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
baseimage = uri.getPath();
image.setImageBitmap(bitmap);
text.setText(baseimage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// private String getRealPathFromURI(Context context, Uri contentUri) {
// Cursor cursor = null;
// try {
// String[] proj = { MediaStore.Images.Media.DATA };
// cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
// int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// cursor.moveToFirst();
// return cursor.getString(column_index);
// } catch (Exception e) {
// Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
// return "";
// } finally {
// if (cursor != null) {
// cursor.close();
// }
// }
// }
public static String getPathFromUri(final Context context, final Uri uri) {//get path name from a uri object(source: web)
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
//...................................................................................................................................
//FOR IMAGE BUTTON
private void captureImage() {
image.setImageResource(0);
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
//ITO YUNG CHOICE KUNG TAKE PHOTO OR SELECT IMAGE . KAPAG TAKE PHOTO DAPAT
// NASASAVE SA GALLERY PERO WALA AKO NAKITA SA GALLERY KO HAHAH FEELING KO MAS OKAY PAG DI NLNG NASSASAVE
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
displayMessage(getActivity().getBaseContext(), photoFile.getAbsolutePath());
Log.i("Stegrapp", photoFile.getAbsolutePath());
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.example.angel.filepicker.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
}
} catch (Exception ex) {
// Error occurred while creating the File
displayMessage(getActivity().getBaseContext(), ex.getMessage().toString());
}
} else {
displayMessage(getActivity().getBaseContext(), "Nullll");
}
//PROBLEMA NITO IS YUNG PAG DISPLAY NG PIC YUNG SIZE NG PIC .
// MAY METHOD NA RESIZIND PERO TSAKA NA CGURO PAG NALAGAY NA UI
} else if (items[item].equals("Choose from Library")) {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
//........................................................................................................
//ITO YUNG PAG CREATE NG FILE NUNG IMAGE GALING CAMERA
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void displayMessage(Context context, String message)
{
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
public static void show(final String toast){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(EmbedFragment.cntx,toast,Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java code
package com.example.angel.filepicker;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 4000;
ImageView imageView;
Toolbar toolbar;
ViewPager viewPager;
TabLayout tabLayout;
FloatingActionButton shareButton;
Button btn_choose_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar_id);
viewPager = findViewById(R.id.viewPager_id);
tabLayout = findViewById(R.id.tabLayout_id);
shareButton = findViewById(R.id.shareButton_id);
//sharing
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
// this should be the file
// must create folder the carrier image
// this is a sample that takes string
//intent takes string should be file
myIntent.setType("text/plain");
//should be the carrier image
String shareBody = "Your body here";
// can be removed / optional
String shareSub = "Your subject here";
myIntent.putExtra(Intent.EXTRA_SUBJECT,shareSub);
myIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
startActivity(Intent.createChooser(myIntent, "Share using"));
}
});
// SETTING UP ViewPagerAdapter
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addElements(new EmbedFragment(), "Embed");
viewPagerAdapter.addElements(new ExtractFragment(), "Extract");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
My app is supposed to display a Google Map with a heatmap, but I can't even get the map to display. It's only showing the logo in the bottom left corner. There seems to be no errors. I also checked the gradle and all the necessary dependencies are there. I can't tell if this is due to an actual error or lack of memory/slow processing.
Here's the MainActivity
package com.example.alexlevine.oceanapp;
package com.example.alexlevine.oceanapp;
import android.app.Dialog;
import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.maps.android.heatmaps.HeatmapTileProvider;
import com.google.maps.android.heatmaps.WeightedLatLng;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import static com.example.alexlevine.oceanapp.R.id.seekBar;
import static com.example.alexlevine.oceanapp.fetchSOCATData.co2array;
public class MainActivity extends AppCompatActivity
implements OnMapReadyCallback {
public static SeekBar seekbar;
public static GoogleMap mGoogleMap;
private HeatmapTileProvider mProvider;
public static TextView minyear;
public static TextView maxyear;
public static TextView currentyeartext;
public static int displayyear;
public static boolean usingSOCAT;
public static String typeKey;
public static Spinner dropdown;
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
Button b2;
Button b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (googleServicesAvailable()) {
Toast.makeText(this, "Play services available", Toast.LENGTH_LONG).show();;
initMap();
b2 = (Button) findViewById(R.id.button2);
b4 = (Button) findViewById(R.id.button4);
b2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button2) {
Intent i = new Intent(MainActivity.this, CarbonCalcActivity.class);
startActivity(i);
finish();
}
}
});
b4.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId() == R.id.button4) {
Intent i = new Intent(MainActivity.this, CalcData.class);
startActivity(i);
finish();
}
}
}
);
//get the spinner from the xml.
dropdown = (Spinner)findViewById(R.id.spinner);
//create a list of items for the spinner.
String[] items = new String[]{"Ocean CO2 Densities", "Land CO2 Emissions (all sources)", "Electricity CO2 Emissions", "Aviation CO2 Emissions", "Ocean Shipping CO2 Emissions"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);
currentyeartext = (TextView) findViewById(R.id.currentyear);
minyear = (TextView) findViewById(R.id.minyear);
maxyear = (TextView) findViewById(R.id.maxyear);
typeKey = "00totals";
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
switch (position) {
case 0: {
usingSOCAT = true;
displayyear = 1991;
seekbar.setMax(24);
minyear.setText("1991");
maxyear.setText("2015");
break;
}
case 1: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "00totals";
break;
}
case 2: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "01elec";
// Whatever you want to happen when the thrid item gets selected
break;
}
case 3: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "11aviation";;
// Whatever you want to happen when the thrid item gets selected
break;
}
case 4: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "12shipping";
// Whatever you want to happen when the thrid item gets selected
break;
}
}
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
seekbar = (SeekBar) findViewById(seekBar);
seekbar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
displayyear = progress + 1991;
if(usingSOCAT)
{
displayyear = progress + 1991;
new fetchSOCATData().execute();
}
else
{
displayyear = progress + 1997;
new fetchFFDASData().execute();
//List<WeightedLatLng> calledData = fetchFFDASData.ffdasArray;
//createHeatMap(fetchFFDASData.ffdasArray);
minyear.setText((CharSequence) fetchFFDASData.ffdasArray);
}
currentyeartext.setText("Showing: " + displayyear);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
if(usingSOCAT) {
}
//new fetchSOCATData().execute();
/*minyear = (TextView) findViewById(R.id.minyear);
maxyear = (TextView) findViewById(R.id.maxyear);
minyear.setText("1957");
maxyear.setText("2015");*/
//fetchSOCATData process = new fetchSOCATData();
//process.execute();
} else {
//No maps layout
}
}
//#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void initMap() {
SupportMapFragment mapFragment = (SupportMapFragment) this.getSupportFragmentManager()
.findFragmentById(R.id.mapFragment);
if(mapFragment != null) {
mapFragment.getMapAsync((OnMapReadyCallback)this);
}
}
public void createHeatMap(List<WeightedLatLng> dataset)
{
List<WeightedLatLng> locations = dataset;
/*mProvider = new HeatmapTileProvider.Builder().weightedData(locations).build();
mProvider.setRadius( HeatmapTileProvider.DEFAULT_RADIUS );
mGoogleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
mProvider = new HeatmapTileProvider();
mProvider.setWeightedData(dataset);
mProvider = mProvider.build();*/
//for (LatLng coordinate : coordinates) {
//WeightedLatLng weightedCoordinate = new WeightedLatLng(coordinate);
//com.google.maps.android.geometry.Point point = weightedCoordinate.getPoint();
// Filter points at infinity
/* if (Double.isInfinite(point.x) || Double.isInfinite(point.y)) {
Log.w(TAG, "Attempted to add undefined point " + coordinate);
continue;
}
weightedCoordinates.add(weightedCoordinate);*/
//}
mProvider = new HeatmapTileProvider.Builder()
.weightedData(dataset)
.opacity(0.5)
.build();
mGoogleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
Toast.makeText(this, "working", Toast.LENGTH_SHORT).show();
}
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
//goToLocation(-65, -12);
}
public void goToLocation(double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mGoogleMap.moveCamera(update);
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS)
return true;
else if (api.isUserResolvableError(isAvailable)) {
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else
Toast.makeText(this, "Can't connect to play services", Toast.LENGTH_LONG).show();
return false;
}
}
Here's my code to fetch the data for the heatmap:
package com.example.alexlevine.oceanapp;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.maps.android.heatmaps.WeightedLatLng;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.example.alexlevine.oceanapp.MainActivity.displayyear;
import static com.example.alexlevine.oceanapp.MainActivity.minyear;
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class fetchSOCATData extends AsyncTask<Object, Object, ArrayList<WeightedLatLng>> {
//String data = "http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.geoJson?year%2Cmonth%2Cday%2Chour%2Cminute%2Csecond%2Clongitude%2Clatitude%2Csal%2CTemperature_equi%2CTemperature_atm%2CpCO2_atm_wet_actual%2Cdelta_fCO2%2Crelative_humidity%2Cspecific_humidity%2Cwind_speed_true%2Cwind_speed_rel%2Cwind_dir_true%2Cwind_dir_rel%2CfCO2_recommended%2Cregion_id%2Ctime&organization=%22%22";
//public static SOCATCO2DataPoint.FeaturesBean[] co2array;
public static List<WeightedLatLng> co2array;
#Override
protected ArrayList<WeightedLatLng> doInBackground(Object... params) {
co2array = new ArrayList<WeightedLatLng>();
int year = displayyear;
URL url = null;
try {
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.geoJson?year%2Cmonth%2Cday%2Chour%2Cminute%2Csecond%2Clongitude%2Clatitude%2Csal%2CTemperature_equi%2CTemperature_atm%2CpCO2_atm_wet_actual%2Cdelta_fCO2%2Crelative_humidity%2Cspecific_humidity%2Cwind_speed_true%2Cwind_speed_rel%2Cwind_dir_true%2Cwind_dir_rel%2CfCO2_recommended%2Cregion_id%2Ctime&organization=%22%22&year%3E=2015&month%3C=1&day%3C=1&hour%3C=1&minute%3C=1&second%3C=10");
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.json?year%2Clongitude%2Clatitude%2CfCO2_recommended%2Ctime&organization=%22%22&year%3E=" + year + "&year%3C=" + year);
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.json?year%2Clongitude%2Clatitude%2CfCO2_recommended%2Ctime&organization=%22%22&year%3E=2015&year%3C=2015&month%3E=1&month%3C=1&day%3E=1&day%3C=1&hour%3E=1&hour%3C=1");
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.geoJson?year%2Cmonth%2Cday%2Chour%2Cminute%2Csecond%2Clongitude%2Clatitude%2CfCO2_recommended%2Ctime&organization=%22%22&year%3E=" + year + "&year%3C=" + year);
url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.json?longitude%2Clatitude%2CfCO2_recommended&organization=%22%22&year=" + displayyear + "&day=1&hour=1&minute%3C=5&second%3C=30&longitude!=NaN&longitude!=NaN&latitude!=NaN&latitude!=NaN");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e1) {
e1.printStackTrace();
}
String result = null;
try {
result = response.body().string();
} catch (IOException e1) {
e1.printStackTrace();
}
//System.out.print("result" + result);
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<OfficialSOCATPoint.TableBean>>() {}.getType();
OfficialSOCATPoint enums = gson.fromJson(result, OfficialSOCATPoint.class);
//Collection<OfficialSOCATPoint.TableBean> enums = gson.fromJson(result, collectionType);
/*SOCATCO2DataPoint.FeaturesBean[] protoExtract = enums.toArray(new SOCATCO2DataPoint.FeaturesBean[enums.size()]);*/
OfficialSOCATPoint protoExtract = gson.fromJson(result, OfficialSOCATPoint.class);
//OfficialSOCATPoint.TableBean[] protoExtract = enums.toArray(new OfficialSOCATPoint.TableBean[enums.size()]);
List<List<String>> dataArray = (List<List<String>>) protoExtract.getTable().getRows();
//for (int i = 0; i < dataArray.size(); i++)
for (int i = 0; i < 2; i++)
{
if(dataArray.get(i).get(2) != "null" && dataArray.get(i).get(1) != "null" && dataArray.get(i).get(0) != "null")
{
//co2array.add(new WeightedLatLng(new LatLng(Double.parseDouble(dataArray.get(i).get(0)), Double.parseDouble(dataArray.get(i).get(1))), Double.parseDouble(dataArray.get(i).get(2))));
}
}
return (ArrayList<WeightedLatLng>) co2array;
}
//#Override
protected void onPostExecute(ArrayList<WeightedLatLng> fb) {
super.onPostExecute(fb);
}
}
Here's the logcat:
10-17 16:45:27.884 1583-1593/? W/WallpaperManagerService: Cannot extract colors because wallpaper could not be read.
10-17 16:45:27.886 1583-1593/? W/WallpaperManagerService: Cannot extract colors because wallpaper could not be read.
10-17 16:45:17.747 2160-2160/? W/zygote: Common causes for lock verification issues are non-optimized dex code
10-17 16:45:17.955 1583-1807/? W/WallpaperManagerService: Cannot extract colors because wallpaper could not be read.
10-17 16:45:19.896 2138-2227/? W/zygote: Common causes for lock verification issues are non-optimized dex code
10-17 16:45:28.114 2188-2312/? W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.recognizer.j.a.a(SourceFile:28)
at com.google.android.apps.gsa.staticplugins.recognizer.j.b.run(SourceFile:15)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.a.ag.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:6)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.f(SourceFile:103)
at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:18)
at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.a.ag.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:6)
10-17 16:45:38.815 2510-2510/? I/Finsky: [2] com.google.android.finsky.setup.VpaService.a(32): Should not show workaround PAI step because experiment disabled
10-17 16:45:48.416 1767-2047/? I/GCoreUlr: WorldUpdater:init: Ensuring that reporting is stopped because of reasons: (no Google accounts)
10-17 16:45:49.205 2069-2069/? I/MediaRouter: Unselecting the current route because it is no longer selectable: null
10-17 16:46:16.401 1767-2047/? W/NetworkScheduler: Immediate task was not started com.google.android.videos/.service.drm.RefreshLicenseTaskService{u=0 tag="refresh_license_forced" trigger=window{start=0s,end=1s,earliest=-1s,latest=0s} requirements=[NET_CONNECTED] attributes=[] scheduled=-1s last_run=N/A jid=N/A status=PENDING retries=0 client_lib=MANCHEGO_GCM-10400000}. Rescheduling immediate tasks can cause excessive battery drain.
10-17 16:46:16.928 1767-2047/? W/NetworkScheduler: Immediate task was not started com.google.android.gms/.tapandpay.gcmtask.TapAndPayGcmTaskService{u=0 tag="immediate" trigger=window{start=0s,end=1s,earliest=-1s,latest=0s} requirements=[NET_CONNECTED] attributes=[] scheduled=-1s last_run=N/A jid=N/A status=PENDING retries=0 client_lib=MANCHEGO_GCM-14366000}. Rescheduling immediate tasks can cause excessive battery drain.
Please help me with this. Thanks!
I created an app with database in assets folder . I wrote a code to copy database to SD Card and of course for android 6 + it needs run time permission. My problem : on first run after granting permission database isn't loaded but on second run there is no problem. Please help me to solve this issue .
UPDATE: Problem solved! now I have problem with favorite section. when I add something to favorite it can't be updated and I have to restart app and also with each run data is shown more than one time.
Here's my code :
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
} else if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this
, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}
, 1);
} else {
setupDB();
selectList();
selectFavorite();
Toast.makeText(MainActivity.this, "You grandet earlier",
Toast.LENGTH_LONG).show();
}
}
if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
} else if (!list.isEmpty()){
list.clear();
selectList();
}
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new
NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}
if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this,
ActivitySearch.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length >= 2 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED && grantResults[1] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Access granted",
Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
} else if (!list.isEmpty()){
list.clear();
selectList();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
You have just shown a toast after permissions are granted for the first time i.e. inside onRequestPermissionsResult. You will need to place the code to perform necessary operations inside there too.