Android - Retrieve a path of an picked image - java

I have java code to pick an image from gallery or camera. In this code when user picks an image then it gets cropped into 200x200 size. I am looking for absolute path of that cropped image and I want to move that cropped image into SD card. But I am not getting the path with file extension. When I tried to get path then it is returning path with file name including random number like below.
/storage/media/865412
I am unable to move this file. I need the absolute path with the file extension.
ProfileInfo.java
public class ProfileInfo extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_info);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.profile_pic);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
Toast.makeText(getApplicationContext(),
photo.getWidth()+"x"+photo.getHeight()+"\n"+photo.getByteCount()+"\n",
0).show();
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
Toast.makeText(getApplicationContext(),mImageCaptureUri.getPath(), 0).show();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
}
profile_info.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/activity_bg_color"
android:paddingBottom="0dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.beproject.ourway.ProfileInfo" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:alpha="0.7"
android:text="Tap on image to change (Optional)"
android:textColor="#FFFFFF" />
<ImageView
android:id="#+id/profile_pic"
android:layout_width="156dp"
android:layout_height="156dp"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:adjustViewBounds="true"
android:src="#drawable/user" />
<EditText
android:id="#+id/your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:gravity="center_horizontal"
android:hint="Your name..."
android:textAlignment="center"
android:textColorHint="#DFDFDF" >
</EditText>
</LinearLayout>
<Button
android:id="#+id/skip_image_upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:background="#drawable/flat_button_selector"
android:text="Skip"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/image_upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="73dp"
android:background="#drawable/flat_button_selector"
android:onClick="uploadImage"
android:text="Upload"
android:textColor="#FFFFFF" />
</RelativeLayout>
CropOptionAdapter.java
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}
CropOption.java
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
crop_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>

You don't necessarily need the absolute file path in order to copy the file, because you can open an InputStream from the Uri directly and copy the contents from that:
void copyFileFromUri(Uri sourceUri, String destFilePath) throws IOException
{
InputStream in = getContentResolver().openInputStream(sourceUri);
File outFile = new File(destFilePath);
OutputStream out = new FileOutputStream(outFile);
copyFile(in, out);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
copyFile() function copied from answer to this question

Related

How to add button in Zxing Scanner Camera View?

I want to add a button in Zxing Scanner Camera View, tried many procedures and seen many answers related to add button in Zxing library and refered this " How to add buttons in Zxing Scanner Camera View " , but it's not working anyone guide me, Thanks in advance, My code is
MainActivity.Java
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
final static String serverUrl = "";
private ZXingScannerView scannerView;
String res;
ImageButton img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Log.e("OnCreate", "OnCreated");
//ZXingScannerView zxing=(ZXingScannerView)findViewById(R.id.zxscan);
scannerView = (ZXingScannerView) findViewById(R.id.zxscan);
img=(ImageButton)findViewById(R.id.img1);
//scannerView.setResultHandler(this);
//scannerView.startCamera();
//zxing.addView(scannerView);
//setContentView(scannerView);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
Log.e("M", "Permission");
Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();
} else {
Log.e("R", "Permission");
requestPermission();
}
}
}
private boolean checkPermission() {
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
Log.e("Successfull", "Success");
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted) {
Log.e("accpt", "Accpt");
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
} else {
Log.e("ntaccpt", "Not Acpt");
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onResume() {
super.onResume();
int capi = android.os.Build.VERSION.SDK_INT;
if (capi >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if (scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
scannerView = null;
}
#Override
public void handleResult(final Result result) {
res = result.getText();
Log.d("Scanner Result", result.getText());
Log.d("Scanner Result", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
GetText();
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setMessage(result.getText());
AlertDialog alert = builder.create();
alert.show();
}
public void GetText() //throws UnsupportedEncodingException
{
String data = res;
String text = "";
BufferedReader reader = null;
Log.e("Datafirst", data);
String requesturi = serverUrl + data;
// Send data
try {
URL url = new URL(requesturi);
Log.e("DataSecond", requesturi);
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Log.e("Data Third", data);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
}
text = sb.toString();
} catch (Exception ex) {
Log.e("Exceptionio", "Error", ex);
ex.printStackTrace();
} finally {
try {
reader.close();
Log.e("Closed", "Closed");
} catch (Exception ex) {
Log.e("Except2", "Error", ex);
ex.printStackTrace();
}
}
Log.e("setText", data);
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<me.dm7.barcodescanner.zxing.ZXingScannerView
android:id="#+id/zxscan"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/img1"
android:layout_marginBottom="15dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:src="#drawable/imgbut"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Try my code, It will look like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:orientation="vertical"
tools:context="com.package.name.TakeSingleScanActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarAdjustScan"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="56dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/titleToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:layout_weight="1"
android:maxLines="1"
android:textColor="#color/white"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dp"
android:id="#+id/searchAdjustBtn"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:maxLines="1"
android:text="SEARCH "
android:textColor="#color/white"
android:textSize="13dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/textv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Point at any barcode to scan"
android:textColor="#color/white"
android:textSize="14sp"
android:textStyle="normal" />
<RelativeLayout
android:layout_marginBottom="120dp"
android:layout_below="#+id/textv"
android:id="#+id/relative_scan_take_single"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:background="#color/colorPrimaryDark"
android:layout_height="120dp"
android:orientation="horizontal">
<Button
android:id="#+id/doneBtn"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:text="Done"
android:textAllCaps="true"
android:textColor="#color/white"
android:textSize="22dp" />
</LinearLayout>
</RelativeLayout>
Java code for Scanner :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_single_scan);
init();
}
private void init() {
//Scanner
mScannerView = new ZXingScannerView(this);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative_scan_take_single);
rl.addView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setSoundEffectsEnabled(true);
mScannerView.setAutoFocus(true);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.e(TAG, rawResult.getText()); // Prints scan results
Log.e(TAG, rawResult.getBarcodeFormat().toString());
Log.e("SCAN_RESULT", "" + rawResult.getText());
//dataSingle.put("0",rawResult.getText());
}

How to upload images to firebase storage from tabbed actvity?

I want my newfeed.java tab to allow users to choose an image from gallery and > upload it to the firebase storage. Also, how to retrieve these images and >display in a listview ?
Newfeed.java
import static android.app.Activity.RESULT_OK;
public class NewfeedTab extends Fragment {
private static final int PICK_IMAGE_REQUEST = 234;
private StorageReference mStorageRef;
private EditText story;
private ImageButton choose;
private ImageButton upload;
private Uri filePath;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news_feed, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
story = (EditText)rootView.findViewById(R.id.et_story);
choose = (ImageButton)rootView.findViewById(R.id.imageButton_choose);
upload = (ImageButton)rootView.findViewById(R.id.imageButton_upload);
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null){
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference picsRef = mStorageRef.child("images/pic.jpg");
picsRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(),"Story posted",Toast.LENGTH_SHORT);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(),"Story couldn't be posted",Toast.LENGTH_SHORT);
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
}
}
}
The app closes after selecting the image from gallery. NewfeedTab.java is a fragment of tabbed activity.
newsfeed.xml
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.seven.pprs.bloodlink.TabActivity$PlaceholderFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/et_story"
android:layout_toStartOf="#+id/imageButton_choose"
android:hint="Share your stories here" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_file_upload_black_24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:id="#+id/imageButton_upload" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:dividerHeight="1dp"
android:divider="#android:color/holo_red_dark"
android:id="#+id/list_of_posts"
android:layout_marginBottom="16dp"
android:layout_below="#+id/et_story" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_add_a_photo_black_24dp"
android:layout_alignBottom="#+id/imageButton_upload"
android:layout_toStartOf="#+id/imageButton_upload"
android:id="#+id/imageButton_choose" />
Do you have read permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

populating alert dialog with list view,JSON

I am trying to fill an alert dialog with a JSON response how ever i am getting the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
i have inflated the list view in the onCreate as other posts suggest
i have included all relevant xml and java code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckedTextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:paddingLeft="?listPreferredItemPaddingLeft"
android:paddingRight="?listPreferredItemPaddingRight"
android:textAppearance="?textAppearanceListItemSmall" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listviewResp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="15dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
public class QueueStatusFragment extends Fragment{
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private TextView txtQueue;
private TextView txtCust;
private TextView txtTime;
private TextView txtBranch;
private String urlString;
private Button btnLeave;
private int reasonId;
ListView list;
public QueueStatusFragment()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_queuestatus, container, false);
txtQueue = (TextView) v.findViewById(R.id.txtQueue);
txtTime = (TextView) v.findViewById(R.id.txtTime);
txtCust = (TextView) v.findViewById(R.id.txtCust);
txtBranch = (TextView) v.findViewById(R.id.txtBranch);
list=(ListView)v.findViewById(R.id.listviewResp);
btnLeave = (Button) v.findViewById(R.id.btnLeave);
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/queueDetails/" + globalVariable.getCustId();
new ProcessJson().execute(urlString);
System.out.println("works");
btnLeave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/reasons";
new getReasons().execute(urlString);
for(int i = 0; i < oslist.size();i++)
{
String id = oslist.get(i).get("id");
System.out.println(id);
}
}
});
alertDialog.show();
// SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
//String urlString1 = "http://172.20.10.5:1012/easyQ.svc/rest/leaveQueue";
// new JsonHandler().execute(urlString1);
//System.out.println("works");
}
});
// Inflate the layout for this fragment
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private class ProcessJson extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
String[] array = stream.split(",");
String part1 = array[1];
String part2 = array[2];
String part3 = array[3];
String part4 = array[4];
String queueId = array[5];
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setQueueId(queueId);
if (part1 != null && part2 != null && part3 != null) {
int minutes = (int) Integer.parseInt(part1) / 60;
txtBranch.append("Branch Name: " + part4);
txtQueue.append("Service Name: " + part3);
txtCust.append("Queue Position: " + part2);
txtTime.append("Waiting Time: " + minutes + " minutes");
}
}
}
}
private class getReasons extends AsyncTask<String, Void, String>{
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null)
{
try
{
JSONObject object = new JSONObject(stream);
JSONArray array = object.getJSONArray("reasonsResult");
for(int i = 0 ; i < array.length(); i++) {
JSONObject reasonObj = array.getJSONObject(i);
String ID = reasonObj.getString("reason_leaving_id");
String reason = reasonObj.getString("description");
HashMap<String, String> map = new HashMap<String, String>();
map.put("description", reason);
map.put("id", ID);
oslist.add(map);
}
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
for(int i = 0; i < oslist.size(); i++)
{
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.dialog_list,
new String[] { "description"}, new int[] {
R.id.text1});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String branchId = oslist.get(+position).get("id");
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setBranchId(branchId);
Fragment fragment = null;
fragment = new JoinFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
});
}
alertDialog.show();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
}
private class JsonHandler extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
System.out.println("sssss" + globalVariable.getQueueId() + globalVariable.getCustId());
JSONObject sender = new JSONObject();
try {
sender.put("queueid", globalVariable.getQueueId());
sender.put("customerid", globalVariable.getCustId());
//sender.put("reasonid",);
} catch (JSONException e) {
e.printStackTrace();
}
stream = hh.POST(urlString, sender);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
if (stream.equals("\"Successful\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Successfully left Queue", Toast.LENGTH_LONG).show();
Fragment fragment=null;
fragment=new HomeFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
} else if (stream.equals("\"Not Exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Unable to leave Queue", Toast.LENGTH_LONG).show();
} else if (stream.equals("\"Not exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Not in queue", Toast.LENGTH_LONG).show();
}
}
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment" >
<TextView
android:id="#+id/txtBranch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="hello"
android:layout_marginTop="100dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtQueue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello1"
android:layout_marginTop="160dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello2"
android:gravity="center|left"
android:layout_marginTop="44dp"
android:layout_centerInParent="false"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtQueue"
android:layout_alignStart="#+id/txtQueue" />
<TextView
android:id="#+id/txtCust"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello3"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_marginTop="47dp"
android:layout_centerInParent="false"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtTime"
android:layout_alignStart="#+id/txtTime" />
<Button
android:id="#+id/btnLeave"
android:layout_width="312dp"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:gravity="center"
android:text="Leave Queue"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_marginBottom="65dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I think your problem is in your fragment_queuestatus there is no Listview. Which you add the previous layout. That why it's not get the listview and when you try to set the adapter it's thing you set something in a NULL object. So, Add the ListView in the fragment_queuestatus layout. That will solve the problem.

How to navigate from QR Code Reader to Paticular URL?

Project is working fine But my problem is How to navigate from QR Code Reader to Particular URL. what is code to navigate please anyone tell me and help me.
AndroidBarcodeQrExample.java
public class AndroidBarcodeQrExample extends Activity {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scanQR(View v) {
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/scanner"
android:layout_width="250dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_margin="10dp"
android:gravity="center"
android:onClick="scanQR"
android:text="QR Code"
android:textSize="18dp" >
</Button>
</LinearLayout>
The code to open url in browser is as follow:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("Your url here"));
startActivity(browserIntent);

Why am I not able to press the buttons when I come into the page?

public class Uploads extends Activity implements OnClickListener {
ImageView btnAllShops, btnFavourites, btnUploads, btnSettings, btnBuys,
btnTakePhoto;
GridView gvUploads;
PhotoDbAdapter ourHelper;
private String description, category, price, imagepath;
final static int cameraData = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_uploads);
findViewById();
onBackPressed();
sdcard();
}
private void findViewById() {
gvUploads = (GridView) findViewById(R.id.gvUploads);
btnAllShops = (ImageView) findViewById(R.id.btnAllShops);
btnFavourites = (ImageView) findViewById(R.id.btnFavourites);
btnUploads = (ImageView) findViewById(R.id.btnUploads);
btnSettings = (ImageView) findViewById(R.id.btnSettings);
btnBuys = (ImageView) findViewById(R.id.btnBuys);
btnTakePhoto = (ImageView) findViewById(R.id.btnTakePhoto);
btnAllShops.setOnClickListener(this);
btnFavourites.setOnClickListener(this);
btnUploads.setOnClickListener(this);
btnSettings.setOnClickListener(this);
btnBuys.setOnClickListener(this);
btnTakePhoto.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
Intent goMain = new Intent(getApplicationContext(),
EditUploads.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bs);
goMain.putExtra("byteArray", bs.toByteArray());
startActivity(goMain);
}
}
private void sdcard() {
setContentView(R.layout.activity_uploads);
// Set up an array of the Thumbnail Image ID column we want
String[] projection = { MediaStore.Images.Thumbnails._ID };
// Create the cursor pointing to the SDCard
cursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, // Which
// columns
// to
// return
null, // Return all rows
null, MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView gvuploads = (GridView) findViewById(R.id.gvUploads);
gvuploads.setAdapter(new ImageAdapter(this));
}
private class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount() {
return cursor.getCount();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_XY);
picturesView.setPadding(10, 10, 10, 10);
picturesView
.setLayoutParams(new GridView.LayoutParams(266, 266));
} else {
picturesView = (ImageView) convertView;
}
return picturesView;
}
}
private Cursor cursor;
// Column index for the Thumbnails Image IDs.
private int columnIndex;
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnAllShops:
Intent iA = new Intent(getApplicationContext(), AllShops.class);
startActivity(iA);
break;
case R.id.btnFavourites:
Intent iF = new Intent(getApplicationContext(), Favourites.class);
startActivity(iF);
break;
case R.id.btnUploads:
Intent iU = new Intent(getApplicationContext(), Uploads.class);
startActivity(iU);
break;
case R.id.btnSettings:
Intent iS = new Intent(getApplicationContext(),
SettingsActivity.class);
startActivity(iS);
break;
case R.id.btnBuys:
Intent iBuy = new Intent(getApplicationContext(), Buys.class);
startActivity(iBuy);
break;
case R.id.btnTakePhoto:
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
}
before i added the grid-view layout i was able to use the button functions. However, after i inserted the grid-view layout, all i can do is just scroll through the images on the grid-view. What do i do so that i can both scroll through the images and also use the buttons? Thanks
public class Mobile extends Activity {
PhotoDbAdapter ourHelper;
ImageView grid_item_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mobile);
grid_item_image = (ImageView) findViewById(R.id.grid_item_image);
PhotoDbAdapter getImage = new PhotoDbAdapter(this);
getImage.open();
String getImagepathe = getImage.getImagePath();
Toast.makeText(this, getImagepathe, Toast.LENGTH_LONG).show();
int id = getResources().getIdentifier(getImagepathe, null, null);
grid_item_image.setImageResource(id);
Intent mobile = new Intent(getApplicationContext(), Uploads.class);
startActivity(mobile);
}
}
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:src="#drawable/sh_uploads" />
<ImageView
android:id="#+id/btnTakePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/hbtn_camera" />
</LinearLayout>
<GridView
android:id="#+id/gvUploads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/bottomBar"
android:layout_below="#+id/linearLayout1"
android:numColumns="3"
tools:listitem="#layout/mobile" >
</GridView>
<LinearLayout
android:id="#+id/bottomBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/btnAllShops"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_home" />
<ImageView
android:id="#+id/btnFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_fave" />
<ImageView
android:id="#+id/btnBuys"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_buys" />
<ImageView
android:id="#+id/btnUploads"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_uploads" />
<ImageView
android:id="#+id/btnSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:contentDescription="#null"
android:src="#drawable/sbtn_settings" />
</LinearLayout>
If the images are into the grid, maybe this helps:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if(v.getId() == btnFavourites.getId()){
//Something happen
}
}
});

Categories