How to upload multi-images from Android to Spring Server? - android

I want to upload multi-images from Android to Spring Server, using Retrofit2, but it is not working.
I refer to this website: https://futurestud.io/tutorials/retrofit-2-how-to-upload-multiple-files-to-server
My code is below:
package com.example.gdtbg.fileupload;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import gun0912.tedbottompicker.TedBottomPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST = 100;
private int PICK_IMAGE_FROM_GALLERY_REQUEST = 1;
ArrayList<Uri> test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test = new ArrayList<Uri>();
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST);
}
Button uploadbutton = (Button) findViewById(R.id.submit);
uploadbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(MainActivity.this)
.setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
#Override
public void onImagesSelected(ArrayList<Uri> uriList) { //this function return Uri file uri type("file://")
uploadAlbum(uriList);
}
})
.setSelectMaxCount(3)
.setEmptySelectionText("선택된게 없습니다! 이미지를 선택해 주세요!")
.create();
tedBottomPicker.show(getSupportFragmentManager());
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
return;
}
}
}
#NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
public static Uri getImageContentUri(Context context, File imageFile) throws FileNotFoundException{
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) throws FileNotFoundException {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
ContentResolver cr = getContentResolver();
Uri castedUri = getImageContentUri(getApplicationContext(), file);
// create RequestBody instance from file
try {
Log.d("testfile", castedUri.toString());
if(cr.getType(castedUri)==null)
{
Log.d("testfile", "content uri is null");
Log.d("testfile", cr.getType(castedUri).toString());
}
else
{
Log.d("testfile", "content uri is not null");
Log.d("testfile", cr.getType(castedUri).toString());
}
RequestBody requestFile =
RequestBody.create(MediaType.parse(cr.getType(castedUri)),file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void uploadAlbum(List<Uri> fileUris) {
final EditText description = (EditText) findViewById(R.id.editText);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://192.168.0.3:8089/Test/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient client = retrofit.create(UserClient.class);
ArrayList<MultipartBody.Part> parts = new ArrayList<>();
Log.d("giduck", "Hello World!");
Log.d("giduck", "" + fileUris.size());
for (int i = 0; i < fileUris.size(); i++) {
Log.d("sendTest", fileUris.get(i).toString());
Log.d("sendTest", "" + fileUris.size());
try {
parts.add(prepareFilePart(""+i, fileUris.get(i)));
} catch (Exception e) {
e.printStackTrace();
}
Log.d("giduckfinal", "" + fileUris.get(i).toString());
Log.d("giduckfinal", "in loop");
}
Log.d("giduckfinal", "this is final position 1");
Call<ResponseBody> call = client.uploadAlbum(
createPartFromString(description.getText().toString()),
parts );
Log.d("final", "this is final position 2");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "Success that Upload Image to Server", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Fail that Upload to Server", Toast.LENGTH_SHORT).show();
}
});
}
}
 
 
package com.example.gdtbg.fileupload;
import java.util.List;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
/**
* Created by gdtbg on 2017-06-21.
*/
public interface UserClient {
/* #Multipart
#POST("uploadForm")
Call<ResponseBody> uploadPhoto(
#Part("description") RequestBody description,
#Part MultipartBody.Part photo
);
#Multipart
#POST("uploadForm")
Call<ResponseBody> uploadPhotos(
#Part MultipartBody.Part profile,
#Part MultipartBody.Part panorama
); */
#Multipart
#POST("uploadForm")
Call<ResponseBody> uploadAlbum(
#Part("description") RequestBody description,
#Part List<MultipartBody.Part> files
);
}

i'm using this code and it works for me
upload.php
<?php
$attachment = $_FILES['attachment'];
define ("MAX_SIZE","9000");
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// Method to extract the uploaded file extention
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Method to extract the uploaded file parameters
function getFileAttributes($file)
{
$file_ary = array();
$file_count = count($file['name']);
$file_key = array_keys($file);
for($i=0;$i<$file_count;$i++)
{
foreach($file_key as $val)
{
$file_ary[$i][$val] = $file[$val][$i];
}
}
return $file_ary;
}
// Check if the POST Global variable were set
if(!empty($attachment) && isset($_POST['dirname']))
{
$dirname = $_POST['dirname'];
$uploaddir = "/var/www/html/uploads/".$dirname."/";
//Check if the directory already exists.
if(!is_dir($uploaddir)){
//Directory does not exist, so create it.
mkdir($uploaddir, 0777, true);
}
$file_attributes = getFileAttributes($attachment);
//print_r($file_attributes);
$count = count($file_attributes);
$response["status"] = array();
$response["count"] = $count; // Count the number of files uploaded
array_push($response["status"], $file_attributes);
$file_dirs = array();
foreach($file_attributes as $val)
{
$old_file = $val['name'];
$ext = getExtension($old_file);
$ext = strtolower($ext);
if(in_array($ext, $valid_formats))
{
$response["files"] = array();
$new_file = date('YmdHis',time()).mt_rand(10,99).'.'.$ext;
move_uploaded_file($val['tmp_name'], $uploaddir.$new_file);
$file_dirs[] = 'http://192.168.50.10/gallery/uploads/'.$dirname."/".$new_file;
}
else
{
$file_dirs[] = 'Invalid file: '.$old_file;
}
}
array_push($response["files"], $file_dirs);
echo json_encode($response);
}
?>
then in xml put this
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="toegy.com.testmultiupload.MainActivity">
<TextView
android:id="#+id/select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="select"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
and in your activity put this
public class MainActivity extends AppCompatActivity {
TextView select;
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
select = (TextView) findViewById(R.id.select);
pDialog = new ProgressDialog(MainActivity.this);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && null != data) {
Log.e("++data", data.getClipData().getItemCount() + "");
List<Uri> uriList = new ArrayList<Uri>();
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
Uri selectedImage = data.getClipData().getItemAt(i).getUri();
Log.e("uri",selectedImage+"");
uriList.add(i,selectedImage);
}
uploadPhotos(uriList,"photos");
} else {
Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
public void uploadPhotos(final List<Uri> uriList, final String folderName) {
pDialog.setMessage("uploading ...............");
pDialog.show();
List<MultipartBody.Part> parts = new ArrayList<>();
for (Uri uri : uriList) {
parts.add(prepareFilePart("attachment[]", uri)); // Note: attachment[]. Not attachment
}
RequestBody requestBodyFolderName = createPartFromString(folderName);
HashMap<String, RequestBody> requestMap = new HashMap<>();
requestMap.put("dirname", requestBodyFolderName); // Note: dirname
FileUploadService service = RetrofitClient.getApiService();
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(requestMap, parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 200) {
// multiple dynamic uploads were successful
Log.e("status", "done");
pDialog.hide();
} else {
Log.e("status", "not done " + response.code());
pDialog.hide();
}
Toast.makeText(MainActivity.this,response.code()+"",Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("status", "not done " + t.toString());
}
});
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = new File(getRealPathFromURI(fileUri));
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
}
}
it will work prefect

Related

Sending SMS using code sends duplicate SMS

I just start android with a small project. I am trying to do the following:
STEP 1. get the response from an url [https://client.itscholarbd.com/getsmsdata]
STEP 2. send sms based on the data received from step 1
STEP 3. DELETE the data which is processed. i.e. sms is sent. this is done by DELETE request with ID
STEP 4. REPEAT from STEP 1.
Here is my code:
package com.pkappstudio.smsv20;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BackgroundService extends Service {
private static final String SMS_SENT_ACTION = "com.pkappstudio.smsv20.SMS_SENT";
private static final String EXTRA_NUMBER = "number";
private static final String EXTRA_MESSAGE = "message";
private RequestQueue requestQueue;
private SmsManager smsManager;
private BroadcastReceiver resultsReceiver;
private boolean start = true;
private String base_url = "https://client.itscholarbd.com";
#Override
public void onCreate() {
super.onCreate();
smsManager = SmsManager.getDefault();
resultsReceiver = new SmsResultReceiver();
IntentFilter intentFilter = new IntentFilter(SMS_SENT_ACTION);
registerReceiver(resultsReceiver, intentFilter);
requestQueue = Volley.newRequestQueue(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String macAddress = intent.getStringExtra("MAC");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_ID)
.setContentTitle("SMS v2.0-Service Running")
.setContentText(macAddress)
.setSmallIcon(R.drawable.ic_message)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//our action starts here
if (start) {
jsonParse();
}
handler.postDelayed(this, 8000);
}
}, 8000);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(resultsReceiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void jsonParse() {
String url = base_url+"/getsmsdata?mac=" + App.MAC_ADDRESS;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("response");
getData(array);
Log.i("reposnse", array.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("JSONDATA", error.toString());
}
});
requestQueue.add(request);
}
private void getData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
String string = object.getString("phone");
int id = Integer.parseInt(object.getString("id"));
int user_id = Integer.parseInt(object.getString("user_id"));
String message = object.getString("message");
double smsLength = message.length();
double perSmsLength = 160;
double FakeQuantity = smsLength / perSmsLength;
int quantity = (int) Math.ceil(FakeQuantity);
start = false;
Log.i("debug", message);
sendNextMessage(id, string, message, quantity, user_id);
deleteFromDB(id);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void deleteFromDB(int id) {
String url = base_url+"/deletedata?id=" + id + "&mac=" + App.MAC_ADDRESS;
StringRequest request = new StringRequest(Request.Method.DELETE, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("resonse", response);
jsonParse();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("resonse", error.toString());
}
});
requestQueue.add(request);
}
private void sendStatusToServer(JSONArray array) {
String url = base_url+"/addsmslog?mac=" + App.MAC_ADDRESS;
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, array, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("response", error.toString());
}
});
requestQueue.add(request);
}
private void sendNextMessage(int id, String number, String message, int quantity, int user_id) {
int requestCode = id + Integer.parseInt(number);
Intent sentIntent = new Intent(SMS_SENT_ACTION);
sentIntent.putExtra(EXTRA_NUMBER, number);
sentIntent.putExtra(EXTRA_MESSAGE, message);
sentIntent.putExtra("quantity", quantity);
sentIntent.putExtra("user_id", user_id);
sentIntent.putExtra("id", id);
PendingIntent sentPI = PendingIntent.getBroadcast(this,
requestCode,
sentIntent,
PendingIntent.FLAG_ONE_SHOT);
// Send our message.
Log.i("dValues", id + " " + number + " " + message);
smsManager.sendTextMessage(number, null, message, sentPI, null);
}
private class SmsResultReceiver extends BroadcastReceiver {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
// Get the result action.
String action = intent.getAction();
// Retrieve the recipient's number and message.
String number = intent.getStringExtra(EXTRA_NUMBER);
String message = intent.getStringExtra(EXTRA_MESSAGE);
int user_id = intent.getIntExtra("user_id", 0);
int quantity = intent.getIntExtra("quantity", 0);
String sent_result;
if (SMS_SENT_ACTION.equals(action)) {
start = true;
int resultCode = getResultCode();
sent_result = translateSentResult(resultCode);
JSONObject object = new JSONObject();
JSONArray array = new JSONArray();
try {
object.put("phone", number);
object.put("message", message);
object.put("quantity", quantity);
object.put("user_id", user_id);
object.put("status", sent_result);
object.put("delivered", null);
} catch (Exception e) {
e.printStackTrace();
}
array.put(object);
sendStatusToServer(array);
Log.i("dResponse", array.toString());
}
}
String translateSentResult(int resultCode) {
switch (resultCode) {
case Activity.RESULT_OK:
return "Sent";
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
return "Failed";
case SmsManager.RESULT_ERROR_RADIO_OFF:
return "Radio off";
case SmsManager.RESULT_ERROR_NULL_PDU:
return "PDU Error";
case SmsManager.RESULT_ERROR_NO_SERVICE:
return "Error Service";
default:
return "Unknown error code";
}
}
}
}
Everything works like a charm. some data is being processed twice. Suppose. at step 1: we got the following json data:
{"response":[{"id":395,"phone":"01620010950","message":"testing! -
itscholarbd.com","user_id":1},{"id":396,"phone":"01673050495","message":"testing! - itscholarbd.com","user_id":1}]}
Then id: 395 is processed twice. I struggle with such problem for 2 days. at last I post here for any idea. Thanks in advance.
I guess that the problem is by calling jsonParse() again in your deleteFromDB(...) method:
private void deleteFromDB(int id) {
.......
.......
#Override
public void onResponse(String response) {
Log.i("resonse", response);
//here, I guess this is the problem
jsonParse();
}
......
......
}

Getting Error in onResponse in Retrofit

I am a newbie to the android world. I am trying to develop an app for my school project and stumble upon this issue. please someone help me.
My fragment code is bellow. Where I want to fill up a form with Image and upload to PHP, Mysql server for registration. But the app is crashing.
package com.dgdev.mtmicds;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dgdev.mtmicds.DbAccess.Remote.APIClient;
import com.dgdev.mtmicds.DbAccess.Remote.ApiInterface;
import com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_OK;
import static android.provider.MediaStore.Images.Media.*;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
/**
* A simple {#link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
View view;
AppCompatImageView imageView;
AppCompatEditText etFullname, etEmail, etDob, etMobile, etPsw, etRePsw, etAddr;
AppCompatButton btnRegister, btnCancel;
private static final int IMAGE_REQUEST = 7777;
Bitmap bitmap;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
imageView = (AppCompatImageView) view.findViewById(R.id.ProfileDP);
etFullname = (AppCompatEditText) view.findViewById(R.id.tvfullanme);
etEmail = (AppCompatEditText) view.findViewById(R.id.tvemail);
etDob = (AppCompatEditText) view.findViewById(R.id.tvdob);
etPsw = (AppCompatEditText) view.findViewById(R.id.tvpsw);
etRePsw = (AppCompatEditText) view.findViewById(R.id.tvpsw_re);
etAddr = (AppCompatEditText) view.findViewById(R.id.tvaddr);
etMobile = (AppCompatEditText) view.findViewById(R.id.tvmobile);
btnRegister = (AppCompatButton) view.findViewById(R.id.btnRegister);
btnCancel = (AppCompatButton) view.findViewById(R.id.btnCancel);
/*-----------------------------------------------------------------------------*/
/* this onClickListener will be responsible for getting image URI from gallery */
/*-----------------------------------------------------------------------------*/
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageFromGallery();
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
return view;
}
private void uploadData() {
String fullname = etFullname.getText().toString();
String dob = convertTOMysqlDate(etDob.getText().toString());
String mobile = etMobile.getText().toString();
String addr = etAddr.getText().toString();
String psw = etPsw.getText().toString();
String prof_pic = imageToString();
Toast.makeText(view.getContext(), dob, Toast.LENGTH_LONG).show();
ApiInterface apiInterface = APIClient.GetClient().create(ApiInterface.class);
Call<UserRegistrationModel> call = apiInterface.RegisterUser(fullname, dob, mobile, addr, psw, prof_pic);
call.enqueue(new Callback<UserRegistrationModel>() {
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
UserRegistrationModel res = response.body();
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<UserRegistrationModel> call, Throwable t) {
Toast.makeText(view.getContext(), "You are not able to talk to server!", Toast.LENGTH_LONG).show();
}
});
}
private String convertTOMysqlDate(String s) {
String $MysqlDateString;
String[] DateParts = s.split("/");
$MysqlDateString = DateParts[2] + "-" + DateParts[1] + "-" + DateParts[0];
return $MysqlDateString;
}
private void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = getBitmap(getActivity().getApplicationContext().getContentResolver(), path);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String imageToString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
byte[] ImageBytes = outputStream.toByteArray();
return Base64.encodeToString(ImageBytes, Base64.DEFAULT);
}
}
And I am getting bellow message in logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel.getStatus()' on a null object reference
at com.dgdev.mtmicds.ProfileFragment$3.onResponse(ProfileFragment.java:105)
Please Help me...I am a newbie...
Try this
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
if(response.isSuccessful()) {
UserRegistrationModel res = response.body();
if(res!=null) {
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(view.getContext(), "Didn't get response", Toast.LENGTH_LONG).show();
}
}
}
Your com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel is null. Check whether it is being alloted any value by getting in debug mode. Run the code step by step in debug mode and check how it is getting initialized.
Hint: Check this line of your code in debugger:
UserRegistrationModel res = response.body();

Preconditions.checkNotNull Android Null pointer Exception

I am trying to access my phone's internal storage to attach a file from internal storage. But anyhow I am getting an exception "java.lang.NullPointerException: uri at com.android.internal.util.Preconditions.checkNotNull". I have checked getCount method is not null. But still, i am facing this issue. what do I do?
**Code:**
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
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.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
public class User_Issue extends AppCompatActivity {
EditText estoreissue, estorename, edescribe;
Button b, btupload;
RequestQueue requestQueue;
TextView tvupload;
private static final int IMAGE_REQUEST_CODE = 3;
private static final int STORAGE_PERMISSION_CODE = 123;
private ImageView imageView;
private EditText etCaption;
private Uri filePath;
Bitmap bitmap;
int serverResponseCode = 0;
//final String uploadFilePath = "/mnt/Environment.getRootDirectory().getAbsolutePath()/";
//final String uploadFileName = "";
String upLoadServerUri = null;
// Create string variable to hold the Edit\Text Value.
String issue, storename, describe;
// Creating Progress dialog.
ProgressDialog progressDialog;
String HttpUrl = "http://10.238.4.153/user_issue.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user__issue);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = (ImageView)findViewById(R.id.imupload);
etCaption = (EditText)findViewById(R.id.etupload);
tvupload = (TextView) findViewById(R.id.tvupload);
estorename = (EditText) findViewById(R.id.editTextstorename);
estoreissue = (EditText) findViewById(R.id.editTextissue);
edescribe = (EditText) findViewById(R.id.editTextdescribe);
b = (Button) findViewById(R.id.button3);
btupload = (Button) findViewById(R.id.buttonupload);
tvupload.setText("Uploading File : 'mnt/Environment.getRootDirectory().getAbsolutePath()/" + "'");
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
requestStoragePermission();
// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(User_Issue.this);
progressDialog = new ProgressDialog(User_Issue.this);
btupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v==imageView)
{
Intent in=new Intent();
in.setType("imupload/*");
in.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(in, "Complete action using"), IMAGE_REQUEST_CODE);
}else if(v == btupload){
uploadMultipart();
}
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressDialog.setMessage("Please wait, while we upload your data to server");
progressDialog.show();
GetValueFromEditText();
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing response message coming from server.
Toast.makeText(User_Issue.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(User_Issue.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("storename", storename);
params.put("issue", issue);
params.put("describ", describe);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(User_Issue.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
});
}
// Creating method to get value from EditText.
public void GetValueFromEditText() {
storename = estorename.getText().toString().trim();
issue = estoreissue.getText().toString().trim();
describe = edescribe.getText().toString().trim();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
tvupload.setText("Path: ". concat(getPath(filePath)));
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void uploadMultipart() {
String caption = etCaption.getText().toString().trim();
//getting actual path
String path = getPath(filePath);
//uploading <code>
try {
String uploadID= UUID.randomUUID().toString();
new MultipartUploadRequest(this, uploadID, HttpUrl)
.addFileToUpload(path, "image") //Adding file
.addParameter("caption", caption) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public String getPath(Uri uri) {
Cursor cursor=null;
cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor!=null && cursor.getCount()>0) {
cursor.moveToFirst();
}
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
if(cursor!=null && cursor.getCount()>0) {
cursor.moveToFirst();
}
//cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
}
Logcat:
FATAL EXCEPTION: main
Process: com.example.mi.mikpiadmin, PID: 14255
java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.query(ContentResolver.java:474)
at android.content.ContentResolver.query(ContentResolver.java:434)
at com.example.mi.mikpiadmin.User_Issue.getPath(User_Issue.java:204)
at com.example.mi.mikpiadmin.User_Issue.uploadMultipart(User_Issue.java:187)
at com.example.mi.mikpiadmin.User_Issue$2.onClick(User_Issue.java:101)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
check Access permissions as required
Also make sure to use .checkDirExists() to see file availablity
You should make sure that filePath is not null before using it with getContentResolver().query()

Twitter Login in fragment doesn't work

I tried the same code in Activity and it worked but the same code in fragment doesn't work.
SignUpFragment.java:
package com.conversionbug.alltee;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
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.LoggingBehavior;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterAuthToken;
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.TwitterAuthClient;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import org.json.JSONObject;
import java.util.Arrays;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.conversionbug.alltee.Constants.ROOT_LOGIN;
import static com.conversionbug.alltee.Constants.ROOT_TOKEN;
import static com.conversionbug.alltee.Constants.SOCIAL_REGISTER;
import static com.facebook.FacebookSdk.getApplicationContext;
public class SignUpFragment extends Fragment implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
TextView loginTV;
Button nextActivity;
EditText name;
EditText email;
EditText password;
LinearLayout linear_main;
String googleName;
String googleEmail;
String googleUserAccessToken;
String googleUserSocialId;
String facebookEmail;
String facebookId;
String facebookName;
String facebookToken;
ImageButton facebook_icon1;
LoginButton facebook_sign_in_button1;
ImageButton google_plus_icon1;
SignInButton googleSignIn1;
ImageButton twitter_icon;
TwitterLoginButton twitter1;
CallbackManager callbackManager;
private GoogleApiClient googleApiClient1;
private static final int REQ_CODE = 9001;
GoogleSignInOptions signInOptions;
TwitterSession session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sign_up, container, false);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Twitter.initialize(getActivity()); //Twitter is initialized
loginTV = (TextView) view.findViewById(R.id.loginTV);
nextActivity = (Button) view.findViewById(R.id.nextActivity);
name = (EditText) view.findViewById(R.id.name);
email = (EditText) view.findViewById(R.id.email);
password = (EditText) view.findViewById(R.id.password);
linear_main = (LinearLayout) view.findViewById(R.id.linearMain1);
facebook_icon1 = (ImageButton) view.findViewById(R.id.facebook_icon1);
facebook_sign_in_button1 = (LoginButton) view.findViewById(R.id.facebook_sign_in_button1);
facebook_sign_in_button1.setReadPermissions(Arrays.asList("email"));
twitter1 = (TwitterLoginButton) view.findViewById(R.id.twitter1);
twitter_icon = (ImageButton) view.findViewById(R.id.twitter_icon);
google_plus_icon1 = (ImageButton) view.findViewById(R.id.google_plus_icon1);
googleSignIn1 = (SignInButton) view.findViewById(R.id.googleSignIn1);
facebook_sign_in_button1.setFragment(this);
signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
googleApiClient1 = new GoogleApiClient.Builder(getActivity())
//.enableAutoManage(getActivity() /* FragmentActivity */, 1, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions)
.build();
try {
session = TwitterCore.getInstance().getSessionManager().getActiveSession();
} catch (Exception exception) {
exception.printStackTrace();
}
facebook_icon1.setOnClickListener(this);
google_plus_icon1.setOnClickListener(this);
twitter_icon.setOnClickListener(this);
facebook_sign_in_button1.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
facebookToken = AccessToken.getCurrentAccessToken().getToken();
try {
facebookEmail = object.getString("email");
facebookId = object.getString("id");
facebookName = object.getString("name");
Toast.makeText(getActivity(), "Email: " + facebookEmail + " Id: " + facebookId + " Name: " + facebookName + " Access Token: " + facebookToken, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
FacebookRegisterTask facebookRegisterTask = new FacebookRegisterTask();
facebookRegisterTask.execute(SOCIAL_REGISTER);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,id,name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Login Cancel", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException e) {
Toast.makeText(getApplicationContext(), "Login Error", Toast.LENGTH_LONG).show();
}
});
loginTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
Fragment fragment = new LoginFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
}
});
nextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RegisterTask registerTask = new RegisterTask();
registerTask.execute(ROOT_LOGIN);
String nameValidation = name.getText().toString().trim();
String emailValidation = email.getText().toString().trim();
String passwordValidation = password.getText().toString().trim();
String namePattern = "[A-Za-z. ]+";
String emailPattern = "[a-z0-9._]+#[a-z]+\\.+[a-z]+";
if (nameValidation.matches(namePattern) && name.length() <= 255 && emailValidation.matches(emailPattern) && passwordValidation.length() >= 6) {
} else {
Snackbar snackbar = Snackbar.make(linear_main, "Wrong Username or Password !!!", Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);
textView.setTypeface(null, Typeface.BOLD);
textView.setTextSize(16f);
sbView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.red));
textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.white));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
else
textView.setGravity(Gravity.CENTER_HORIZONTAL);
snackbar.show();
}
}
});
twitter1.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
session = result.data;
String userName = session.getUserName().toString();
long userId = session.getId();
if(userName.isEmpty()) {
Toast.makeText(getActivity(), "Data isn't fetched", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getActivity(), "Login Successful with token: " + token + "\n secret: " + secret + "\n User Name: " + userName + "\n Id: " + userId, Toast.LENGTH_LONG).show();
}
/*getUserData();*/
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(), "Login Failure", Toast.LENGTH_LONG).show();
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Toast.makeText(getActivity(),"inside onActivityResult",Toast.LENGTH_LONG).show();
if (requestCode == REQ_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
Fragment fragment = getFragmentManager().findFragmentById(R.id.linearMain1);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
/*void getUserData() {
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback<String>() {
#Override
public void success(Result<String> result1) {
String s1 = result1.data.toString().toLowerCase();
if(s1.isEmpty()) {
Toast.makeText(getActivity(),"No EmailId",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getActivity(),"Email: "+s1,Toast.LENGTH_LONG).show();
}
}
#Override
public void failure(TwitterException exception) {
}
});
}
*/
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.facebook_icon1:
facebook_sign_in_button1.performClick();
break;
case R.id.google_plus_icon1:
signIn();
break;
case R.id.twitter_icon:
twitter1.performClick();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getApplicationContext(), "Connection failed G+", Toast.LENGTH_SHORT).show();
}
private void handleResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
googleName = account.getDisplayName();
googleEmail = account.getEmail();
googleUserAccessToken = account.getIdToken();
googleUserSocialId = account.getId();
Toast.makeText(getActivity(), "Name: " + googleName + " Email: " + googleEmail + " UserAccessToken: " + googleUserAccessToken + " UserSocialId " + googleUserSocialId, Toast.LENGTH_SHORT).show();
GoogleRegisterTask googleRegisterTask = new GoogleRegisterTask();
googleRegisterTask.execute(SOCIAL_REGISTER);
}
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient1);
startActivityForResult(intent, REQ_CODE);
}
#Override
public void onStart() {
super.onStart();
if (googleApiClient1 != null)
googleApiClient1.connect();
}
#Override
public void onStop() {
if (googleApiClient1 != null && googleApiClient1.isConnected()) {
googleApiClient1.disconnect();
}
super.onStop();
}
public class RegisterTask extends AsyncTask<String, Void, String> {
int responseCode;
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody postData = new FormBody.Builder()
.add("name", name.getText().toString())
.add("email", email.getText().toString())
.add("password", password.getText().toString())
.build();
Request request = new Request.Builder()
.url(params[0])
.post(postData)
.build();
Response response = client.newCall(request).execute();
responseCode = response.code();
String result = response.body().string();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
/*Toast.makeText(getActivity(), ""+s.toString(), Toast.LENGTH_SHORT).show();*/
if (responseCode == 200) {
AuthTask authTask = new AuthTask();
authTask.execute(ROOT_TOKEN);
Intent intent = new Intent(getActivity(), BottomNavigationActivity.class);
startActivity(intent);
} else if (s.toString().equals("{\"error\":\"Email id already taken\"}")) {
Toast.makeText(getActivity(), "Email-id already exist", Toast.LENGTH_LONG).show();
}
}
}
public class AuthTask extends AsyncTask<String, Void, String> {
int responseCode1;
#Override
protected String doInBackground(String... params1) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody postData = new FormBody.Builder()
.add("client_id", "2")
.add("client_secret", "oreOeeeN7ZYpCGNFMmW2W1OowPQVaJ92jadcl8B2")
.add("grant_type", "password")
.add("scope", "*")
.add("username", email.getText().toString())
.add("password", password.getText().toString())
.build();
Request request = new Request.Builder()
.url(params1[0])
.post(postData)
.build();
Response response = client.newCall(request).execute();
responseCode1 = response.code();
String result = response.body().string();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getActivity(), "" + s.toString(), Toast.LENGTH_LONG).show();
}
}
public class GoogleRegisterTask extends AsyncTask<String, Void, String> {
int responseCode;
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody postData = new FormBody.Builder()
.add("name", googleName)
.add("email", googleEmail)
.add("access_token", googleUserAccessToken)
.add("social_id", googleUserSocialId)
.add("social", "google_id")
.build();
Request request = new Request.Builder()
.url(params[0])
.post(postData)
.build();
Response response = client.newCall(request).execute();
responseCode = response.code();
String result = response.body().string();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (responseCode == 200) {
GoogleAuthTask googleAuthTask = new GoogleAuthTask();
googleAuthTask.execute(ROOT_TOKEN);
Intent intent = new Intent(getActivity(), BottomNavigationActivity.class);
startActivity(intent);
}
}
}
public class GoogleAuthTask extends AsyncTask<String, Void, String> {
int responseCode1;
#Override
protected String doInBackground(String... params1) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody postData = new FormBody.Builder()
.add("grant_type", "social")
.add("client_id", "2")
.add("client_secret", "oreOeeeN7ZYpCGNFMmW2W1OowPQVaJ92jadcl8B2")
.add("access_token", googleUserAccessToken)
.add("network", "google_id")
.build();
Request request = new Request.Builder()
.url(params1[0])
.post(postData)
.build();
Response response = client.newCall(request).execute();
responseCode1 = response.code();
String result = response.body().string();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getActivity(), "" + s.toString(), Toast.LENGTH_LONG).show();
}
}
public class FacebookRegisterTask extends AsyncTask<String, Void, String> {
int responseCode;
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody postData = new FormBody.Builder()
.add("name", facebookName)
.add("email", facebookEmail)
.add("access_token", facebookToken)
.add("social_id", facebookId)
.add("social", "facebook_id")
.build();
Request request = new Request.Builder()
.url(params[0])
.post(postData)
.build();
Response response = client.newCall(request).execute();
responseCode = response.code();
String result = response.body().string();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
FacebookAuthTask facebookAuthTask = new FacebookAuthTask();
facebookAuthTask.execute(ROOT_TOKEN);
Intent intent = new Intent(getActivity(), BottomNavigationActivity.class);
startActivity(intent);
Toast.makeText(getActivity(), "" + responseCode, Toast.LENGTH_LONG).show();
}
}
public class FacebookAuthTask extends AsyncTask<String, Void, String> {
int responseCode1;
#Override
protected String doInBackground(String... params1) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody postData = new FormBody.Builder()
.add("grant_type", "social")
.add("client_id", "2")
.add("client_secret", "oreOeeeN7ZYpCGNFMmW2W1OowPQVaJ92jadcl8B2")
.add("access_token", facebookToken)
.add("network", "facebook_id")
.build();
Request request = new Request.Builder()
.url(params1[0])
.post(postData)
.build();
Response response = client.newCall(request).execute();
responseCode1 = response.code();
String result = response.body().string();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getActivity(), "" + s.toString(), Toast.LENGTH_LONG).show();
}
}
} }
}
}
fragment_sign_up.xml:`
<FrameLayout
android:id="#+id/FrameLayout3"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="30dp"
android:layout_weight="1">
<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="#+id/twitter1"
android:layout_width="40dp"
android:layout_height="40dp"
android:visibility="gone"/>
<ImageButton
android:id="#+id/twitter_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/twitter_icon" />
</FrameLayout>`
After clicking on the button, it is redirecting to the twitter login page and after clicking on "connect" button, it simply returns to the fragment and doesn't show the Toast message. When I Click the button for the second time, it shows toast from failure method.
just add in your activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
yourcurrentfragment.onActivityResult(requestCode, resultCode, data);
}

Search all .pdf files present in the Android device

How can I search all .pdf and .doc files present in the Android device through a programmatic way?
Try using the below code. This will work for you.
public void walkdir(File dir) {
String pdfPattern = ".pdf";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pdfPattern)){
//Do whatever you want
}
}
}
}
}
To search on the whole SD card, call this function using:
walkdir(Environment.getExternalStorageDirectory());
Have a look at File, list.
Basically, get a starting Directory, call "list" with a filter(FilenameFilter), and then traverse sub directories. I am not sure if there is a one function that does all this for you.
Download source code from here (Open pdf file from SD card in android programmatically)
Add this Dependency in your Gradle file:
compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’
MainActivity.java:
package com.pdffilefromsdcard;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
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.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);
Log.e(“Position”, i + “”);
}
});
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
}
else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
}
else {
}
}
if (booleanpdf) {
booleanpdf = false;
}
else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
}
else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}
else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();
}
}
}
}
PdfActivity.java:
package com.pdffilefromsdcard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.io.File;
import java.util.List;
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}
Have a look at Stack Overflow question How can I get all audio files from the SD card on Android?.
Change the extension of the file like if you want all PDF files then extension ".pdf". Use this to get all PDF files from the device.
I found this method in my old project. This function will get you the PDF file and its information.
ManageFIleInfoForRecycler is my custom class to store the file information.
"storage" passes as "external".
public ArrayList<ManageFIleInfoForRecycler> fileList(String storage) {
ArrayList< ManageFIleInfoForRecycler > fileInfo = new ArrayList<>();
// Can give any file type, "doc", "pdf", etc.
String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
int j = 0;
Uri table = MediaStore.Files.getContentUri(storage);
// Column
String[] column = {MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.TITLE};
// Where
String where = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String[] args = new String[]{pdf};
Cursor fileCursor = getApplicationContext().getContentResolver().query(table, column, where, args, null);
String [] filesLists = new String[]{};
while (fileCursor.moveToNext()) {
int pathString = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
int nameIndex = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE);
String path = fileCursor.getString(pathString);
String name = fileCursor.getString(nameIndex);
ManageFIleInfoForRecycler temp = new ManageFIleInfoForRecycler();
temp.filePath = path;
temp.fileName = name;
fileInfo.add(temp);
}
return fileInfo;
}

Categories

Resources