This is my PDFListAdapter class method. I have downloaded file locally and save on Sqlite database. But if I scroll my RecyclerView, then I am having different item id. If not scroll RecyclerView then item id is perfect.
The problem is when I scroll down the RecyclerView the item id changes. That is, I can fit one item on the screen at once. When I scroll to the second item, it saves different file and opens different.
public class PDFListAdapter extends RecyclerView.Adapter<PDFListAdapter.MyViewHolder> {
private ArrayList<NotesResponseInfo> pdfModelClasses;
Context context;
static NotesResponseInfo pdfList;
String final_nav_opt_name;
ProgressDialog progressDialog;
String TAG = "PDFListAdapter";
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
int id = 1;
DatabaseNotes databaseNotes;
MyViewHolder holder;
Downloader downloader;
int deepak =0 ;
public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder1.txtDownload.setVisibility(View.VISIBLE);
holder1.layout_download_note_option.setVisibility(View.GONE);
} else {
holder1.txtDownload.setVisibility(View.GONE);
holder1.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
alertDialog.show();
}
}
});
holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
deepak =index ;
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
NotesResponseInfo item = new NotesResponseInfo();
item = pdfModelClasses.get(deepak);
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) >0) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
I have modified your onBindViewHolder function. The changes are following.
Declared the pdfList variable as final and used it everywhere. It is not necessary to get the pdfList from the pdfModelClasses, each time you use it.
The holder variable is removed, as it is not actually necessary. The holder1 is used everywhere.
There are some changes with the visibility of the buttons. Check holder1.imgDownloadNote.setOnClickListener.
I have found no other problem in your onBindViewHolder. Please let me know if the modified code works.
#Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
final int position = index;
// Declare the variable here and make it final.
final PDFList pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder1.txtDownload.setVisibility(View.VISIBLE);
holder1.layout_download_note_option.setVisibility(View.GONE);
} else {
holder1.txtDownload.setVisibility(View.GONE);
holder1.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I have the desired pdfList already, no need to get that again.
// pdfList = pdfModelClasses.get(position);
// Assigning to holder is not necessary.
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
alertDialog.show();
}
}
});
holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
deepak =index ;
// We don't need the reassignment.
// holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
// Make them visible when the internet connection is there.
holder1.imgDownloadNote.setVisibility(View.VISIBLE);
holder1.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder1.progress_download_note.setVisibility(View.VISIBLE);
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
}
} else {
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
} else {
// Put proper visibility everywhere.
holder1.imgDownloadNote.setVisibility(View.GONE);
holder1.imgCancelDownloadNote.setVisibility(View.GONE);
holder1.progress_download_note.setVisibility(View.GONE);
Log.e("","Not in db");
}
}
});
holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
Related
In this app, I created scanner and the result will shown in alertDialogwith two button; OK and NEXT.NEXT button I would like to go to new activity.The problem is, when click the NEXT button, it crash.
please help me..
i'm new.
#Override
public void handleResult(final Result result) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(qrscanner.this);
}
});
builder.setNeutralButton("NEXT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(qrscanner.this,attend_form.class);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
this attend_form
public class attend_form extends AppCompatActivity {
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_rega;
RadioGroup battend;
EditText File,Ic;
String file_number,ic_no;
String attendance = "";
AlertDialog.Builder builder;
String url_reg = "http://192.168.1.7/spm/android/attendance/attend.php";
File file;
Dialog dialog;
LinearLayout mContent;
View view;
signature mSignature;
Bitmap bitmap;
// Creating Separate Directory for saving Generated Images
String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/";
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String StoredPath = DIRECTORY + pic_name + ".png";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attend_form);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Setting ToolBar as ActionBar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btn_rega = (Button)findViewById(R.id.btn_rega);
final RadioGroup battend = (RadioGroup)findViewById(R.id.attendance);
final RadioButton attend = (RadioButton)findViewById(R.id.btn_attend);
final RadioButton absent = (RadioButton)findViewById(R.id.btn_absent);
// Button to open signature panel
btn_get_sign = (Button) findViewById(R.id.signature);
File = (EditText)findViewById(R.id.file_number);
Ic = (EditText)findViewById(R.id.ic_no);
builder = new AlertDialog.Builder(attend_form.this);
btn_rega.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
file_number = File.getText().toString();
ic_no = Ic.getText().toString();
if (battend.getCheckedRadioButtonId() == attend.getId())
{
attendance = "ATTEND";
}
else if(battend.getCheckedRadioButtonId() == absent.getId())
{
attendance = "ABSENT";
}
if(file_number.equals("") || ic_no.equals(""))
{
builder.setTitle("Something were wrong");
builder.setMessage("Please fill all field");
displayAlert("input_error");
}
else
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_reg, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
builder.setTitle("Server Response");
builder.setMessage(message);
displayAlert(code);
}catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#SuppressWarnings("deprecation")
#Override
protected Map<String, String> getPostParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("file_number",file_number);
params.put("ic_no",ic_no);
params.put("attendance",attendance);
return super.getPostParams();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("file_number",file_number);
params.put("ic_no",ic_no);
params.put("attendance",attendance);
return params;
}
};
MySingleton.getInstance(attend_form.this).addToRequestque(stringRequest);
}
}
});
// Method to create Directory, if the Directory doesn't exists
file = new File(DIRECTORY);
if (!file.exists()) {
file.mkdir();
}
// Dialog Function
dialog = new Dialog(attend_form.this);
// Removing the features of Normal Dialogs
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_signature);
dialog.setCancelable(true);
btn_get_sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Function call for Digital Signature
dialog_action();
}
});
}
public void displayAlert(final String code)
{
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if(code.equals("input_error"))
{
File.setText("");
Ic.setText("");
}
else if(code.equals("reg_success"))
{
finish();
}
else if(code.equals("reg_failed"))
{
File.setText("");
Ic.setText("");
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
// Function for Digital Signature
public void dialog_action() {
mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
mSignature = new signature(getApplicationContext(), null);
mSignature.setBackgroundColor(Color.WHITE);
// Dynamically generating Layout through java code
mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mClear = (Button) dialog.findViewById(R.id.clear);
mGetSign = (Button) dialog.findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button) dialog.findViewById(R.id.cancel);
view = mContent;
mClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});
mGetSign.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
view.setDrawingCacheEnabled(true);
mSignature.save(view, StoredPath);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Successfully Saved", Toast.LENGTH_SHORT).show();
// Calling the same class
recreate();
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Canceled");
dialog.dismiss();
// Calling the same class
recreate();
}
});
dialog.show();
}
public class signature extends View {
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void save(View v, String StoredPath) {
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if (bitmap == null) {
bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(bitmap);
try {
// Output the file
FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
v.draw(canvas);
// Convert the output file to Image such as .png
bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
Log.v("log_tag", e.toString());
}
}
public void clear() {
path.reset();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void debug(String string) {
Log.v("log_tag", string);
}
private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY) {
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
}
StringRequestClass
public class StringRequestClass extends AsyncTask<String, Void, String> {
//Your task happens here
EditText File,Ic;
String file_number,ic_no;
String attendance = "";
AlertDialog.Builder builder;
String url_reg = "http://192.168.1.7/spm/android/attendance/attend.php";
#Override
protected String doInBackground(String... params) {
//Do your StringRequest here.
if(file_number.equals("") || ic_no.equals(""))
{
builder.setTitle("Something were wrong");
builder.setMessage("Please fill all field");
displayAlert("input_error");
}
return null;
}
//Things to do when your task is complete.
#Override
protected void onPostExecute(String result) {
//Do everything you want to do after the StringRequest is completed.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_reg, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
String message = jsonObject.getString("message");
builder.setTitle("Server Response");
builder.setMessage(message);
displayAlert(code);
}catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("file_number",file_number);
params.put("ic_no",ic_no);
params.put("attendance",attendance);
return params;
}
};
MySingleton.getInstance(attend_form.this).addToRequestque(stringRequest);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if(file_number.equals("") || ic_no.equals(""))
{
builder.setTitle("Something were wrong");
builder.setMessage("Please fill all field");
displayAlert("input_error");
}
} //Things to do before the internet-related task
#Override
protected void onProgressUpdate(Void... values) {}
public void displayAlert(final String code)
{
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if(code.equals("input_error"))
{
File.setText("");
Ic.setText("");
}
else if(code.equals("reg_success"))
{
finish();
}
else if(code.equals("reg_failed"))
{
File.setText("");
Ic.setText("");
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Try to use getContext()
Intent intent = new Intent(getContext(), attend_form.class);
getContext().startActivity(intent);
New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()
In this app I save products in a sqlite database. Could you help me understand why I can’t see the image when I want to edit a product? I can see it when I add it but not when I click on product to edit it.
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final int EXISTING_PRODUCT_LOADER = 1;
private static final int PICTURE_GALLERY_REQUEST = 1;
private static final String STATE_PICTURE_URI = "STATE_PICTURE_URI";
private Uri mPictureUri;
private Uri mCurrentProductUri;
private EditText mNameEditText;
private EditText mPriceEditText;
private EditText mQuantityEditText;
private EditText mSupplierEditText;
private EditText mMailEditText;
private int mProductQuantity=-1;
private Button mIncreaseQuantityButton;
private Button mDecreaseQuantityButton;
private Button mSelectImageButton;
private ImageView mProductImageView;
private String picturePath;
private String stringUri;
private Button mOrderButton;
final Context mContext = EditorActivity.this;
private boolean mProductHasChanged = false;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mProductHasChanged = true;
return false;
}
};
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 70, image.length);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor_activity);
Intent intent = getIntent();
mCurrentProductUri = intent.getData();
if (mCurrentProductUri == null) {
setTitle(getString(R.string.editor_activity_title_new_product));
invalidateOptionsMenu();
} else {
setTitle(getString(R.string.editor_activity_title_edit_product));
getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this);
}
initialiseViews();
setOnTouchListener();
}
private void setOnTouchListener() {
mNameEditText.setOnTouchListener(mTouchListener);
mPriceEditText.setOnTouchListener(mTouchListener);
mQuantityEditText.setOnTouchListener(mTouchListener);
mSupplierEditText.setOnTouchListener(mTouchListener);
mMailEditText.setOnTouchListener(mTouchListener);
mIncreaseQuantityButton.setOnTouchListener(mTouchListener);
mDecreaseQuantityButton.setOnTouchListener(mTouchListener);
mSelectImageButton.setOnTouchListener(mTouchListener);
mOrderButton.setOnTouchListener(mTouchListener);
}
private void initialiseViews() {
mOrderButton = (Button) findViewById(R.id.order_button);
mOrderButton.setVisibility(View.VISIBLE);
mOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String productName = mNameEditText.getText().toString().trim();
String emailAddress = "mailto:" + mMailEditText.getText().toString().trim();
String subjectHeader = "Order For: " + productName;
String orderMessage = "Please send a unit of " + productName + ". " + " \n\n" + "Thank you.";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse(emailAddress));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, orderMessage);
intent.putExtra(Intent.EXTRA_SUBJECT, subjectHeader);
startActivity(Intent.createChooser(intent, "Send Mail..."));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
mNameEditText = (EditText) findViewById(R.id.edit_name);
mPriceEditText = (EditText) findViewById(R.id.edit_price);
mQuantityEditText = (EditText) findViewById(R.id.edit_quantity);
mSupplierEditText = (EditText) findViewById(R.id.edit_supplier);
mMailEditText= (EditText) findViewById(R.id.edit_supplier_mail);
mIncreaseQuantityButton = (Button) findViewById(R.id.editor_increase);
mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
mProductQuantity++;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}}
});
mDecreaseQuantityButton = (Button) findViewById(R.id.editor_decrease);
mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
if (mProductQuantity > 0) {
mProductQuantity--;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}
}}
});
mProductImageView = (ImageView) findViewById(R.id.image);
mSelectImageButton = (Button) findViewById(R.id.upload_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openPictureGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
openPictureGallery.setDataAndType(data, "image/*");
startActivityForResult(openPictureGallery, PICTURE_GALLERY_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
// checking if the request code and result code match our request
if (requestCode == PICTURE_GALLERY_REQUEST && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
try {
//this is the address of the image on the sd cards
mPictureUri = resultData.getData();
int takeFlags = resultData.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
picturePath = mPictureUri.toString();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(mPictureUri, takeFlags);
}
} catch (SecurityException e) {
e.printStackTrace();
}
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
} catch (Exception e) {
e.printStackTrace();
//Show the user a Toast mewssage that the Image is not available
Toast.makeText(EditorActivity.this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
public Bitmap getBitmapFromUri(Uri uri, Context mContext, ImageView imageView) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
if (input != null)
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
Bitmap.createScaledBitmap(bitmap, 88, 88, false);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
Log.e("EditorActivity", "Failed to load image.", fne);
return null;
} catch (Exception e) {
Log.e("EditorActivity", "Failed to load image.", e);
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private void saveProduct() {
String nameString = mNameEditText.getText().toString().trim();
String quantityString = mQuantityEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String supplierString = mSupplierEditText.getText().toString().trim();
String supplierEmailString = mMailEditText.getText().toString().trim();
if (mCurrentProductUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(quantityString) &&
TextUtils.isEmpty(priceString) && TextUtils.isEmpty(supplierString)&& TextUtils.isEmpty(supplierEmailString)) {
return;
}
int quantity = parseInt(quantityString);
double price = Double.parseDouble(mPriceEditText.getText().toString().trim());
ContentValues values = new ContentValues();
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME, nameString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE, priceString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY, quantityString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER, supplierString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL, supplierEmailString);
if(mPictureUri!=null) {
picturePath = mPictureUri.toString().trim();
}
else{
picturePath=stringUri;
}
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE, picturePath);
if (mCurrentProductUri == null) {
Uri newUri = getContentResolver().insert(ProductContract.ProductEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, getString(R.string.editor_insert_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_insert_product_successful),
Toast.LENGTH_SHORT).show();
}
} else {
int rowsAffected = getContentResolver().update(mCurrentProductUri, values, null, null);
if (rowsAffected == 0) {
Toast.makeText(this, getString(R.string.editor_update_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_update_product_successful),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mCurrentProductUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveProduct();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mProductHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (!mProductHasChanged) {
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
};
showUnsavedChangesDialog(discardButtonClickListener);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ProductContract.ProductEntry._ID,
ProductContract.ProductEntry.COLUMN_PRODUCT_NAME,
ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE,
ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL,
ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE};
return new CursorLoader(this, // Parent activity context
mCurrentProductUri, // Query the content URI for the current product
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
});
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
Uri uriData = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
if (mPictureUri!=null){
if (stringUri!=null)
mProductImageView.setImageURI(uriData);
else {
Bitmap bM = getBitmapFromUri(mPictureUri, mContext, mProductImageView);
mProductImageView.setImageBitmap(bM);
}}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mNameEditText.setText("");
mPriceEditText.setText("");
mQuantityEditText.setText("");
mSupplierEditText.setText("");
mMailEditText.setText("");
mProductImageView.setImageResource(R.drawable.ic_add_a_photo_black_24dp);
}
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved_changes_dialog_msg);
builder.setPositiveButton(R.string.discard, discardButtonClickListener);
builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteProduct();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteProduct() {
if (mCurrentProductUri != null) {
int rowsDeleted = getContentResolver().delete(mCurrentProductUri, null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, getString(R.string.editor_delete_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_delete_product_successful),
Toast.LENGTH_SHORT).show();
}
}
finish();
}
}
The link to the full code is : https://drive.google.com/open?id=1aQFcWHinIqqXHbTyssfPYTD20o9E2piA
and if you can’t find the java files here they are: https://drive.google.com/drive/folders/1VKp0CoJlJssSdKzK4ctk26KFY0_xIDzU?usp=sharing
In your onLoadFinished you assume mPictureURI is set and is not empty.
Now you have set a listener on mProductImageView for changes. No matter what you write/set down below the mProductImageView finally the in the listener it was set back to mPictureURI which was empty hence showing an empty image space.
Please have a look at the code below(also verified that it works).
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
mPictureUri = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(mPictureUri !=null) {
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
}
});
}
I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.
I have a contact list activity but want to add some functionality so that when you click on a contact it will begin calling their phone number. I have tried this code snippet but nothing happens when I tap on a contact:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + currentContact.getPhone()));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
try{
((Activity) context).startActivity(callIntent);
}catch (Exception e){
e.printStackTrace();
}
All Contact activity code:
public class ContactList extends ActionBarActivity {
Spinner spinner, spinnerFilter;
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
ImageView contactImageimgView, btnSort;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
//Uri imageUri = null;
AlertDialog alertDialog;
Bitmap photoTaken;
String userId;
boolean isReverseEnabledPriority = false, isReverseEnabledName = false;
//ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
userId = user.get("uid");
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
contactListView = (ListView) findViewById(R.id.listView);
contactImageimgView = (ImageView) findViewById(R.id.imgViewContactImage);
spinner = (Spinner) findViewById(R.id.spinner);
spinnerFilter = (Spinner) findViewById(R.id.spinnerFilter);
btnSort = (ImageView) findViewById(R.id.btnSort);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("add contact");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("List");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("contact list");
tabHost.addTab(tabSpec);
getContacts(ContactList.this);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filter = spinnerFilter.getSelectedItem().toString();
if(filter.equals("Priority")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getPriorityVal().compareTo(v2.getPriorityVal());
}
});
if(isReverseEnabledPriority)
Collections.reverse(Contacts);
isReverseEnabledPriority = !isReverseEnabledPriority;
populateList();
}else if(filter.equals("Name")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getName().compareTo(v2.getName());
}
});
if(isReverseEnabledName)
Collections.reverse(Contacts);
isReverseEnabledName = !isReverseEnabledName;
populateList();
}else{
Toast.makeText(ContactList.this, "Please selectr a method to sort..!", Toast.LENGTH_SHORT).show();
}
}
});
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Contact contact = new Contact(photoTaken, nameTxt.getText().toString(), phoneTxt.getText().toString(), emailTxt.getText().toString(), addressTxt.getText().toString(), spinner.getSelectedItem().toString(), userId);
Contacts.add(contact);
saveContact(contact, ContactList.this);
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageimgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
}
void getContacts(final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Please wait..", false);
}
});
try {
Contacts = ContactsController.getAllContactsOfUser(userId);
populateList();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
}.start();
}
void saveContact(final Contact contact, final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
boolean result = false;
int id;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Saving Contact..", false);
}
});
try {
id = ContactsController.saveContact(contact);
if(id > 0){
contact.setId(id);
result = ContactsController.uploadImage(contact);
}
} catch (Exception e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(id == 0){
Toast.makeText(context, "Contact is not saved..!", Toast.LENGTH_SHORT).show();
}
if(!result){
Toast.makeText(context, "Image upload failed..!", Toast.LENGTH_SHORT).show();
}else{
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1) {
Uri imageUri = data.getData();
try {
photoTaken = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
} catch (IOException e) {
e.printStackTrace();
}
contactImageimgView.setImageURI(data.getData());
}
}
}
private void populateList() {
ArrayAdapter<Contact> adapter = new ContactListAdapter();
contactListView.setAdapter(adapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(ContactList.this, R.layout.listview_item, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
final Contact currentContact = Contacts.get(position);
try {
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
TextView cPriority = (TextView) view.findViewById(R.id.cPriority);
cPriority.setText(currentContact.getPriority());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
if(currentContact.getImage() != null)
ivContactImage.setImageBitmap(currentContact.getImage());
} catch (Exception e) {
e.printStackTrace();
}
ImageView btnDeleteContact = (ImageView) view.findViewById(R.id.btnDeleteContact);
btnDeleteContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(ContactList.this);
builder.setTitle("Confirm Delete");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteContact(currentContact, ContactList.this);
alertDialog.dismiss();
}
});
builder.setNegativeButton("No", null);
alertDialog = builder.create();
alertDialog.show();
}
});
return view;
}
#Override
public int getCount() {
return Contacts.size();
}
void deleteContact( final Contact contact, final Context context){
new Thread(){
Handler handler = new Handler();
ProgressDialog progressDialog;
Boolean result = false;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Deleting Contact..", false);
}
});
try {
result = ContactsController.deleteContact(contact);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(!result){
Toast.makeText(context, "Contact delete failed..!", Toast.LENGTH_SHORT).show();
}else{
Contacts.remove(contact);
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been deleted from your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
}
}
Have you try this code??
Uri number = Uri.parse("tel:123456789");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);