[Q] How do I display text from a messgae into a toast? - Java for Android App Development

Hi all skilled developers,
I am a newbie in coding, and I just want to make some small changes to my app.
It is a licensing feature.
1) Licensee information are stored at a very simple website. With columns for Names, IMEI and Remarks.
2) I have the following chunk of code:
Code:
if(hadLicense) {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is registered.\nWelcome.")
.setPositiveButton("Send", new DialogInterface.OnClickListener()
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
I want to show a toast saying,
Welcome, Shawn. Your device is registered till DD/MM/YY.
Click to expand...
Click to collapse
Can someone teach me how I can go about doing this?:silly:

You can show a toast using:
Code:
Toast.makeText(context, text, duration).show();
Just make the text String first with the text and time. For duration use Toast.LENGTH_SHORT

SimplicityApks,
Thanks for your reply. I still don't really know what you mean. how do I echo a text from a website into the app's toast?
This is the full code:
Code:
protected Void doInBackground(Void... params) {
String url_for_sale = "www(dot)heyfellas(dot)com/guru/index.php";
parseLicense(url_for_sale);
return null;
}
@Override
protected void onPostExecute(Void result) {
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
final String imei = mngr.getDeviceId();
boolean hadLicense = false;
for(LicenseInfo license: licenses) {
if(license.phoneIMEI.equals(imei))
hadLicense = true;
}
if(hadLicense) {
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
} else {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is not registered.\nPlease send your details to the admin.")
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "Request for license");
i.putExtra(Intent.EXTRA_TEXT , "UserName: \n\nPhone Number: \n\nEmail: \n\nIMEI: " + imei);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(PropertyGuruSplash.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create().show();
}
}
}

You need
[java]
String name = ...;
String date = ....;
Toast.makeToast(Activity.this, name + ", you have registered since "+date, Toast.LENGTH_SHORT).show();[/java]

I suppose, you are strong at server side than in client programming? Then echo the result in your desired format in your php and read it in java then display it in toast. Use the below snippet:
Code:
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www(dot)heyfellas(dot)com/guru/index.php");
HttpResponse response = httpclient.execute(httppost);
String Result = EntityUtils.toString(response.getEntity());
Toast.makeText(Context, Result, Toast.LENGTH_SHORT).show();

Related

Cursor help!

I'm new to using cursors to obtain data from the device. I'm working on a music player (see market link in signature) and I need to be able to list (and eventually play) the music found on the sdcard. I have some code, but I can't seem to get it to work
Here's the code I found on a website, but it leads to a force-close:
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null, null
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
Here's my attempt at fixing it, which still leads to a force-close:
public class test3 extends Activity {
TextView view = (TextView) findViewById(R.id.text1);
ListView list;
private ArrayAdapter<String> adapter;
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
ArrayList<String> _list = new ArrayList<String>(Arrays.asList(projection));
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_list);
list.setAdapter(adapter);
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null,
MediaStore.MediaColumns.DISPLAY_NAME + "ASC"
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
What am I doing wrong? Both codes lead to a force-close and I can't think of anything else to do. Thanks in advance.
did you set the correct permissions in the android manifest?
*slaps hand to forehead* I always forget about the manifest. Lol. Ummmm....what all am I supposed to put in there for these codes? Do both codes look like they would accomplish the same thing?
Well, I've written hundreds of Cursors in Android and I don't run my loop like you do, so, as a suggestion:
Code:
Cursror c = yada, yada;
if(c.moveToFirst()) {
do {
// TO DO HERE...
} while(c.moveToNext());
}
c.close();
Never had a problem.
Awesome! Thanks. Ill try it when I get a chance

SAP webservice consuming

Hi all ,
I am developing an android app to invoke a webservice in SAP side.i have deployed the webservice and i have sucessfully invoked it using soapui.i am connected to my sap network via vpn.when i try to invoke the webservice from eclipse in the emulator.i am getting an warning "UnknownHostException: Unable to resolve host "myhostaddress": No address associated with hostname".
here is the code i used
public class customer_complaint extends Activity {
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "";
private static String METHOD_NAME1 = "ZfmCoeMob";
private static String NAMESPACE = "urn:sap-com:document:sap:soap:functions:mc-style";
private static String URL = "hypertextprotocol://10.201.52.86:8003/sap/bc/srt/wsdl/bndg_E2C5751FB4DDC7F192D3000E0CB7EB52/wsdl11/allinone/ws_policy/document?sap-language=EN&sap-client=100&sap-user=abap&[email protected]";
Button submit;
EditText editText_Customer,editText_Invoice;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.customer_complaint);
submit = (Button)findViewById(R.id.submit);
editText_Customer = (EditText)findViewById(R.id.editText_Customer);
editText_Invoice = (EditText)findViewById(R.id.editText_Invoice);
submit.setOnClickListener(new View.OnClickListener()
{
@override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("ZfmCoeMob",editText_Customer.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
// SoapObject result = (SoapObject)envelope.bodyIn;
SoapPrimitive resultString = (SoapPrimitive)envelope.getResponse();
if(resultString != null)
{
//Get the first property and change the label text
// editText_Invoice.setText(result.getProperty(0).toString());
editText_Invoice.setText(resultString.toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
is it something wrong due to the url link.but i am able to invoke the same service using soapui.i have attached my wsdl file with this thread.

Android getting SMS body from inbox

Hi,
I want to get body of SMS when I click on one. I have tried an approach simmilar to contact picker. Here is my code :
public class Decrypt extends Fragment {
Button loadButton;
EditText smsDisplay;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.decrypt, null);
// Button loadButton=(Button)v.findViewById(R.id.)
loadButton=(Button)v.findViewById(R.id.buttonLoad);
smsDisplay=(EditText)v.findViewById(R.id.editTextLoad);
loadButton.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
//sendIntent.setType(Sm)
//sendIntent.putExtra("sms_body","");
startActivityForResult(sendIntent,2);
}
});
return v;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
// if (resultCode == Activity.RESULT_OK) {
Uri ur = data.getData();
Cursor c = getActivity().getContentResolver().query(ur, null, null, null, null);
if (c.moveToFirst()) {
String s = c.getString(c.getColumnIndex("body"));
System.out.println(s);
Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
smsDisplay.setText(s);
}
}catch(Exception e){
e.printStackTrace();
}
// }
}
}
It opens a Inbox like when I open original sms app in anroid, but when I click on one message it doesnt copy body of that sms in my edittext. Please couul you look at my code and find mistake?
Thanks a lot for your time

How do I implement a onscroll Listener to my listview?

I have a large data to load from JSON.
I have implemented a custom list view by following a tutorial, now since the data is huge I want it load as the user scrolls.
This is my LoadRestaurant class code which is inside the main activity.
Code:
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(SearchAll.this, RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
intent.putExtra("login_id", loginId);
startActivity(intent);
}
});
}
});
}
}
}
I want to load around 20 restaurants and then it auto loads another 20 as soon as user reaches the end of first 20.
There are lots of tutorials online but its confusing to implement.
Please help me out!
The custom ListView, support for automatic loading you can try https://github.com/chrisbanes/Android-PullToRefresh

BLE Application (Display data from characteristic in a textView)

I used the BluetoothLeGatt example code to write an app that automatically connects to a bonded BLE peripheral upon launching the app. Now i am trying to display the data from one of the peripheral's characteristic in a textView. The BluetoothLeGatt example code only demonstrates this using ExpandableListView.OnChildClickListener, my app should require no user input and simply get he data from the characteristic. This is what i have so far:
Code:
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
mConnectionState.setTextColor(Color.parseColor("#FF17AA00"));
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
*edit*
UUID chara = UUID.fromString("c97433f0-be8f-4dc8-b6f0-5343e6100eb4");
List<BluetoothGattService> servs = mBluetoothLeService.getSupportedGattServices();
for (int i = 0; servs.size() > i; i++) {
List<BluetoothGattCharacteristic> charac = servs.get(i).getCharacteristics();
for (int j = 0; charac.size() > i; i++) {
BluetoothGattCharacteristic ch = charac.get(i);
if (ch.getUuid() == chara) {
mBluetoothLeService.readCharacteristic(ch);
mBluetoothLeService.setCharacteristicNotification(ch, true);
}
}
}
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_control);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
I've successfully connected to an already bonded device, but now im trying to get the data from a characteristic using its uuid and display it in a textView. The BluetoothLeGatt example shows how a characteristic is selected by a user using an expandable list view onclick listener displaying the supported characteristics. I want to bypass all that and just get the data from the characteristic with the known uuid.
-EDIT-
figured it out

Categories

Resources