How to parse result of QR-scanning Zbar android? - android

I use Zbar library for QR-scanning.
I try to parse result of this scanning, but I lost some information. For parsing I use this library.
Does any other library can parse handleResult(Result rawResult) rawResult?
This my code :
#Override
public void handleResult(final Result rawResult) {
Log.v("myLog", rawResult.getContents()); // Prints scan results
Log.v("myLog", rawResult.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)
unswer = rawResult.getContents();
if (unswer.contains("VCARD")){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Содержимое");
builder.setMessage(unswer = rawResult.getContents());
builder.setPositiveButton("Добавить контакт", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String parseVcard = unswer;
VCard vCard = VCardParser.parse(parseVcard);
String name = vCard.getName();
String fname = vCard.getFormattedName();
Log.d("myLog", name + " " + fname);
addContact(fname + " " + name);
}
});
builder.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

vCard.getFormattedName() is not going to return you a value because your rawResult does not contain a "FN" value. When you look at the value you sent it only contains "N" which means you'll only have value with vCard.getName();

Related

how to show values in the second edittext only if user puts all the correct values in the first edit text

what should add in the code so that values are shown in the other text box only when the user have entered only corrected values...because with this code it is showing both the corrected values in the text box and incorrect in the dialog box..
String s=editText1.getText().toString();
String z[]=s.split("\\s");
editText2.setText("");
String a = "";
String b = " Not valid";
boolean is_open_dialog=false;
for(int i=0;i<z.length;i++)
{
int j=Integer.parseInt(z[i]);
if(j>=65 && j<=97)
{
editText2.setText(editText2.getText() + "" + String.valueOf((char) j));
}
else {
is_open_dialog = true;
a += z[i]+"\t";
}
}
if(is_open_dialog){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage(a+b)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
I do not know if I have clear your problem, but try this:
...
if(is_open_dialog){
editText2.setText("");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
...
}

Error:java.lang.IllegalArgumentException: Empty file name Android

I'am creating application which gets data from MySQL db. Few days ago I made few big changes one of them is that instead of multiple activity forms,I am using fragments and toolbar to switch between them. After that i noticed that i got this error:
02/com.example.kurpaest.kurpaest W/JNIHelp﹕ Discarding pending exception (java.lang.NullPointerException) to throw java/lang/IllegalArgumentException
09-12 14:50:53.180 15402-15402/com.example.kurpaest.kurpaest E/MSG﹕ **java.lang.IllegalArgumentException: Empty file name**
This error shows up when my top 5 places is returning null. But when I try to debug application it runs smoothly with out error or any kind problem.
My server is on my pc and i connect to it using IP address which is provided by ISP.
One more interesting thing is that this error shows up more often when wifi is used instead of mobile network.
One of my guesses is that servers configuration is incorrect and second part is that all tabs makes there own requests to server instead of one complete request.
In the doInBackground() method the app stops suddenly:
#Override
protected String doInBackground(String... params) {
handler.post(new Runnable() {
#Override
public void run() {
gps = new GpsTracker(context);
}
});
HashMap<String,String> param = new HashMap<String,String>();
//param.put("lat", String.valueOf(gps.getLatitude()));
// param.put("long", String.valueOf(gps.getLongitude()));
JSONObject json = jsonParser.makeHttpRequest(url_all_products,"GET",param);
try{
int success = json.getInt(TAG_SUCCESS);
switch(success){
case 1:
products = json.getJSONArray(TAG_LUNCH);
for(int i = 0;i<5;i++){
JSONObject c = products.getJSONObject(i);
String id = c.getString(TAG_ID);
String name =c.getString(TAG_NAME);
Log.d("MSG", name);
String picture ="images/"+c.getString(TAG_PICTURE)+".png";
Log.d("MSG", picture+"wasd");
String cost = c.getString(TAG_COST);
Log.d("MSG", cost);
String lat = c.getString(TAG_LAT);
String longi = c.getString(TAG_LONG);
Log.d("MSG", lat + longi);
String worktime = c.getString(TAG_WORKTIME);
**Log.d("MSG", worktime);**
String distance = calcDist(lat, longi);
lunchList[i][0] = id;
lunchList[i][1] = name;
lunchList[i][2] = picture;
lunchList[i][3] = cost;
lunchList[i][4] = worktime;
lunchList[i][5] = distance ;
gps.stopUsingGPS();
}
break;
case 2:
handler.post(new Runnable() {
#Override
public void run() {
notNetworkDialog.setTitle("Neizdevās izveidot savienojumu!");
notNetworkDialog
.setMessage("Neizdevās izveidot savienojumu ar datu serveri, serveris nav pieejams \n" +
"Mēģināt velreiz?")
.setCancelable(false)
.setPositiveButton("Jā", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new LoadLunches().execute();
}
})
.setNegativeButton("Nē", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
AlertDialog alertDialog = notNetworkDialog.create();
alertDialog.show();
}
});
break;
case 3:
handler.post(new Runnable() {
#Override
public void run() {
notNetworkDialog.setTitle("Neizdevās izveidot savienojumu!");
notNetworkDialog
.setMessage("Neizdevās izveidot savienojumu ar datu serveri, lūdzu pārliecinaties, ka tālrunis ir savienots ar internetu! \n" +
"Mēģināt velreiz?")
.setCancelable(false)
.setPositiveButton("Jā", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new LoadLunches().execute();
}
})
.setNegativeButton("Nē", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
AlertDialog alertDialog = notNetworkDialog.create();
alertDialog.show();
}
});
break;
case 0:
handler.post(new Runnable() {
#Override
public void run() {
notNetworkDialog.setTitle("Kļūda");
notNetworkDialog
.setMessage("Kļūme pieprasījuma! \n" +
"Mēģināt velreiz?")
.setCancelable(false)
.setPositiveButton("Jā", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new LoadLunches().execute();
}
})
.setNegativeButton("Nē", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
AlertDialog alertDialog = notNetworkDialog.create();
alertDialog.show();
}
});
break;
}
}catch(Exception e){
Log.d("MSG",e.toString());
}
return null;
}
Programs works till Log.d("MSG",worktime).
Then skips calculations and continues at these lines:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
lunchAdapter adapter = new lunchAdapter(getActivity(), lunchList, lunchid);
lv.setAdapter(adapter);
}
});
}
I didn't find real cause of such error in my case. Because i recived all data from my DB and further there is no any other files which name could be wrong or missing. So my workaround was quite simple.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
lunchAdapter adapter = new lunchAdapter(getActivity(), lunchList, lunchid);
lv.setAdapter(adapter);
}
});
i added new lines
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(lunchlist==null){
new LoadLunches().execute();
}else{
lunchAdapter adapter = new lunchAdapter(getActivity(), lunchList, lunchid);
lv.setAdapter(adapter);
}
});

Accessing Variables in AlertDialog in Android

In one of my Activity there are some calculations and total price will be calculated.After pressing the submit button it should show an alert dialog with Are you sure you want to pay Rupees:XXX...? here XXX should be the final price which I'm storing in the variable.
in alertdialog.setTitle() I should able to access the variable.
Please help me to solve this.
public void onPay()
{
getItems();
int rate = 0;
if(spare1_item.equals("Tyres") || qty_1.equals("Quantity"))
{
}
else
{
//Toast.makeText(getApplicationContext(), "Now you can pay", 5000).show();
db = this.openOrCreateDatabase("mobile_cycle_clinic", MODE_PRIVATE, null);
c = db.rawQuery("select price from sparelist where name = '"+spare1_item+"'", null);
if(c.moveToNext())
{
do{
price = c.getInt(c.getColumnIndex("price"));
}
while(c.moveToNext());
}
fianl1_qty = Integer.parseInt(qty_1);
rate = rate + price * fianl1_qty;
db.execSQL("insert into spares_items(cycle_id,item_name,quantity,total_price)values('"+cycle_id+"','"+spare1_item+"',"+fianl1_qty+","+rate+")");
//Toast.makeText(getApplicationContext(), ""+rate, 5000).show();
}
Here rate is a static variable and in another method I should use that variable in alertDialog.setMeaasge().
public void storeData(View v)
{
cycle_id = id.getText().toString();
if(cycle_id.equals("") || cycle_id.equals("null"))
{
Toast.makeText(getApplicationContext(), "Please Scan Cycle",5000).show();
}
else
{
AlertDialog.Builder pauseBuild = new AlertDialog.Builder(this);
pauseBuild.setTitle("Pay Alert");
pauseBuild.setMessage("Do you really want to Pay..?"+rate);
pauseBuild.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
//time = sdf.format(new Date());
onPay();
finish();
return;
} });
pauseBuild.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// show it
pauseBuild.show();
}
You can use a function to show or create the AlertDialog.
For example:
private void showConfirmAlertDialog(int price) {
AlertDialog.Builder builder = new AlertDialog.Builder();
builder.setTitle("Are you sure you want to pay rupees: " + price);
....
builder.show();
}
If you perfer getting an instance of AlertDialog, you can change the function to private AlertDialog createConfirmAlertDialg(int price), and use return builder.create(); at the end of function.

Android 4.4 SQLite Not Updating

I have a fully functional SQLite database in my Android App which works perfect on my testing devices (Android 4.0 - 4.3), but I have a user running KitKat and they are unable to update the database. To summarize my code, I have a user click a switch, then asks whether they want to make the change, if so it updates the database table.
Here is my calls to the database from the Activity:
StatusData statusData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_macro);
statusData = new StatusData(getBaseContext());
}
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder;
AlertDialog alertDialog;
switch (v.getId())
case R.id.switchOffSeason:
String season,
seasonHeading = "";
alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog message
if (switchOffSeason.isChecked()) {
season = "This will delete all your current settings and default to the standard diet. This cannot be undone";
seasonHeading = "Set Standard Diet";
} else {
season = "This will delete all your current settings and default to Off-Season diet. This cannot be undone.";
seasonHeading = "Set Off-Season Diet";
}
// set title
alertDialogBuilder.setTitle(seasonHeading);
alertDialogBuilder
.setMessage(season)
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String passedTask = "offSeason";
dropTable task = new dropTable(passedTask);
task.execute(passedTask);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (switchOffSeason.isChecked()) {
switchOffSeason.setChecked(false);
} else {
switchOffSeason.setChecked(true);
}
dialog.cancel();
}
});
alertDialog = alertDialogBuilder.create();
private class dropTable extends AsyncTask<String, Void, String> {
String task;
public dropTable(String passedTask) {
super();
task = passedTask;
}
#Override
protected String doInBackground(String... params) {
if (task.equals("reset")) {
String offSeason = statusData.profileTable()[10];
profileTable = statusData.profileTable();
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
} else if (task.equals("offSeason")) {
if (switchOffSeason.isChecked()) {
statusData.updateFieldProfile(new String[] { "offseason",
"1" });
} else {
statusData.updateFieldProfile(new String[] { "offseason",
"0" });
}
String offSeason = statusData.profileTable()[10];
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
}
return "Executed";
}
Here is my StatusData (Database) class:
public void updateFieldProfile(String updateArray[]) {
open();
Log.i("log", "in method");
String fieldToUpdate = updateArray[0];
String valueToUpdate = updateArray[1];
String query = "UPDATE PROFILE SET " + fieldToUpdate + "="
+ "= ?";
Log.i("logQuery", query);
Cursor c = db.rawQuery(query, new String[] {valueToUpdate});
c.moveToFirst();
c.close();
db.close();
}

AlertDialog in custom Hashmap array adapter

I am creating a custom Hash map array adapter.In that,when the user clicks on an element, an AlertDialog pops up,in that user can see his messaages,
For this I am using this code,
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("PassWord Protected Message");
alert.setMessage("Please Enter The Password to See The Messages");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
// Editable value = input.getText();
// Do something with value!
String we=input.getText().toString();
// Toast.makeText(getApplicationContext(), we, Toast.LENGTH_SHORT ).show();
if (we.equalsIgnoreCase("password"))
{
try
{
String[] splitted = smsList.get( pos ).split("\n");
String sender = splitted[0];
for ( int i = 1; i < splitted.length; ++i )
{
//some code here
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
This AlertDialog will ask user to enter a password.Then user will be able to see the messages.
But I am getting error ,
String[] splitted = smsList.get( pos ).split("\n");
In this,I am getting error on split function and the error is "The method split(String) is undefined for the type HashMap".
You'll have to type cast the smsList to String
String[] splitted = ((String)smsList.get( pos )).split("\n");

Categories

Resources