Retrieving data from Parse - java

I manage to have the user record information name, headline, age, and even gender selection as well as gender preference in parse. Now I want to be able to retrieve the information, with conditions. For instance, if the current user selected that he is looking for a female, than it would only display queryequal female.
Below is the code where the user enter the information that is submitted to parse:
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
RadioButton male, female;
String gender;
RadioButton lmale, lfemale;
String lgender;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
male = (RadioButton)findViewById(R.id.rimale);
female = (RadioButton)findViewById(R.id.rifemale);
lmale = (RadioButton)findViewById(R.id.rlmale);
lfemale = (RadioButton)findViewById(R.id.rlfemale);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
/* // Locate the image from the ImageView
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
fron image view);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("profilePicture.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageName" and set the string
currentUser.put("ImageName", "AndroidBegin Logo");
// Create a column named "ImageFile" and insert the image
currentUser.put("ProfilePicture", file);
// Create the class and the columns
currentUser.saveInBackground(); */
if(male.isChecked())
gender = "Male";
else
gender = "Female";
if(lmale.isChecked())
lgender = "Male";
else
lgender = "Female";
currentUser.put("Name", name);
currentUser.put("Age", age);
currentUser.put("Headline", headline);
currentUser.put("Gender", gender);
currentUser.put("Looking_Gender", lgender);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Below is the code that I am brainstorming could be used to retrieved information:
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = "";
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.whereEqualTo("ActivityName","");
query.whereNotEqualTo("Looking_Gender",currentUserID);
The issue i have now is setting a condition, where if a guy wants to be match with guy so only those guys who want to be match with guys information returns, and vice-versa for women.
Let me know, if this is fine.
Thanks in advance.

The following line will ensure that the Users returned are only users who match the gender for which the current user is looking. That is, if I'm looking for a female, the constraint below will ensure that only females are returned.
query.whereEqualTo("Gender", ParseUser.getCurrentUser().getString("Looking_Gender"));
The following line will ensure that the Users returned are only users who are looking for other users that match the gender for which I am. That is, if I'm a male, the constraint below will ensure that only users who are looking for males will be returned.
query.whereEqualTo("Looking_Gender", ParseUser.getCurrentUser().getString("Gender"));
If I understand your question correctly, using the above two constraints together should achieve what you're looking for.

Related

How to upload this gridview of base 64 converted images to firebase?

This is the code I am working on, make a multiple selection of images and the most in a gridview array that calls it ImageList, but I would recommend converting the images to a base64 to have more efficiency when uploading and displaying the images, so I looked for examples and documentation and I found a way to convert them, but I was somewhat confused, because the array where the images are stored was ready List of images I had to pass it to a chain of chains, but I did not understand very well how to upload them to the firebase both the storage and the database, since they are images that will be saved of products that will be shown in the store this is the code
here is the activity where the data will be uploaded, the data as name price and description already uploaded to the database the imagenes not.
public class adminActivity extends AppCompatActivity {
private EditText nombreP, precioP, infoP;
int PICK_IMAGE = 100;
Uri imagenUri;
Button btnCargar;
Button btnEditar;
GridView gvImagenes;
List<Uri> listaImagenes = new ArrayList<>();
List<Uri> listaBase64Imagenes = new ArrayList<>();
GridViewAdapter baseAdapter;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference mStorageRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
/*INICIALIZAMOS LA CONEXION CON FIREBASE*/
FirebaseApp.initializeApp(this);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
mStorageRef = FirebaseStorage.getInstance().getReference();
nombreP = (EditText) findViewById(R.id.nameProducto);
precioP = (EditText) findViewById(R.id.precioProducto);
infoP = (EditText) findViewById(R.id.infoProducto);
gvImagenes = findViewById(R.id.gvImagenes);
btnEditar = findViewById(R.id.editar);
btnCargar = (Button) findViewById(R.id.cargar);
btnEditar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
abrirGaleria();
}
});
btnCargar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre = nombreP.getText().toString();
String precio = precioP.getText().toString().trim();
String infor = infoP.getText().toString();
if (!nombre.isEmpty() && !precio.isEmpty() && !infor.isEmpty()){
cargarUsuario();
limpiarCaja();
}else {
Toast.makeText(adminActivity.this,"Deben llenarse todos los campos.",Toast.LENGTH_SHORT).show();
return;
}
}
});
}
private void limpiarCaja() {
nombreP.setText("");
precioP.setText("");
infoP.setText("");
}
public void cargarUsuario() {
listaBase64Imagenes.clear();
for (int i = 0 ; i < listaImagenes.size() ; i++){
try {
InputStream is = getContentResolver().openInputStream(listaImagenes.get(i));
Bitmap bitmap = BitmapFactory.decodeStream(is);
String cadena = convertirUriToBase64(bitmap);
enviarImagen(cadena);
bitmap.recycle();
} catch (IOException e){
}
}
//Toast.makeText(this, "Producto Registrado", Toast.LENGTH_LONG).show();
String nombre = nombreP.getText().toString();
String precio = precioP.getText().toString();
String infor = infoP.getText().toString();
productos p = new productos();
p.setUid(UUID.randomUUID().toString());
p.setNombre(nombre);
p.setPrecio(precio);
p.setInformacion(infor);
databaseReference.child("Productos").child(p.getUid()).setValue(p);
Toast.makeText(adminActivity.this,"Agregado.",Toast.LENGTH_SHORT).show();
}
private void enviarImagen(final String cadena) {
StorageReference folderRef = mStorageRef.child("imagenesProductos");
folderRef.putFile((Uri) listaImagenes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
}
});
}
private String convertirUriToBase64(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
return encode;
}
private void abrirGaleria() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "SELECCIONA LAS IMAGENES"),PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ClipData clipData = data.getClipData();
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
/*PARA UNA SOLA IMAGEN*/
if (clipData == null){
imagenUri = data.getData();
listaImagenes.add(imagenUri);
}
}else {
/*PARA VARIAS IMAGENES*/
for (int i = 0; i < clipData.getItemCount(); i++){
listaImagenes.add(clipData.getItemAt(i).getUri());
}
}
baseAdapter = new GridViewAdapter(adminActivity.this, listaImagenes);
gvImagenes.setAdapter(baseAdapter);
}
}
and here is the gridview adapter code
#Override
public int getCount() {
return listaImagenes.size();
}
#Override
public Object getItem(int position) {
return listaImagenes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.item_carga_imagenes, null);
}
ImageView ivImagen = view.findViewById(R.id.ivImagen);
ImageButton ibtnEliminar = view.findViewById(R.id.ibtnEliminar);
ivImagen.setImageURI(listaImagenes.get(position));
ibtnEliminar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listaImagenes.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
here i point out the method where i try to make the connection to the storage of firebase, they could help to rebuild it in order to be able to upload them to the storage and also to the database with their respective name, price and description
private void enviarImagen(final String cadena) {
StorageReference folderRef = mStorageRef.child("imagenesProductos");
folderRef.putFile((Uri) listaImagenes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
}
});
}
Your question is still little bit of confusion, In my case what i understand from you, you want to store images to firebase in BASE64 format.
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
Now, you don't have you store string, you can simply store byte[] in firbase and retrive it and just converted it to bitmap, here is a example for you:
byte[] byteImage = Base64.decode(encode, Base64.DEFAULT);
Bitmap imageBitmap = BitmapFactory.decodeByteArray(byteImage, 0, decodedString.length);

How do I get a gridview class to call itself on click, then on another grid item click, reference another activity?

Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}

Cannot relate seek bar to text

I am trying to relate my seekbar to the text. With assistance, I tried to do so, but my attempt have been unsuccessful.
Also I want to also include a range seek bar in the below is the code, but not sure how to work that out. Any assistance would be greatly appreciated.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Updated code
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Below code snippet should be moved out of onClickListener. Write it in onCreate
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});

.Resources$NotFoundException: String resource ID #0x3

In my application when i pass an intent into another class,so that user can send sms messages and that data get stored in database,..and when user click on select contact button he get the contacts checked on which he send the messages,firstly it worked fine but when i added update code on button click it start giving back the error..and logcat is showing me the error
03-24 11:45:10.811: E/AndroidRuntime(18748): android.content.res.Resources$NotFoundException: String resource ID #0x3
03-24 11:45:10.811: E/AndroidRuntime(18748): at android.widget.Toast.makeText(Toast.java:311)
smsSend.java
public class SmsSend extends Activity implements OnClickListener {
BroadcastReceiver smsSentReciver, smsSentDelivery;
static EditText edName, edMessage;
static int ResultCode = 12;
static ArrayList<String> sendlist = new ArrayList<String>();
Button btnSaveForLater, btnStart, btnExternal, btnSelect;
static TextView txt;
static StringBuilder conct = new StringBuilder();
static String contacts = "";
String delim = ";";
public static String Name;
TextView ed;
int i = 0;
String rowid, rowid1, value;
int j;
String Name1, msg, msg1;
String[] cellArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_camp);
btnExternal.setOnClickListener(this);
txt = (TextView) findViewById(R.id.textnum2);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
rowid = getIntent().getStringExtra("rowid");
value = getIntent().getStringExtra("key");
rowid1 = getIntent().getStringExtra("rowid1");
entryData();
edName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edName.setError(null);
}
});
edMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edMessage.setError(null);
}
});
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
txt.setError(null);
}
});
// Toast.makeText(getApplication(), contacts.toString(),
// Toast.LENGTH_LONG).show();
Name1 = edName.getText().toString();
msg1 = edMessage.getText().toString();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
edName.setText(null);
edMessage.setText(null);
conct.delete(0, conct.length());
contacts = null;
txt.setText("0");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(smsSentReciver);
unregisterReceiver(smsSentDelivery);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
smsSentReciver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "sms has been sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic Fail",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No Service",
Toast.LENGTH_SHORT).show();
default:
break;
}
}
};
smsSentDelivery = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Sms Delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "Sms not Delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver(smsSentReciver, new IntentFilter("SMS_SENT"));
registerReceiver(smsSentDelivery, new IntentFilter("SMS_DELIVERED"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelp entry = new DatabaseHelp(SmsSend.this);
entry.open();
switch (v.getId()) {
case R.id.btnSelect:
Intent a = new Intent(SmsSend.this, MainActivity.class);
startActivityForResult(a,ResultCode);
break;
case R.id.btnExternal:
Intent file = new Intent(SmsSend.this, File_Selecter.class);
startActivity(file);
break;
case R.id.btnStart:
Log.i("SMS", "Sendlist Size: " + sendlist.size());
if (edName.getText().toString().length() == 0
|| edName.getText().toString().length() == 0
|| txt.getText().equals("0")) {
edName.setError("First name is required!");
edMessage.setError("Message is required!");
txt.setError("Contacts required!");
} else {
/* if (rowid1 != null
&& edName.getText().toString().length() != 0
&& edName.getText().toString().length() != 0
&& txt.getText().equals("0")
&& edName.getText().toString() == value) {
Toast.makeText(getApplication(), "update", Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this,
0, new Intent("SMS_SENT"), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(
this, 0, new Intent("SMS_DELIVERED"), 0);
Log.i("SMS", "contacts: " + contacts);
contacts = conct.toString();
cellArray = contacts.split(";");
for (int a1 = 0; a1 < cellArray.length; a1++) {
smsManager.sendTextMessage(cellArray[i].toString(),
null, msg1, piSend, piDelivered);
}
long ltt = Long.parseLong(rowid1);
entry.updateEntry(ltt, Name1, msg1, contacts);
Toast.makeText(getApplication(), "updated",
Toast.LENGTH_LONG).show();
} else {*/
boolean diditwork1 = true;
try {
Toast.makeText(getApplication(), "insert", Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this,
0, new Intent("SMS_SENT"), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(
this, 0, new Intent("SMS_DELIVERED"), 0);
Log.i("SMS", "contacts: " + contacts);
contacts = conct.toString();
//Toast.makeText(getApplication(), contacts.toString(), Toast.LENGTH_LONG).show();
cellArray = contacts.split(";");
Toast.makeText(getApplication(), cellArray.length, Toast.LENGTH_LONG).show();
for (int a1 = 0; a1 < cellArray.length; a1++) {
smsManager.sendTextMessage(cellArray[i].toString(),
null, msg1, piSend, piDelivered);
}
DatabaseHelp entry1 = new DatabaseHelp(SmsSend.this);
entry1.open();
entry1.entryCreate(Name1, msg1, contacts);
entry1.close();
}
catch (Exception e) {
diditwork1 = false;
String erroe = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(erroe);
d.setContentView(tv);
d.show();
} finally {
if (diditwork1) {
Dialog d = new Dialog(this);
d.setTitle("Heck Yeah!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
}
edName.setText("");
edMessage.setText("");
txt.setText("0");
break;
}
}
//}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
sendlist = data.getStringArrayListExtra("name");
Toast.makeText(getApplication(), sendlist.size(), Toast.LENGTH_LONG).show();
if (sendlist != null) {
for (int i = 0; i < sendlist.size(); i++) {
conct.append(sendlist.get(i).toString());
conct.append(delim);
//Toast.makeText(getApplication(), conct.toString(),Toast.LENGTH_LONG).show();
}
}
}
i = sendlist.size();
txt.setText(Integer.toString(i));
if (resultCode == RESULT_CANCELED) {
}
}
}
}
MainaActiivty.java
public class MainActivity extends Activity implements OnItemClickListener {
ArrayList<String> name1 = new ArrayList<String>();
static ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
MyAdapter ma;
Button send;
String[] cellArray = null;
int[] str;
int v = 0;
String contacts;
static int check1;
ListView lv;
int index;
int top;
StringBuilder b = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.get);
// TextView txt = (TextView) findViewById(R.id.textView1);
getAllCallLogs(this.getContentResolver());
lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// b = SmsSend.contacts;
contacts = SmsSend.contacts;
if (SmsSend.contacts != null) {
cellArray = contacts.split(";");
// Toast.makeText(getApplication(),contacts.toString(),
// Toast.LENGTH_LONG).show();
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < phno1.size(); j++) {
if (cellArray[i].equals(phno1.get(j))) {
Toast.makeText(getApplication(),cellArray[i].toString(),
Toast.LENGTH_LONG).show();
ma.setChecked(j, true);
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.contact_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.addPage:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
phno0.add(phno1.get(i).toString());
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ name1.get(i).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
Toast.makeText(getApplication(), phno0.size(), Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
System.out.println(phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(name1.get(position));
tv1.setText(phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
try this one:
Toast.makeText(getApplication(), sendlist.size().tostring(), Toast.LENGTH_LONG).show();
or else:
Toast.makeText(getApplication(), sendlist.size().toString()+"", Toast.LENGTH_LONG).show();
bcoz it will allow second params in a string.. and also use getApplication instead of this one example :
Toast.makeText(getApplicationContext(),
"Error during request: " + e.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
Thank you,,
Toast.makeText(getApplication(), sendlist.size(), Toast.LENGTH_LONG).show();
sendlist.size() returns an int and passing an int to Toast.makeText() uses the overload that attempts to load a string resource with the given id.
Replace with e.g. Integer.toString(sendlist.size()) to toast the integer value.
You have the same issue in multiple places. Check all your Toast.makeText() calls.
The second param to Toast must be a String type.
Concatenate second param like this:
Toast.makeText(getApplication(), "" + sendlist.size(), Toast.LENGTH_LONG).show();
try this one
Toast.makeText(ExploreMatchDetail.this,sendlist.size()+"",Toast.LENGTH_SHORT).show();

Zbar Qr Code Reader - crash after qr code reader

I'm trying to do a Qr code reader with Zbar but the app crash after the Qr Code detect (when result != 0)
I'm not getting error message, only a warning:
CHECK surface infomation creating=false formatChanged=false
sizeChanged=false visible=false visibleChanged=true
surfaceChanged=true realSizeChanged=false redrawNeeded=false
left=false top=false
Here is the code which I got the crash
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = mScanner.scanImage(barcode);
if (result != 0) {
mCamera.cancelAutoFocus();
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mPreviewing = false;
SymbolSet syms = mScanner.getResults();
for (Symbol sym : syms) {
String symData = sym.getData();
if (!TextUtils.isEmpty(symData)) {
Intent dataIntent = new Intent();
dataIntent.putExtra(SCAN_RESULT, symData);
dataIntent.putExtra(SCAN_RESULT_TYPE, sym.getType());
setResult(Activity.RESULT_OK, dataIntent);
finish();
break;
}
}
}
}
I did update my code and it works great! thx all!
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = mScanner.scanImage(barcode);
if (result != 0) {
mCamera.cancelAutoFocus();
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mPreviewing = false;
SymbolSet syms = mScanner.getResults();
for (Symbol sym : syms) {
String symData = sym.getData();
Log.i("url qr code",symData);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(symData));
startActivity(browserIntent);
break;
}
}
}
try this... for Qr Reader....
public class QRCodeActivityTest extends Activity implements
OnQRCodeReadListener {
QRCodeReaderView qrView;
TextView tvQr;
Image_Sql sql;
String Description;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.qrtest_layout);
qrView = (QRCodeReaderView) findViewById(R.id.qRCodeReaderView1);
qrView.setOnQRCodeReadListener(this);
tvQr = (TextView) findViewById(R.id.txtqr);
sql= new Image_Sql(this);
sql.Open();
}
#Override
public void onQRCodeRead(String text, PointF[] points) {
// TODO Auto-generated method stub
Cursor desc = sql.fetchNameFromTitle(text);
while (desc.moveToNext()) {
Description = desc.getString(desc
.getColumnIndexOrThrow(Image_Sql.IMAGE_DESCRIPTION));
}
if(text.equals(""))
{
Dialog d = new Dialog(this);
TextView tv = new TextView(this);
tv.setText("Please Sync Catalogue TO Display QRCode Image Information");
d.setContentView(tv);
d.setTitle("Required Syncing..");
d.show();
}else
{
tvQr.setText(Description);
}
}
#Override
public void cameraNotFound() {
// TODO Auto-generated method stub
}
#Override
public void QRCodeNotFoundOnCamImage() {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
qrView.getCameraManager().startPreview();
}
#Override
protected void onPause() {
super.onPause();
qrView.getCameraManager().stopPreview();
}
}

Categories