I'm working on uploading multiple images. I can pick an image from my phone's sd card but when I'm trying to upload it to my database, the progress dialog shows "Uploading" only and after that it is being dismissed. Honestly, I'm not sure on my php code. Hope someone can help me :)
Here's my uploadActivity.java:
#SuppressLint("NewApi")
public class MainActivity extends Activity {
private Button upload, pick;
private ProgressDialog dialog;
MultipartEntity entity;
GridView gv;
int count = 0;
public ArrayList<String> map = new ArrayList<String>();
Bundle b;
TextView noImage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
b = getIntent().getExtras();
noImage = (TextView) findViewById(R.id.noImage);
upload = (Button) findViewById(R.id.btnUpload);
pick = (Button) findViewById(R.id.btnPicture);
gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this));
if (b != null) {
ArrayList<String> ImgData = b.getStringArrayList("IMAGE");
for (int i = 0; i < ImgData.size(); i++) {
map.add(ImgData.get(i).toString());
}
} else {
noImage.setVisibility(View.VISIBLE);
}
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ImageUploadTask()
.execute(count + "", "pk" + count + ".jpg");
}
});
pick.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i3 = new Intent(MainActivity.this, UploadActivity.class);
startActivity(i3);
}
});
}
class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url = "http://iguideph-001-btempurl.com/uploads.php";
int i = Integer.parseInt(params[0]);
Bitmap bitmap = decodeFile(map.get(i));
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("user_id", new StringBody("199"));
entity.addPart("club_id", new StringBody("10"));
entity.addPart("club_image", new ByteArrayBody(data,
"image/jpeg", params[1]));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
count++;
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public Bitmap decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
private class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return map.size();
}
public Object getItem(int position) {
return null;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85,
Gravity.CENTER));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(1, 1, 1, 1);
} else {
imageView = (ImageView) convertView;
}
imageView
.setImageBitmap(BitmapFactory.decodeFile(map.get(position)));
return imageView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
MainActivity.this.finish();
}
}
and here's my uploads.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['club_image'];
$userid=$_POST['user_id'];
$clubid=$_POST['club_id'];
require_once('connection.php');
$sql ="SELECT * FROM photos ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.jpg";
$actualpath = "http://iguideph-001-site1.btempurl.com/PhotoUpload/$path";
$sql = "INSERT INTO photos (image) VALUES ('$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
Related
I have an activity class along with customlistadapter inside customlist adapter.
I have a thread runouithread which give me error msg when i wrap it with ((Activity) context).runOnUiThread(new Runnable().
it throws the error msg at runtime has ClassCastException: android.app.Application cannot be cast to android.app.Activity.
So please some one help me.
public class CustomListAdapterfriend extends BaseAdapter {
List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;
URL urll;
HttpURLConnection connection;
InputStream input;
ViewHolder viewHolder;
//UI for Locations
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2,emasr,cn;
ArrayList<String> listItems;
ListView lv;
public int count1 = 0;
ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
int position2;
String id,emm;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email,session_ph,session_type,session_loc,connter;
ArrayList<HashMap<String, Object>> usersList,usersList1;
JSONParser jParser = new JSONParser();
int i ;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
private String imagePath = IP+"/social/upload/";
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_properties5 = IP+"/social/get_all_agen_like.php";
private static String url_all_properties1 = IP+"/social/get_lik_coun.php";
private static String url_all_properties6 = IP+"/social/get_all_agen_like3.php";
private static String url_all_properties7 = IP+"/social/get_all_dele_like.php";
private static String url_all_properties8 = IP+"/social/get_all_dele_uplike.php";
boolean isSelected;
int a,a1,b,b1;
//private static final String TAG_SUCCESS1 = "mass";
private static final String TAG_USER = "users";
private static final String TAG_PRO = "properties";
//private static final String TAG_PRO1 = "properties1";
// products JSONArray
JSONArray users = null;
//JSONArray users1 = null;
View view;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
// int position;
public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models) {
this.context = context;
this. models = models;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt,idas5,emasr,cn;
// public String id,emm;
public ImageView like;
public ImageView share;
/*public void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}*/
}
public void clear(){
if(models!=null)
models.clear();
}
#Override
public int getCount() {
return models.size();
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView( final int position, final View convertView, ViewGroup parent) {
// view = null;
view = convertView;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
sPref= context.getSharedPreferences("REAL", Context.MODE_PRIVATE);
session_email = sPref.getString("SESSION_UID","");
session_ph = sPref.getString("SESSION_PH","");
session_type = sPref.getString("SESSION_TYPE", "");
session_loc = sPref.getString("SESSION_LOC", "");
// lv=(ListView)view.findViewById(R.id.list);
pos = getItemViewType(position);
// long posn = getItemId(position);
// final int paps= (int)posn ;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fragment_home2, parent, false);
//your code
//add below code after (end of) your code
viewHolder.idas5 = (TextView) view.findViewById(R.id.hpid);
viewHolder. emasr= (TextView) view.findViewById(R.id.ema);
viewHolder.like=(ImageView)view.findViewById(R.id.likem);
viewHolder.share=(ImageView)view.findViewById(R.id.sharemsp);
viewHolder.cn = (TextView) view.findViewById(R.id.count);
viewHolder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
HashMap<String, Object> item = models.get(position);
String imagePath = (String)item.get("IMAGE").toString();
try {
urll = new URL(imagePath);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection = (HttpURLConnection) urll.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setDoInput(true);
try {
connection.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap immutableBpm = BitmapFactory.decodeStream(input);
if(immutableBpm !=null)
{
Bitmap mutableBitmap = immutableBpm.copy(Bitmap.Config.ARGB_8888, true);
View view = new View(context);
view.draw(new Canvas(mutableBitmap));
String path = Images.Media.insertImage(context.getContentResolver(), mutableBitmap, "Nur", null);
Uri uri = Uri.parse(path);
/* image = (ImageView) view.findViewById(R.id.feedImage1);
Drawable mDrawable = image.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
String path = Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);*/
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share, "Share Image!"));
}
else
{
Toast.makeText(context, "No image to share", Toast.LENGTH_LONG).show();
}
}
});
// viewHolder.share.setOnItemClickListener(this);
viewHolder.like.setBackgroundResource(R.drawable.like1);
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
// viewHolder.countt = (TextView) v.findViewById(R.id.count);
HashMap<String, Object> item = models.get(position);
viewHolder.idas5.setText((CharSequence) item.get("UIDAS"));
// id=(String) viewHolder.idas5.getText();
viewHolder.emasr.setText((CharSequence) item.get("EMAILM"));
id=(String) viewHolder.idas5.getText();
emm=(String) viewHolder.emasr.getText();
new LoadAllProducts().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
/*if( viewHolder.like.isSelected()){
viewHolder.like.setSelected(false);
//viewHolder.like.setBackgroundResource(R.drawable.like2);
new LoadAllProducts7().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
}
else if(!viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
// viewHolder.like.setBackgroundResource(R.drawable.like1);
new LoadAllProducts().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
}*/
}
});
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.like.setTag(position);
viewHolder.share.setTag(position);
final HashMap<String, Object> item = getItem(position);
/* name.setText(((String)item.get(R.id.name)));
*
*
*/
new LoadAllProducts78().execute();
// boolean isSelected = (Boolean) item.get("selected");
/*if (viewHolder.like.isSelected()) {
viewHolder.like.setSelected(false);
viewHolder.like.setBackgroundResource(R.drawable.like2);
} else if (!viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
viewHolder.like.setBackgroundResource(R.drawable.like1);
} */
pic = (ImageView) view.findViewById(R.id.profilePic);
name = (TextView) view.findViewById(R.id.name);
idas = (TextView) view.findViewById(R.id.hpid);
idas2 = (TextView) view.findViewById(R.id.hpid2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
msg = (TextView) view.findViewById(R.id.txtStatusMsg);
url = (TextView) view.findViewById(R.id.txtUrl);
image = (ImageView) view.findViewById(R.id.feedImage1);
idas.setText((CharSequence) item.get("UIDAS"));
viewHolder.cn.setText((CharSequence) item.get("COUN"));
// listItems.add(idas.getText().toString());
name.setText((CharSequence) item.get("NAME"));
timestamp.setText((CharSequence) item.get("TIME"));
msg.setText((CharSequence) item.get("MSG"));
url.setText((CharSequence) item.get("URL"));
//countt.setText((CharSequence) item.get("COUN"));
//count.setText("" + count1);
int w = image.getWidth();
int h = image.getHeight();
if (w > 1000)
{
a=w-1000;
b=w-a;
}
else
{
b=w;
}
if (h > 1000)
{
a1=h-1000;
b1=h-a1;
}
else
{
b1=h;
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.placeholder(R.drawable.profile_dummy)
//.error(R.drawable.ic_whats_hot)
.resize(50, 50)
// .centerCrop()
// .fit()
.into(pic);
/*Display display = getActivity().getWindowManager().
getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;*/
Picasso.with(context)
.load((String)item.get("IMAGE"))
//.load("IMAGE")
// .placeholder(R.drawable.ic_pages)
//.error(R.drawable.ic_home)
.resize(1000,image.getHeight())
.onlyScaleDown()
//.centerCrop()
// .fit().centerInside()
.into(image);
return view;
}
protected ContentResolver getContentResolver() {
// TODO Auto-generated method stub
return null;
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
/*Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("loc", "liked"));
params.add(new BasicNameValuePair("con", "1"));
params.add(new BasicNameValuePair("idtes", id));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties5, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All start: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
Log.d("Inside success...", json.toString());
connter = json.getString("loca");
Intent intent = ((Activity) context).getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
sPref.edit().putString("SESSION_UID", session_email).commit();
sPref.edit().putString("SESSION_TYPE", session_type).commit();
sPref.edit().putString("SESSION_PH", session_ph).commit();
sPref.edit().putString("SESSION_LOC", session_loc).commit();
((Activity) context).finish();
((Activity) context).overridePendingTransition(0, 0);
((Activity) context).startActivity(intent);
((Activity) context).overridePendingTransition(0, 0);
//Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();
}
else if (success== 5){
// no products found
Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
// pDialog.dismiss();
}
}
class LoadAllProducts78 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*pDialog = new ProgressDialog(Friendsprofile.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
*/
/*Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
//usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties6, "POST", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All bastart: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
viewHolder.like.setBackgroundResource(R.drawable.like1);
viewHolder.like.setSelected(true);
}
else if(success == 2) {
viewHolder.like.setBackgroundResource(R.drawable.like2);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
//pDialog.dismiss();
}
}
class LoadAllProducts22 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_properties1, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All Productgetting start: ", json.toString());
// Checking for SUCCESS TAG
try {
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
}
else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
class LoadAllProducts7 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("loc", "liked"));
params.add(new BasicNameValuePair("con", "1"));
params.add(new BasicNameValuePair("idtes", id));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties7, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All start: ", json.toString());
// Checking for SUCCESS TAG
try {
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
// new LoadAllProducts22().execute();
// products found
// Getting Array of Products
/*users = json.getJSONArray(TAG_PRO);
//users1 = json.getJSONArray(TAG_PRO1);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
//ImageView imageView = (ImageView) findViewById(R.id.profilePic);
// Storing each json item in variable
//String scpass = countt.getText().toString();
String uid = c.getString("uid1"); //from php blue
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put("UIDAS", uid); //from
map.put("PIC", pic);
usersList.add(map);
//usersList1.add(map);
// creating new HashMap
}*/
}
else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
Because while calling this constructor:
CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
You are providing getApplicationContext(). Try to provide context of the activity.
Edit 1:
Following the comments:
CustomListAdapterfriend adapter = new CustomListAdapterfriend(Friendsprofile.this, usersList); lv.setAdapter(adapter);
Modify the constructor of your adapter class from
public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
to
public CustomListAdapterfriend(Activity context, List<HashMap<String, Object>> models)
So whenever you call the constructor, the IDE will notify you to provide an Activity as a parameter, so the cast in your adapter won't fail.
While using in fragments try requireActivity() instead of getApplicationContext()
CustomListAdapterfriend(requireActivity(), List<HashMap<String, Object>> models)
I'm building a GIF Creator for my graduation project. What it is, when I try to select from the gallery a photo it just gets it to the view, I want to select more than one photo simultaneously not to go to select photo to get another picture. As well as that I've created a button so if the user changes their mind they can delete and start from scratch not having to restart the application however I don't know what the code is for that.
The main activity:
public class MainActivity extends AppCompatActivity {
/**
* this is the destination of the new GIF file, it will be saved directly in the SD card
* (internal storage) in a file named "test.gif"
*/
private static final String IMAGE_PATH = "/sdcard/test.gif";
private static final int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private boolean zoomOut = false;
private Button btnSelect;
private LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (root.getChildCount() == 0) {
return;
}
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(IMAGE_PATH);
outStream.write(generateGIF());
outStream.close();
Toast.makeText(MainActivity.this,
"GIF saved to " + IMAGE_PATH, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outStream != null) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
// the following code causes a crash "NullPointerException" :
// Point point = null; // --> the reason for the crash
// getWindowManager().getDefaultDisplay().getSize(point);
// int width = point.x;
// int height = point.y;
//
// ivImage.setMinimumWidth(width);
// ivImage.setMinimumHeight(height);
//
// ivImage.setMaxWidth(width);
// ivImage.setMaxHeight(height);
// ivImage.getLayoutParams().width = 20; // --> another crash happens here
// ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.WRAP_CONTENT,
GridLayout.LayoutParams.MATCH_PARENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
// setContentView(root);
// ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut = false;
} else {
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
private byte[] generateGIF() {
ArrayList<Bitmap> bitmaps = new ArrayList<>();
View v;
ImageView iv;
for (int i = 0; i < root.getChildCount(); i++) {
v = root.getChildAt(i);
if (v instanceof ImageView) {
iv = (ImageView) v;
bitmaps.add(((BitmapDrawable) iv.getDrawable()).getBitmap());
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
You can use custom library for multiple image pick like
1) MultiSelectRecyclerGalleryGridView
2) MultipleImagePick
like Kyle Shank answered
https://stackoverflow.com/a/19848052/5090511
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Or you can use something like that:
https://github.com/luminousman/MultipleImagePick
I have a sliding image that extends pageradapter. At first it was working. But when i open new activity then press the back button the app is crashing and i've got this error :
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 0 Pager id: malate.denise.chelsie.igphthesisbfinal:id/pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class malate.denise.chelsie.igphthesisbfinal.SlidingImage_Adapter
Here's my SlidingImage_Adapter.class
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Pictures> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context,ArrayList<Pictures> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimage_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
new DownloadImageTask(imageView).execute(IMAGES.get(position).getPhotopath());
// imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
notifyDataSetChanged();
}
#Override
public Parcelable saveState() {
return null;
}
and my AttractionInfo.class
public class AttractionInfo extends ActionBarActivity implements View.OnClickListener {
TextToSpeech tts;
TextView nameofplace,location,exact_address,operatinghours,info;
String nameofplace_s,location_s,exact_address_s,operatinghours_s,info_s,latlang_s,path_s,category_s;
ImageView play,rate,addtoplan,map;
ArrayList<Pictures> records;
private static ViewPager mPager;
private static int currentPage = 0;
String line=null;
private static int NUM_PAGES = 0;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_info);
map = (ImageView)findViewById(R.id.map);
map.setOnClickListener(this);
records=new ArrayList<Pictures>();
nameofplace = (TextView) findViewById(R.id.nameofplace);
info = (TextView) findViewById(R.id.info);
exact_address = (TextView) findViewById(R.id.exact_address);
location = (TextView)findViewById(R.id.location);
operatinghours=(TextView)findViewById(R.id.operatinghours);
play = (ImageView) findViewById(R.id.play);
rate = (ImageView) findViewById(R.id.rate);
addtoplan = (ImageView)findViewById(R.id.addtoplan);
addtoplan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
play.setOnClickListener(this);
rate.setOnClickListener(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
tts = new TextToSpeech(AttractionInfo.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
if (extras != null) {
nameofplace_s = extras.getString("name");
nameofplace.setText(nameofplace_s);
info_s = extras.getString("description");
info.setText(info_s);
exact_address_s = extras.getString("exactaddress");
exact_address.setText(exact_address_s);
location_s = extras.getString("location");
location.setText(location_s);
operatinghours_s=extras.getString("operatinghours");
operatinghours.setText(operatinghours_s);
latlang_s = extras.getString("latlang");
path_s=extras.getString("path");
category_s = extras.getString("category");
}
}
public void onStart() {
super.onStart();
fetchphoto bt = new fetchphoto();
bt.execute();
}
#Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
if (v == play) {
String speech1 = nameofplace.getText().toString();
String speech2 = info.getText().toString();
String speech = speech1 + "." + speech2;
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
} else if (v==rate){
Intent myIntent = new Intent(this, ListOfReviews.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if(v==addtoplan){
Intent myIntent = new Intent(this, AddPlan.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if (v == map){
Intent myIntent = new Intent(this, Map.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
myIntent.putExtra("latlang",latlang_s);
myIntent.putExtra("address",exact_address_s);
myIntent.putExtra("path",path_s);
startActivity(myIntent);
}
}
private void init() {
SlidingImage_Adapter adapter = new SlidingImage_Adapter(this,records);
for(int i=0;i<records.size();i++){
Pictures pics = records.get(i);
String pic = pics.getPhotopath();
adapter.notifyDataSetChanged();
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES =records.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},5000, 5000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
private class fetchphoto extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("cityname", nameofplace_s));
try
{
records.clear();
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getphoto.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pictures p = new Pictures();
p.setPhotoname(json_data.getString("photo_name"));
p.setPlacename(json_data.getString("place_name"));
p.setCategory(json_data.getString("category"));
p.setPhotopath(json_data.getString("path"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
init();
}
}
}
I've red some similar problems and learned that adding notifychanged may solved the problem but i dont where to place it. Hope you can help m . thanks
This is my activity code, when click on capture picture button, it will load camera from your phone. after i take a picture with camera, the picture will show at the imageView. Then i will click upload image picture button to upload my picture to server. Here the problem i faced, the code works well on all android version 4.4 and below, when i test this code with android 5.0, the picture taken from camera wasn't show on the imageView. I had tried many solution and yet keep fail. Can anyone help me with this? thank you.
Activity code
public class TestUpload extends Activity implements OnItemSelectedListener {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello camera";
private Uri fileUri;
private ImageView imgPreview;
private Button btnCapturePicture, btnUploadImage;
private EditText itemname;
private EditText description;
private EditText price;
private EditText contact;
private String randNum, uname;
Random random = new Random();
private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STR_LENGTH = 12;
private Spinner spinCat, spinLoc;
private String [] Category = {"IT Gadgets","Men Fashion","Women Fashion","Beauty","Sports","Cars and Motors","Furnitures","Music Instrument","Books","Property","Photography","Games and Toys","kids and Baby","Others"};
private String [] Location = {"Kuala Lumpur","Melacca","Johor","Selangor","Kelantan","Kedah","Negeri Sembilan",
"Pahang","Perak","Perlis","Penang","Sabah","Sarawak","Terengganu"};
private static final String TAG_SUCCESS = "success";
JSONParser2 jsonParser2 = new JSONParser2();
private static String url_create_image = "http://gemini888.tk/GP_trade_api_v2/image_connect/create_product.php";
private SweetAlertDialog pDialog;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_test);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#96ead7")));
ab.setDisplayHomeAsUpEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btn_camera);
btnUploadImage = (Button) findViewById(R.id.btn_upload);
itemname = (EditText) findViewById(R.id.input_upload_item_name);
description = (EditText) findViewById(R.id.input_item_desc);
price = (EditText) findViewById(R.id.upload_input_item_price);
contact = (EditText) findViewById(R.id.input_contact);
spinCat = (Spinner) findViewById(R.id.spin_category);
spinLoc = (Spinner) findViewById(R.id.spin_location);
ArrayAdapter<String> adapter_Category = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Category);
ArrayAdapter<String> adapter_Location = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Location);
adapter_Category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_Location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCat.setAdapter(adapter_Category);
spinLoc.setAdapter(adapter_Location);
spinCat.setOnItemSelectedListener(this);
spinLoc.setOnItemSelectedListener(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
//timeStamp = new SimpleDateFormat ("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
randNum = getRandomString();
//capture image button click event
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//capture image
captureImage();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//uploading the file to server
new UploadFileToServer().execute();
}
});
}
//capturing Camera image will lunch camera app request image capture
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Start image capture intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
//Receiving activity result method will be called after closing the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//if the result i capture image
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
//success capture image, display it on imageview
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
//user cancel image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
//failed to capture image
Toast.makeText(getApplicationContext(), "Sorry, failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
//Display image from a path to imageview
private void previewCapturedImage() {
imgPreview.setVisibility(View.VISIBLE);
//bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
//downsize image as it throws Outofmemory execption for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
//store the file url as it will be null after returning from camera app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save file url in bundle as it will be null on screen orientation change
outState.putParcelable("file_uri", fileUri);
}
//restore the fileUri again
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the Urifile
fileUri = savedInstanceState.getParcelable("file_uri");
}
//create file Uri to store image
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
//returning image
private File getOutputMediaFile(int type) {
//External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), UserFunctions.IMAGE_DIRECTORY_NAME);
//create the storage directory if it does not exist
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Failed create" + UserFunctions.IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
//Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + uname + randNum + ".jpg");
} else {
return null;
}
return mediaFile;
}
//upload image to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new SweetAlertDialog(TestUpload.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Picture uploading, please wait..");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void...params) {
String iname = itemname.getText().toString();
String des = description.getText().toString();
String iprice = price.getText().toString();
String icontact = contact.getText().toString();
String cat = spinCat.getSelectedItem().toString();
String loc = spinLoc.getSelectedItem().toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("name", iname));
param.add(new BasicNameValuePair("description", des));
param.add(new BasicNameValuePair("price", iprice));
param.add(new BasicNameValuePair("username", uname));
param.add(new BasicNameValuePair("category", cat));
param.add(new BasicNameValuePair("location", loc));
param.add(new BasicNameValuePair("timestamp", randNum));
param.add(new BasicNameValuePair("contact", icontact));
JSONObject json = jsonParser2.makeHttpRequest(url_create_image,
"POST", param);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Create Response", "success");
} else {
// failed to create product
Toast.makeText(getApplicationContext(),"failed",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return uploadFile();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UserFunctions.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
setProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(fileUri.getPath());
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("http://gemini888.tk"));
entity.addPart("email", new StringBody("thegemini888#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
public String getRandomString() {
StringBuffer randStr = new StringBuffer();
for (int i =0; i<RANDOM_STR_LENGTH; i++) {
int number = getRandomNumber();
char ch = _CHAR.charAt(number);
randStr.append(ch);
}
return randStr.toString();
}
private int getRandomNumber() {
int randomInt = 0;
randomInt = random.nextInt(_CHAR.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinCat.setSelection(position);
String CatList = (String) spinCat.getSelectedItem();
CatList.toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
in captureImage() method try this.
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
//Start image capture intent
}
//first of all create a directory to store your captured Images
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/PGallery");
if (!myDir.exists()) {
myDir.mkdirs();
}
//Give name to your captured Image
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss",java.util.Locale.getDefault());
Date date = new Date();
String sDate = formatter.format(date);
imageName = "PRAVA"+sDate+".jpg";
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filePath = new File(myDir,imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
catch (ActivityNotFoundException e) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
On Actvity Result:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
ImagePath = filePath.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(ImagePath, bitmapOptions);
ImageView mImageView = (ImageView) findViewById(R.id.ivCamreaPic);
mImageView.setImageBitmap(bitmap);
}
I am using viewpager with gridview and downloading json data into it and implemented gridview scroll listener but whenever i start activity again the current viewpager fragment in which sroll listener implemented shows blank.
Here is my code, please see and tell me my mistake.
//My Activity Fragment
private static String url = "http://--------/------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
//My Json Execution
new LoadData().execute(url);
//Scroll listener when gridview reaches at end
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 10) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//Loading new datas in gridview
new LoadData()
.execute("http://-----/-----");
mLoading = true;
}
}
});
return rootView;
}
private class LoadData extends AsyncTask<String, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//checking whether adapter is null or not
if (adap == null) {
adap = new Grid_View_Adatper(getActivity()
.getApplicationContext(), arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
}
Thanks in advance...