How can I connect to a specific wifi network? - java

I have devlope project to list out all wifi connection available near to my device.Now, I want to connect any one specific network connection.
SO what can I do? I have got all networks in listview.
If any example available then post comment link.
private void getWifiNetworksList() {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
final WifiManager wifiManager = (WifiManager) getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
;
registerReceiver(new BroadcastReceiver() {
#SuppressLint("UseValueOf")
#Override
public void onReceive(Context context, Intent intent) {
sb = new StringBuilder();
scanList = wifiManager.getScanResults();
sb.append("\n Number Of Wifi connections :" + " "
+ scanList.size() + "\n\n");
adapter = new ArrayAdapter<String>(DraginoActivity.this,
android.R.layout.simple_list_item_1, list);
adapter.clear();
for (int i = 0; i < scanList.size(); i++) {
listWifiDevice.setAdapter(adapter);
// list.add(new Integer(i + 1).toString() + ". ");
list.add((new Integer(i + 1).toString() + ". ")
+ (scanList.get(i)).toString().substring(5,
(scanList.get(i)).toString().indexOf(",")));
// list.add("\n\n");
listWifiDevice.setAdapter(adapter);
adapter.notifyDataSetChanged();
listWifiDevice
.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
TextView tv = (TextView) arg1;
// TODO Auto-generated method stub
Toast.makeText(DraginoActivity.this,
"" + tv.getText().toString(), 1000)
.show();
}
});
}
// listWifiDevice.setAdapter(adapter);
}
}, filter);
wifiManager.startScan();
}

private void setNetworksList() {
networksList = (ListView) findViewById(R.id.networkList);
networksList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) {
final int chosenPosition = position;
WiFiItem wifiItem = new WiFiItem();
wifiItem = (WiFiItem) parent.getItemAtPosition(position);
networkSSID = wifiItem.getSSID();
networkPass = "";
showPasswordDialog(ConnectActivity.this);
setPasswordListener(new PasswordTypedListener() {
#Override
public void onPasswordTyped() {
connectHelper = new ConnectHelper();
if(scanResult.get(chosenPosition).capabilities.contains("WEP")) {
connectHelper.setupConnection(networkSSID, networkPass, "WEP");
}
//jezeli siec WPA
else if(scanResult.get(chosenPosition).capabilities.contains("WPA")) {
connectHelper.setupConnection(networkSSID, networkPass, "WPA");
}
//inne przypadki (open network)
else {
connectHelper.setupConnection(networkSSID, networkPass, "ELSE");
}
wifiManager.addNetwork(connectHelper.getConfiguration());
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
if(wifiManager.reconnect()) {
for(int j=0;j<listWifi.size();j++){
listWifi.get(j).setConnected(false);
}
runnableCounter=0;
handler.postDelayed(ifConnected,1000);
}
break;
}
}
}
});
}
});
}
and also dialog
private void showPasswordDialog(Context context) {
final EditText input = new EditText(context);
input.setSingleLine();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("PASSWORD");
alert.setView(input);
alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
networkPass = input.getText().toString();
if(ConnectActivity.this.passwordListener != null)
ConnectActivity.this.passwordListener.onPasswordTyped();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
}
and in onCreate but you could skip creating WifiItems and just store SSIDs
ArrayList<WiFiItem> listWifi = new ArrayList<WiFiItem>();
wifiManager.startScan();
scanResult = wifiManager.getScanResults();
for(ScanResult sc : scanResult) {
WiFiItem wifiItem = new WiFiItem();
wifiItem.setSSID(sc.SSID);
wifiItem.setBSSID(sc.BSSID);
listWifi.add(wifiItem);
}

Related

startActivityForResult not working as i planned

hi guys im run into problem and it take 3 days and still nothing at all ;
first of all im very sorry for my poor english and apologies ;
my probelm is i can't reach the second else if in sale_ads_fragment although i setresult and started my intent im really upset and even can't sleep for this bug
thanks in advance
private void setUpActivity() {
lnContainer1.setVisibility(View.VISIBLE);
lnContainer2.setVisibility(View.GONE);
txtToolBarTitle.setText("درج آگهی");
txtSend.setText(" " + "ارسال");
//activity result
activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Constant.RESULT_OK && result.getData() != null) {
Intent intent = result.getData();
String mid = intent.getStringExtra(Constant.KEY_ID);
String mTitle = intent.getStringExtra(Constant.KEY_TITLE);
btnChoose1.setText(mTitle);
btnChoose2.setText(mTitle);
lnContainer1.setVisibility(View.GONE);
lnContainer2.setVisibility(View.VISIBLE);
setData(mid);
}**else if (result.getResultCode()==1318) {
G.T("success");**
}
}
});
}
private void selectDialog() {
View view = G.myGLayoutInflater.inflate(R.layout.dialog_select_camera_or_gallery,null);
txtTitle_chooseImg=view.findViewById(R.id.txtTitle);
txtCamera=view.findViewById(R.id.Camera);
txtGallery=view.findViewById(R.id.chooseGallery);
txtCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
**Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activity.setResult(1318,intent);
activity.startActivity(intent);**
alertDialog.dismiss();
}
});
txtGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// G.T("اینو نتونستم ردیفش کنم اما قول میدم درستش کنم");
alertDialog.dismiss();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(view);
builder.setCancelable(true);
alertDialog=builder.create();
alertDialog.show();
}
}
private void setUpListeners() {
lstCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (!categories.get(i).isLastNode) {
assignArrayList(categories.get(i).getId(), false);
} else {
String mId = categories.get(i).getId();
String mTitle = categories.get(i).getTitle();
Intent intent = new Intent();
intent.putExtra(Constant.KEY_ID,mId);
intent.putExtra(Constant.KEY_TITLE,mTitle);
setResult(Constant.RESULT_OK,intent);
finish();
}
}
});
edtSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String text = edtSearch.getText().toString();
int counter = 0;
for (int i = 0; i < G.CATEGORIES.size(); i++) {
if (G.CATEGORIES.get(i).getTitle().equals(text))
{
if (counter == position) {
String mId = G.CATEGORIES.get(i).getId();
String mTitle = G.CATEGORIES.get(i).getTitle();
Intent intent = new Intent();
intent.putExtra(Constant.KEY_ID,mId);
intent.putExtra(Constant.KEY_TITLE,mTitle);
setResult(Constant.RESULT_OK,intent);
finish();
break;
} else {
counter ++;
}
}
}
}
});
}
}

If RecyclerView scrolls, then item id changes. How to resolve this?

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;
}

Image do not show after i saved it in a sqlite database

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));
}
}
}
});
}

Google Cloud Speech API for Android

Currently I`m working on a project where i have to use Google Cloud Speech Api and TextToSpeech. I try-ed to work around with RecognizerIntent but i would like to give a try to Cloud Speech .
Would be great some tutorial material or guide , i checked the sample app
but i`m looking for tutorial , guide anything that could explain something.
Here is my work around with TTS and RecognizerIntent .
private TextToSpeech tts;
private TextToSpeech secondTTS;
private TextView speechInputTextView,correctAnswerTextView,wrongAnswerTextView,currentQuestionTextView;
private ArrayList<String> correctAnswersArrayList, questionArrayList, sayCorrectArrayList, sayWrongArrayList ,toSay ,toASk;
private MediaPlayer mediaPlayer;
private DBHelper dbHelper;
private SQLiteDatabase sqlDB;
private int correctACount,wrongACount,currentQuestion, Unit;
private boolean isStarted;
private String currentLanguage ;
private static int TOTAL_QUESITONS;
private final static int REQ_CODE_SPEECH_INPUT = 100;
private final static String PAUSE_COMMAND = "pos";
private final static String STOP_COMMAND = "stop";
private final static String RESTART_COMMNAD = "restart";
private final static String REPEAT_COMMAND = "repeat";
private final static String EXIT_COMMAND = "exit";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unit);
isStarted = true;
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.unitonemp3);
currentQuestion = 0;
speechInputTextView = (TextView) findViewById(R.id.speechInput);
correctAnswerTextView = (TextView) findViewById(R.id.correctAnswers_TextView);
currentQuestionTextView = (TextView) findViewById(R.id.currentQuestion_TextView);
wrongAnswerTextView = (TextView) findViewById(R.id.wrongAnswer_TextView);
Unit = 1;
currentLanguage = getIntent().getBundleExtra("resultBundle").getString("language");
Button next = (Button) findViewById(R.id.nextButton);
Button changeUnitButton = (Button) findViewById(R.id.changeUnitButton);
Button playButton = (Button) findViewById(R.id.playButton);
Button pauseButton = (Button) findViewById(R.id.pauseButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts.stop();
secondTTS.stop();
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
}
});
tts = new TextToSpeech(this, this);
secondTTS = new TextToSpeech(this, this);
changeUnitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
secondTTS.stop();
tts.stop();
Unit ++;
mediaPlayer.start();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
currentQuestion = getIntent().getBundleExtra("resultBundle").getInt("npc");
}
ImageView micButton = (ImageView) findViewById(R.id.micButton);
micButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!tts.isSpeaking()) {
currentQuestion = 13;
startSayWithID(questionArrayList.get(currentQuestion), 1000, "questionID");
}
}
});
String[] sayCorrectList = getResources().getStringArray(R.array.sayCorrect);
String[] sayWrongList = getResources().getStringArray(R.array.satWrong);
String[] listToSay = getResources().getStringArray(R.array.toSay);
String[] listToAsk = getResources().getStringArray(R.array.toAsk);
toSay = new ArrayList<>(Arrays.asList(listToSay));
toASk = new ArrayList<>(Arrays.asList(listToAsk));
questionArrayList = new ArrayList<>();
correctAnswersArrayList = new ArrayList<>();
addGerCorrect();
addEngQuestions();
sayCorrectArrayList = new ArrayList<>(Arrays.asList(sayCorrectList));
sayWrongArrayList = new ArrayList<>(Arrays.asList(sayWrongList));
TOTAL_QUESITONS = questionArrayList.size();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startSayWithID("Welcome",1000,"instruction");
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0 ; i< questionArrayList.size();i++){
Log.d(" question List "," item :"+"pisition "+i+ "" +questionArrayList.get(i));
}
currentQuestion++;
tts.stop();
secondTTS.stop();
startSayWithID("",1000,"instruction");
}
});
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (utteranceId.contains("say")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ", "current Question" + currentQuestion + "" + correctAnswersArrayList.get(currentQuestion));
}else
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
}
if (utteranceId.contains("instruction")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ","current Question"+currentQuestion +""+correctAnswersArrayList.get(currentQuestion));
} else if (questionArrayList.get(currentQuestion).contains("?")) {
startSayWithID(toASk.get(new Random().nextInt(toASk.size())), 1000, "say");
} else {
startSayWithID(toSay.get(new Random().nextInt(toSay.size())), 1000, "say");
}
}
if (utteranceId.contains("question")) {
if(questionArrayList.get(currentQuestion).contains("?")){
startSayWithID("in Spanish you ask",1000,"german");
}else{
startSayWithID("In Spanish you say",1000,"german");
}
}
if (utteranceId.contains("german")) {
secondTTS.speak(correctAnswersArrayList.get(currentQuestion),TextToSpeech.QUEUE_FLUSH,null,"ask");
}
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
secondTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// end of MainActivity
}
private void promptSpeechInput() {
Intent prompIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
prompIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es-ES");
prompIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "How do you say \n" +questionArrayList.get(currentQuestion));
try {
startActivityForResult(prompIntent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
makeText(getApplicationContext(), "speech not supported", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
switch (currentLanguage){
case "Spanish" :
secondTTS.setLanguage(new Locale("es","Es"));
break;
case "Italian" :
secondTTS.setLanguage(Locale.ITALY);
break;
case "German" :
secondTTS.setLanguage(Locale.GERMAN);
break;
case "French" :
secondTTS.setLanguage(Locale.FRENCH);
break;
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
speechInputTextView.setText(result.get(0));
}
}
String inputSpeechToString = speechInputTextView.getText().toString().toLowerCase();
if (currentQuestion < TOTAL_QUESITONS && inputSpeechToString.contains(correctAnswersArrayList.get(currentQuestion))) {
currentQuestion++;
correctACount++;
correctAnswerTextView.setText(String.valueOf(correctACount));
currentQuestionTextView.setText(String.valueOf(currentQuestion));
Log.d("Onactivity ", "CurrentQ = " + currentQuestion);
startSayWithID(sayCorrectArrayList.get(new Random().nextInt(sayCorrectArrayList.size())), 1000, "instruction");
} else if (inputSpeechToString.contains(STOP_COMMAND)) {
Intent stopIntent = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putBoolean("isStarted", isStarted);
stopIntent.putExtra("resultBundle", resultBundle);
startActivity(stopIntent);
} else if (inputSpeechToString.contains(PAUSE_COMMAND)) {
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
} else if (inputSpeechToString.contains(RESTART_COMMNAD)) {
currentQuestion = 0;
startSayWithID("Restarted", 1000, "say");
} else if (inputSpeechToString.contains(REPEAT_COMMAND)) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
} else if (inputSpeechToString.contains(EXIT_COMMAND)) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
} else {
startSayWithID(sayWrongArrayList.get(new Random().nextInt(sayWrongArrayList.size())), 1000, "instruction");
wrongACount++;
wrongAnswerTextView.setText(String.valueOf(wrongACount));
Log.d("Onactivity ", "CORRECT = " + correctAnswersArrayList.get(currentQuestion));
Log.d("Onactivity ", "You said : " + inputSpeechToString);
}
}
}
private void addEngQuestions() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryEngQuestion = "SELECT English FROM " +currentLanguage+ " WHERE " + "Unit = " +Unit+ " ORDER BY Unit ASC";
Cursor cursor = sqlDB.rawQuery(queryEngQuestion, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
questionArrayList.add(cursor.getString(cursor.getColumnIndex("English")));
cursor.moveToNext();
}
} finally {
cursor.close();
}
Log.d("Line 255", " English Arraylist" + questionArrayList.size());
}
private void addGerCorrect() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryGerCOrrect = "SELECT "+ currentLanguage +" FROM "+ currentLanguage + " WHERE "+ "Unit = "+Unit+ " ORDER BY Unit ASC";
Cursor cursor2 = sqlDB.rawQuery(queryGerCOrrect, null);
try {
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
correctAnswersArrayList.add(cursor2.getString(cursor2.getColumnIndex(currentLanguage))
.replaceAll("\\p{P}", "").toLowerCase());
cursor2.moveToNext();
}
} finally {
cursor2.close();
}
}
private void startSayWithID(final String text, int mSeconds, final String ID) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, ID);
}
}, mSeconds);
}
private void startAsk(int seconds) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
promptSpeechInput();
}
}, seconds);
}
#Override
protected void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (secondTTS != null) {
secondTTS.stop();
secondTTS.shutdown();
}
super.onDestroy();
}
Setting up Google Speech cloud on Android is not a straightforward 1,2,3 process, but I will give you some guidance.
Download the Sample project from here, use the Speech example.
https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech
Setup a google cloud project, enable the Speech API, and link it to
your gmail account's billing (you get 60min of free speech recognition
every month).
Generate an authentication json, and put it into the "raw" folder of
the sample project.
Setup Google cloud on your computer and obtain an access token.
Insert that access token on your SpeechService.java class.
*Documentation on steps 3 and 4:
https://cloud.google.com/speech/docs/getting-started
*If you run into problems when trying to mimic the sample project into your own project, check this:
Cannot import com.google.cloud.speech.v1.SpeechGrpc in Android
The exact steps are too long to list, I can't even remember them all, if you run into specific trouble let me know.

Attempt to invoke interface method 'int org.ksoap2.serialization.KvmSerializable.getPropertyCount()' on a null object reference

i have a school project. It was built by some previous developer. I am trying to run it. But i am getting NullPointerException. Here is my code:
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setToolbar();
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE1,OPERATION_NAME1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS1);
httpTransport.debug=true;
try {
httpTransport.call(SOAP_ACTION1, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
response= envelope.getResponse();
Log.e("response: ", response.toString() + "");
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
Log.e("response: ", response.toString() + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
try {
Log.e("response: ", response.toString() + "");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this,response.toString()+"",Toast.LENGTH_LONG).show();
}
StringTokenizer tokens = new StringTokenizer(response.toString(), "=");
List<String> mylist=new ArrayList<String>();
for(int i=0;tokens.hasMoreTokens();i++){
StringTokenizer tokens1 = new StringTokenizer(tokens.nextToken(), ";");
mylist.add(tokens1.nextToken());
}
mylist.remove(0);
int partitionSize =1;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < mylist.size(); i += partitionSize) {
partitions.add(mylist.subList(i,
i + Math.min(partitionSize, mylist.size() - i)));
}
city=new ArrayList<String>();
for(int k=0;k<partitions.size();k++){
city.add(partitions.get(k).get(0));
}
callGetArea();
}
}.execute();
spcity= (Spinner) findViewById(R.id.spcity);
spcity.setOnItemSelectedListener(this);
sparea = (Spinner) findViewById(R.id.sparea);
sparea.setOnItemSelectedListener(this);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
rg = (RadioGroup) findViewById(R.id.gendergroup);
name= (EditText) findViewById(R.id.fname);
address=(EditText)findViewById(R.id.address);
contact= (EditText) findViewById(R.id.contact);
email= (EditText) findViewById(R.id.email);
weight= (EditText) findViewById(R.id.weight);
password= (EditText) findViewById(R.id.password);
cpass= (EditText) findViewById(R.id.cpassword);
earea= (Spinner) findViewById(R.id.sparea);
ecity= (Spinner) findViewById(R.id.spcity);
btnContinue= (TextView)findViewById(R.id.btncont);
bdate = (EditText) findViewById(R.id.bdate);
bdate.setInputType(InputType.TYPE_NULL);
bdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDateTimeField();
fromDatePickerDialog.show();
}
});
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isEmptyField(name)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Name", Toast.LENGTH_LONG).show();
} else if (isEmptyField(bdate)) {
Toast.makeText(RegistrationActivity.this, "Please Select Birthdate", Toast.LENGTH_LONG).show();
} else if (isEmptyField(address)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Address", Toast.LENGTH_LONG).show();
} else if (isEmptyField(weight)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Weight", Toast.LENGTH_LONG).show();
} else if (isEmptyField(contact)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Contact", Toast.LENGTH_LONG).show();
} else if (isEmptyField(email)) {
Toast.makeText(RegistrationActivity.this, "Please Enter E-Mail", Toast.LENGTH_LONG).show();
}else if (!isEmailPattern(email)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Valid E-Mail", Toast.LENGTH_LONG).show();
}else if (isEmptyField(password)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Password", Toast.LENGTH_LONG).show();
} else if (isEmptyField(cpass)) {
Toast.makeText(RegistrationActivity.this, "Please Confirm Password", Toast.LENGTH_LONG).show();
} else if (!isPasswordMatch(cpass,password)) {
Toast.makeText(RegistrationActivity.this, "Password doesn't match", Toast.LENGTH_LONG).show();
}
else {
if(isNetworkAvailable()) {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
resp = loginCall(email.getText().toString().trim());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.e("Response", resp + "");
dialog.dismiss();
if (resp == 1) {
UserClass userClass = new UserClass();
userClass.name = name.getText().toString();
userClass.dob = bdate.getText().toString();
int selectedId = rg.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(selectedId);
userClass.gender = radioButton.getText().toString();
userClass.address = address.getText().toString();
userClass.city = city.get(ecity.getSelectedItemPosition());
userClass.area = area.get(earea.getSelectedItemPosition()).city;
userClass.weight = weight.getText().toString();
userClass.contact = contact.getText().toString();
userClass.email = email.getText().toString();
userClass.password = password.getText().toString();
Log.e("name", userClass.name + "");
Log.e("dob", userClass.dob + "");
Log.e("gender", userClass.gender + "");
Log.e("address", userClass.address + "");
Log.e("city", userClass.city + "");
Log.e("area", userClass.area + "");
Log.e("weight", userClass.weight + "");
Log.e("contact", userClass.contact + "");
Log.e("email", userClass.email + "");
Log.e("password", userClass.password + "");
PrefUtils.setCurrentUser(userClass, RegistrationActivity.this);
Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity2.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Email Already Exist", Toast.LENGTH_LONG).show();
}
}
}.execute();
}
else
{
Toast.makeText(RegistrationActivity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar userAge = new GregorianCalendar(year,month,day);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(userAge))
{
Toast.makeText(RegistrationActivity.this,"Please enter valid date",Toast.LENGTH_LONG).show();
}
}
private void callGetArea() {
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE2,OPERATION_NAME2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
httpTransport.debug=true;
try {
httpTransport.call(SOAP_ACTION2, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
response= envelope.getResponse();
Log.e("response: ", response.toString() + "");
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
Log.e("response: ", response.toString() + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
try {
Log.e("response: ", response.toString() + "");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this,response.toString()+"",Toast.LENGTH_LONG).show();
}
StringTokenizer tokens = new StringTokenizer(response.toString(), "=");
List<String> mylist=new ArrayList<String>();
for(int i=0;tokens.hasMoreTokens();i++){
StringTokenizer tokens1 = new StringTokenizer(tokens.nextToken(), ";");
mylist.add(tokens1.nextToken());
}
mylist.remove(0);
final int partitionSize =2;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < mylist.size(); i += partitionSize) {
partitions.add(mylist.subList(i,
i + Math.min(partitionSize, mylist.size() - i)));
}
area=new ArrayList<Area>();
for(int k=0;k<partitions.size();k++){
area.add(new Area(partitions.get(k).get(0),partitions.get(k).get(1)));
}
TimeSpinnerAdapter1 tspcity=new TimeSpinnerAdapter1(RegistrationActivity.this,city);
spcity.setAdapter(tspcity);
spcity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayList<Area> tempList=new ArrayList<Area>();
for(int i=0;i<area.size();i++){
Log.e("city............",area.get(i).area+"");
if(area.get(i).area.equalsIgnoreCase(city.get(position))){
tempList.add(area.get(i));
}
}
TimeSpinnerAdapter tsparea = new TimeSpinnerAdapter(RegistrationActivity.this, tempList);
sparea.setAdapter(tsparea);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}.execute();
}
private void setDateTimeField() {
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar userAge = new GregorianCalendar(year,monthOfYear,dayOfMonth);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(userAge))
{
Toast.makeText(RegistrationActivity.this,"Please Enter Valid Date",Toast.LENGTH_LONG).show();
} else {
bdate.setText(dateFormatter.format(userAge.getTime()));
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
public boolean isEmptyField(EditText param1) {
boolean isEmpty = false;
if (param1.getText() == null || param1.getText().toString().equalsIgnoreCase("")) {
isEmpty = true;
}
return isEmpty;
}
private void setToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Register");
setSupportActionBar(toolbar);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class TimeSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<Area> asr;
public TimeSpinnerAdapter(Context context,ArrayList<Area> asr) {
this.asr=asr;
activity = context;
}
public int getCount()
{
return asr.size();
}
public Object getItem(int i)
{
return asr.get(i);
}
public long getItemId(int i)
{
return (long)i;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setText(asr.get(position).city);
txt.setTextColor(Color.parseColor("#494949"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_spinner, 0);
txt.setText(asr.get(i).city);
txt.setTextColor(Color.parseColor("#ffffff"));
return txt;
}
}
public static boolean isEmailPattern(EditText param1) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(param1.getText().toString()).matches();
}
public static boolean isPasswordMatch(EditText param1, EditText param2) {
boolean isMatch = false;
if (param1.getText().toString().equals(param2.getText().toString())) {
isMatch = true;
}
return isMatch;
}
public class TimeSpinnerAdapter1 extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<String> asr;
public TimeSpinnerAdapter1(Context context,ArrayList<String> asr) {
this.asr=asr;
activity = context;
}
public int getCount()
{
return asr.size();
}
public Object getItem(int i)
{
return asr.get(i);
}
public long getItemId(int i)
{
return (long)i;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setText(asr.get(position));
txt.setTextColor(Color.parseColor("#494949"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_spinner, 0);
txt.setText(asr.get(i));
txt.setTextColor(Color.parseColor("#ffffff"));
return txt;
}
}
public int loginCall(String c1)
{
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo p1=new PropertyInfo();
p1.setName("email");
p1.setValue(c1);
p1.setType(String.class);
request.addProperty(p1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Object response=null;
try
{
httpTransport.debug=true;
httpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
}
catch (Exception ex)
{
// ex.printStackTrace();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
//displayExceptionMessage(ex.getMessage());
//System.out.println(exception.getMessage());
}
return Integer.parseInt(response.toString());
}
I am getting NullPointerException on response= envelope.getResponse();
My error is following:
Process: com.nkdroid.blooddonation, PID: 16820
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int org.ksoap2.serialization.KvmSerializable.getPropertyCount()' on a null object reference
at org.ksoap2.serialization.SoapSerializationEnvelope.getResponse(SoapSerializationEnvelope.java:513)
at com.nkdroid.blooddonation.RegistrationActivity$1.doInBackground(RegistrationActivity.java:146)
at com.nkdroid.blooddonation.RegistrationActivity$1.doInBackground(RegistrationActivity.java:120)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
Can anyone help me with that?
I know code is a mess. But any help will be appreciated.
Thanks! :)
Make sure you have the same name as property in your service and android parameters, for example request.addProperty("name",name) in the WebService public class Login(String name)

Categories

Resources