Show Toast if no results were found - java

Quickly about what I am trying to do. I am creating a script that scans looks for certain Wi-Fi connection. If it finds it, returns to StartingActivity with String.
But how do I make it display Toast if it scanned all connections and didn't found the right one. Because right now, it just sits there and does nothing. And I have to explain user that it found nothing.
Button btnHit;
TextView txtJson;
String urlfinal;
String fssid;
Intent intent;
private static final String TAG = "My Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_connection);
btnHit = (Button) findViewById(R.id.request);
txtJson = (TextView) findViewById(R.id.results);
if (Build.VERSION.SDK_INT > 22) {
final String CoarseLocation = Manifest.permission.ACCESS_COARSE_LOCATION;
final String AccessWifi = Manifest.permission.ACCESS_WIFI_STATE;
final String ChangeWifi = Manifest.permission.CHANGE_WIFI_STATE;
if (checkSelfPermission(CoarseLocation) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
}
if (checkSelfPermission(AccessWifi) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE}, 123);
}
if (checkSelfPermission(ChangeWifi) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE}, 123);
}
}
LocationManager lman = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = false;
try
{
network_enabled = lman.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!network_enabled)
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
mWifiManager.setWifiEnabled(true);
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = mWifiManager.getScanResults();
final int Amount = results.size();
int num = 0;
while (num < Amount)
{
Log.v(TAG, "SSID = " + results.get(num).SSID);
num = num+1;
}
int dis = 0;
String res = "Results:\n\n\n";
while (dis < Amount)
{
res = res + results.get(dis).SSID + "\n\n";
new JsonTask().execute(results.get(dis).SSID);
dis = dis+1;
}
}
}, filter);
mWifiManager.startScan();
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(FindConnection.this);
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
fssid = params[0];
urlfinal = "http://myurl?ssid=" + fssid;
URL url = new URL(urlfinal);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
if (!line.equals("null"))
{
String NetworkSSID = fssid;
String NetworkPass = line;
WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"" + NetworkSSID + "\"";
config.preSharedKey = "\"" + NetworkPass + "\"";
WifiManager wifiman = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
wifiman.addNetwork(config);
List<WifiConfiguration> list = wifiman.getConfiguredNetworks();
for ( WifiConfiguration i : list )
{
if (i.SSID != null && i.SSID.equals("\"" + NetworkSSID + "\""))
{
wifiman.disconnect();
wifiman.enableNetwork(i.networkId, true);
wifiman.reconnect();
break;
}
Intent intent1 = new Intent(FindConnection.this, StartingPage.class);
intent1.putExtra("ssid_name", fssid);
startActivity(intent1);
}
}
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
}
}
UPDATE:
My best guess how to do that is set a timer and if it sits there for 5 seconds then display a toast (that means it hasn't changed activity, so found no results). But it feel that it is not the best way to do it.

Show your toast after the following line, if results.size is zero (0).
final int Amount = results.size();
That is probably suffice. [I am not sure if you can throw toast from a broadcast receiver. I have barely worked with them.]
Cheers!

Related

How to pass the value of a variable from a local class to another class (for its scope)?

I'm having trouble using the value of a variable in a local class and passing it to another class that will be loaded in the intent.
The string value is null and gives an error in the application.
public class Carro extends AppCompatActivity {
ListView lvCarrinhoItems;
Button bFinalizar;
String url2 = "";
String parametros2 = "";
String insertUrl = "http://localhost/registrar.php";
RequestQueue requestQueue;
String result = "";
public static String idOrder = "", dta = "";
public static MeuPedido meuPedido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_carrinho);
lvCarrinhoItems = (ListView) findViewById(R.id.tela5lv);
LayoutInflater layoutInflater = getLayoutInflater();
final Carrinhos carrinhos = CarrinhoHelper.getCarrinhos();
final TextView tvTotalPrice = (TextView) findViewById(R.id.tvsoma);
final TextView tvObspedido = (TextView) findViewById(R.id.etobscar);
tvTotalPrice.setText((Bandeja.MOEDA+String.valueOf(carrinhos.getTotalPrice().setScale(2, BigDecimal.ROUND_HALF_UP))).replace(".",","));
final TCartItemAdapter tcartItemAdapter = new TCartItemAdapter(this);
tcartItemAdapter.updateCartItems(getCarrinhoItems(carrinhos));
lvCarrinhoItems.setAdapter(tcartItemAdapter);
bFinalizar = (Button) findViewById(R.id.button4);
bFinalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alerta = new AlertDialog.Builder(Carro.this);
alerta.setTitle("Confirmação de pedido");
alerta
.setIcon(R.drawable.service)
.setMessage("Deseja confirmar o seu pedido?")
.setCancelable(false)
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
pref = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
final String idcliente = pref.getString("idusuario", null);
final String idrestaurante = CarrinhoHelper.getIdResta();
final String valorpedido = String.valueOf(carrinhos.getTotalPrice());
final String obspedido = tvObspedido.getText().toString();
if (idcliente == null){
Intent intent = new Intent(Carro.this, A2_1semlogin.class);
startActivity(intent);
}else
if (networkInfo != null && networkInfo.isConnected()) {
url2 = "http://localhost/registrarpedido.php";
parametros2 = "idcliente=" + idcliente + "&idrestaurante=" + idrestaurante + "&valorpedido=" + valorpedido + "&obspedido=" + obspedido;
new SolicitaDados2().execute(url2);
} else {
Toast.makeText(getApplicationContext(), "Por favor, verifique sua conexão", Toast.LENGTH_LONG).show();
}
Log.d("DadosRet2", parametros2);
Log.d("DadosRet2", idcliente + ", " + idrestaurante + ", " + valorpedido + ", " + obspedido);
class MyAsyncTaskresources extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream isr = null;
try{
String URL=params[0];
java.net.URL url = new URL( URL);
URLConnection urlConnection = url.openConnection();
isr = new BufferedInputStream(urlConnection.getInputStream());
}
catch(Exception e){
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
s = s + "login info : " + json.getString("idOrder") + " " + json.getString("idcliente") + " " + json.getString("idrestaurante") + " " + json.getString("data");
**STRING QUE DESEJO ACESSAR = idOrder**
idOrder = json.getString("idOrder");
dta = json.getString("data");
List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
Log.d(TAG, "Current shopping cart: " + carrinhos);
Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();
for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
final CarrinhoItem carrinhoItem = new CarrinhoItem();
carrinhoItem.setBandeja((Bandeja) entry.getKey());
carrinhoItem.setQuantidade(entry.getValue());
carrinhoItems.add(carrinhoItem);
final String idcomida = carrinhoItem.getBandeja().getIdcomida();
final String quantidade = carrinhoItem.getBandeja().getQuantidade();
final BigDecimal valorunit = carrinhoItem.getBandeja().getPreco();
final String adicional = carrinhoItem.getBandeja().getAdicional();
final String obsproduto = carrinhoItem.getBandeja().getObsproduto();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("idOrder",idOrder);
parameters.put("idcomida", idcomida);
parameters.put("quantidade", quantidade);
parameters.put("valorunit", valorunit.toString());
parameters.put("adicional", adicional);
parameters.put("obsproduto", obsproduto);
final MeuPedido meupedido = new MeuPedido();
String novaId = idOrder;
meupedido.setmPedido(novaId);
return parameters;
}
};
requestQueue.add(request);
}
break;
}
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
}
new MyAsyncTaskresources().execute("http://localhost/sel.php?idcliente="+idcliente+"&idrestaurante=" +idrestaurante);
}
});
AlertDialog alertaDialog = alerta.create();
alertaDialog.show();
}
});
}
public static final List<CarrinhoItem> getCarrinhoItems(Carrinhos carrinhos) {
List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
Log.d(TAG, "Current shopping cart: " + carrinhos);
Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();
for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
final CarrinhoItem carrinhoItem = new CarrinhoItem();
carrinhoItem.setBandeja((Bandeja) entry.getKey());
carrinhoItem.setQuantidade(entry.getValue());
carrinhoItems.add(carrinhoItem);
final String comida = carrinhoItem.getBandeja().getComida();
final String adicional = carrinhoItem.getBandeja().getAdicional();
final String quantidade = carrinhoItem.getBandeja().getQuantidade();
final BigDecimal valor = carrinhoItem.getBandeja().getPreco();
}
return carrinhoItems;
}
private class SolicitaDados2 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametros2);
}
#Override
protected void onPostExecute(String resultado) {
if (resultado.contains("pedido_ok")) {
Toast.makeText(getApplicationContext(), "Registro efetuado com sucesso", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Carro.this, Anotafiscal.class);
** LOCAL ONDE DESEJO INSERIR A STRING**
String hjhj = idOrder ;
intent.putExtra("iddopedido",hjhj);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Ocorreu um erro no cadastro", Toast.LENGTH_LONG).show();
}
}
}
}

java.lang.ClassCastException: java.util.HashMap cannot be cast to android.content.pm.PackageInfo

i have lists of apps sorted in hash map from json parser. While i try to view the apps info onClick it crashes here's the code
please bear in mind that i have other listviews of different app categories
public class iqa extends Fragment {
ListView communication;
ArrayList<HashMap<String, String>> communicationlist = new ArrayList<HashMap<String, String>>();
public class now extends AsyncTask <HttpURLConnection, Void,Void> implements AdapterView.OnItemClickListener {
//returns app name using package name as input
public String appName(String pack){
String Name = null;
try{
PackageManager packManager = getContext().getPackageManager();
ApplicationInfo app = getContext().getPackageManager().getApplicationInfo(pack, 0);
Name = packManager.getApplicationLabel(app).toString();
}
catch(Exception e){
e.printStackTrace();
}
return Name;
}
private void getAppCategories() throws IOException, JSONException
{
BufferedReader bufferedReader = null;
HttpURLConnection urlConnection = null;
BufferedWriter bufferedWriter = null;
StringBuilder result = new StringBuilder();
//Create JSON object to send to webservice
JSONObject jsonObjectSend = new JSONObject();
JSONArray jsonArrayPakages = new JSONArray();
PackageManager packageManager;
List<ResolveInfo> listApps; //this list store all app in device
try {
packageManager = getActivity().getPackageManager();
Intent filterApp = new Intent(Intent.ACTION_MAIN);
filterApp.addCategory(Intent.CATEGORY_LAUNCHER);
listApps = packageManager.queryIntentActivities(filterApp, PackageManager.GET_META_DATA);
for (ResolveInfo app : listApps){
jsonArrayPakages.put(app.activityInfo.packageName.trim());
}
jsonObjectSend.put("packages", jsonArrayPakages);
Log.d("json", jsonObjectSend.toString());
URL url = new URL("http://getdatafor.appspot.com/data?key=53972606b926d38191a5446fdff89e377873d767fabedf6d");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(30000); /* milliseconds */
urlConnection.setReadTimeout(30000); /* milliseconds */
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application-json");
urlConnection.setDoOutput(true); /* allow output to send data */
urlConnection.connect();
OutputStream outputStream = urlConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(jsonObjectSend.toString());
bufferedWriter.flush();
InputStream inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Read data
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
/*Parse JSON**********************************************************************************/
JSONObject jsonObjectResult = new JSONObject(result.toString().trim());
JSONArray jsonArrayApps = jsonObjectResult.getJSONArray("apps");
for (int j = 0; j < jsonArrayApps.length(); j++) {
JSONObject jsonObjectApp = jsonArrayApps.getJSONObject(j);
String packageName = jsonObjectApp.getString("package").trim();
String cate = jsonObjectApp.getString("category").trim();
Log.d("result", (j + 1) + "---> : " + packageName + "---" + cate);
HashMap<String, String> communicationmap = new HashMap<String, String>();
String Communication = "Communication";
String ca = e.getString("category").trim();
String vit = e.getString("package").trim();
String va = appName(vit);
if (ca.equals(Communication) || ca.equals(Social) || ca.equals(dat))
{
boolean communicexist = communicationmap.containsValue(va);
if (communicexist == false)
{
communicationmap.put("Name", va);
communicationmap.put("cate", ca);
communicationlist.add(communicationmap);
}
else
{
cmap.put("Name", va);
cmap.put("cate", ca);
}
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
#Override
protected Void doInBackground(HttpURLConnection... params) {
try {
getAppCategories();
} catch (IOException e) {
Log.d("tag", "Net work error: " + e.getMessage(), e);
} catch (JSONException e) {
Log.d("tag", "JSON is not valid: " + e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// Keys used in Hashmap
String[] from = { "Name","cate" };
// Ids of views in listview_layout
int[] to = { R.id.packa,R.id.catego};
ListAdapter communicationadapter = new SimpleAdapter(getActivity().getBaseContext(), communicationlist,R.layout.lay,from,to);
communication.setAdapter(communicationadapter);
communication.setOnItemClickListener(this);
Utility.setListViewHeightBasedOnChildren(communication);
super.onPostExecute(aVoid);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//THIS IS WHERE THE ERROR STARTS
PackageInfo packageInfo = (PackageInfo) parent.getItemAtPosition(position);
AppData appData = (AppData) getActivity().getApplicationContext();
appData.setPackageInfo(packageInfo);
try {
Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
startActivity(appInfo);
}
catch (Exception e)
{
Log.e(TAG, "error in intent");
}
}
}
THE OnItemClick ADAPTER IS WHERE THE ERROR STARTS
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PackageInfo packageInfo = (PackageInfo) parent.getItemAtPosition(position);
AppData appData = (AppData) getActivity().getApplicationContext();
appData.setPackageInfo(packageInfo);
try {
Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
startActivity(appInfo);
}
catch (Exception e)
{
Log.e(TAG, "error in intent");
}
}
After implementing, it like this
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,String> clickedItem = (HashMap<String, String>) parent.getItemAtPosition(position);
String packageName = clickedItem.get("package");
try {
PackageManager packManager = getContext().getPackageManager();
ApplicationInfo app = getContext().getPackageManager().getApplicationInfo(packageName, 0);
String appName = packManager.getApplicationLabel(app).toString();
PackageInfo packageInfo = (PackageInfo) parent.getItemAtPosition(position);
AppData appData = (AppData) getActivity().getApplicationContext();
appData.setPackageInfo(packageInfo);
}
catch (Exception e)
{
e.printStackTrace();
}
try {
Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
startActivity(appInfo);
}
catch (Exception e)
{
Log.e(TAG, "error in intent");
}
}
i got the following error
FATAL EXCEPTION: main
Process: com.finalyearstudentvitus.splash, PID: 25698
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.finalyearstudentvitus.splash/com.finalyearstudentvitus.splash.permdisabled}: java.lang.NullPointerException: Attempt to read from field 'android.content.pm.ApplicationInfo android.content.pm.PackageInfo.applicationInfo' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NullPointerException: Attempt to read from field 'android.content.pm.ApplicationInfo android.content.pm.PackageInfo.applicationInfo' on a null object reference
at com.finalyearstudentvitus.splash.permdisabled.setValues(permdisabled.java:44)
at com.finalyearstudentvitus.splash.permdisabled.onCreate(permdisabled.java:31)
at android.app.Activity.performCreate(Activity.java:6686)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method)
the following is permdisabled.java class
public class permdisabled extends Activity {
TextView appLabel, packageName;
TextView req_permission, diss_perission;
PackageInfo packageInfo;
String pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.permdisabled);
findViewsById();
AppData appData = (AppData) getApplicationContext();
packageInfo = appData.getPackageInfo();
setValues();
}
private void findViewsById() {
appLabel = (TextView) findViewById(R.id.appplabel);
packageName = (TextView) findViewById(R.id.packagee_name);
req_permission = (TextView) findViewById(R.id.req_permissionn);
diss_perission = (TextView) findViewById(R.id.diss_permissionn);
}
private void setValues()
{
// APP name ERROR STARTS HERE
appLabel.setText(getPackageManager().getApplicationLabel(
packageInfo.applicationInfo));
// package name
packageName.setText(packageInfo.packageName);
// uses-permission
if (packageInfo.requestedPermissions != null) {
req_permission.setText(getPermissions(packageInfo.requestedPermissions));
pass = req_permission.toString();
}
else {
req_permission.setText("-");
}
}
// Convert string array to comma separated string
private String getPermissions(String[] requestedPermissions) {
String permission = "";
for (int i = 0; i < requestedPermissions.length; i++) {
permission = permission + requestedPermissions[i] + ",\n";
}
return permission;
}
}
try implementing following :
// Modify your HashMap like this
if (communicexist == false)
{
communicationmap.put("package", vit);
communicationmap.put("cate", ca);
communicationlist.add(communicationmap);
}
else
{
cmap.put("package", vit);
cmap.put("cate", ca);
}
Then in onItemClick,
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,String> clickedItem = parent.getItemAtPosition(position);
String packageName = clickedItem.get("package");
try{
PackageManager packManager = getContext().getPackageManager();
ApplicationInfo app = getContext().getPackageManager().getApplicationInfo(packageName , 0);
String appName = packManager.getApplicationLabel(app).toString();
AppData appData = (AppData) getActivity().getApplicationContext();
appData.setPackageInfo(packageInfo);
}
catch(Exception e){
e.printStackTrace();
}
try {
Intent appInfo = new Intent(getActivity().getApplicationContext(), permdisabled.class);
startActivity(appInfo);
}
catch (Exception e)
{
Log.e(TAG, "error in intent");
}
}

Android 23 (Marshmallow) and Higher permission Having a heck of a time

First, Thank you very much for looking at this!
I've been handed an app someone wrote before Marshmallow. I've fixed the Theme and SSL issues that came with Nougat but I'm having a heck of a time with Write to External Storage Permission or something associated. Debug is lacking or I'm not using it properly. This app creates a file onto the device and adds the ssl cert and login info in a folder called My Documents.
When I open the app it say network timeout right away. That message is from LoginActivity.java . I click ok then I get the Android pop up asking to allow permissions. I allow it. After that I put in the username and password and click login. It instantly gives the network timeout message from LoginActivity.java. LoginActivity.java is the Main Activity. If I click ok it's back to the login screen. All permissions are in the Android Manifest as well.
Maybe it's not from permissions but it works fine in version 22. I've worked on this 12 hours today and thought if you guys could help that'd be great. I'm a network engineer dabbling in Java so please excuse my question if it's "ugly".
I tried to find a line by line debug like I've done with phonegap but wasn't successful.
My Apps Main Activity LoginActivity.java and associated activity is LoginScreen.java and shown below.
LoginActivity.java
public class LoginActivity extends Activity {
private String userName = "";
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blackactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new SSLHandler().execute();
if(Variables.testing)
{
}
if (hasPermissions()){
// our app has permissions.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}
}
//Begin Permission Methods
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
//End Permission Methods
private void attemptLogin() throws IOException {
String filepath = Variables.fileFolder + "/login.txt";
File tempFile = new File(filepath);
if (!tempFile.exists()) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
BufferedReader reader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
} catch (Exception e) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
fileExists = true;
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean success = false;
Boolean timedOut = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setMessage("Network Timed Out").setTitle("Notice");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (result) {
Variables.storeTechName(userName, LoginActivity.this);
Variables.assignTechName();
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginActivity.this,
"Loading...", "Logging you in...");
mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
System.out.println(e.toString());
timedOut = true;
}
return success;
}
}
#Override
protected void onPause() {
super.onPause();
}
}
LoginScreen.java
public class LoginScreen extends Activity {
private String userName;
private static final int PERMS_REQUEST_CODE = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (!SSLHandler.loaded) {
new SSLHandler().execute();
}
// Creates login and name files and attempts to log in
Button createButton = (Button) findViewById(R.id.createbutton);
createButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((EditText) findViewById(R.id.usernamefield)).getText()
.toString().isEmpty()
|| ((EditText) findViewById(R.id.passwordfield))
.getText().toString().isEmpty()) {
GUI.oneOptionDialog(LoginScreen.this,
"Missing field entries", "OK", false);
} else {
createLoginFile();
((EditText) findViewById(R.id.usernamefield)).setText("");
((EditText) findViewById(R.id.passwordfield)).setText("");
attemptLogin();
}
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
createFiles();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void createFiles() {
}
private void attemptLogin() {
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
try {
String filepath = Variables.fileFolder + "/login.txt";
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
fileExists = true;
}
catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this,
"Login file does not exist. Please enter login info.",
"OK", false);
}
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean timedOut = false;
Boolean success = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
GUI.oneOptionDialog(LoginScreen.this, "Network Timed Out",
"OK", false);
} else {
if (result) {
Variables.storeTechName(userName, LoginScreen.this);
Variables.assignTechName();
startActivity(new Intent(LoginScreen.this,
MainActivity.class));
finish();
} else {
GUI.oneOptionDialog(LoginScreen.this,
"Login Failed. Please try again.", "OK", false);
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginScreen.this,
"Loading...", "Logging you in...");
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
jc.setConnectTimeout(Variables.timeoutTimeLimit);
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
timedOut = true;
}
return success;
}
}
private void createLoginFile() {
try {
File dir = new File(Variables.fileFolder);
if (!dir.isDirectory()) {
dir.mkdirs();
}
String filepath = Variables.fileFolder + "/Login.txt";
String username = ((EditText) findViewById(R.id.usernamefield))
.getText().toString();
String password = ((EditText) findViewById(R.id.passwordfield))
.getText().toString();
String salt = new RandomString(20).nextString();
String passwordHash = Variables.sha256(password + salt);
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
writer.println(username);
writer.println(passwordHash);
writer.println(salt);
writer.close();
} catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this, e.toString(), "OK", false);
}
}
#Override
protected void onPause() {
super.onPause();
}
}

cant set text in postExecute ,Async, Android

I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}

Sending SMS on android through a Third-party Gateway

Please i would like to know what is wrong with the below code and why it does not deliver sms, when i debug no error was found. please can i get help?
public class LaunchSMS extends Activity implements OnClickListener {
private TextView phone;
private TextView phone2;
private EditText TFmsg;
private TextView TVfrom;
Button btnsend;
static final String username = "xxxxxxx";
static final String password = "xxxxxxx";
static String url = "http://www.esmsafrica.com/components/com_spc/smsapi.php";
static final String charset = "UTF-8";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
TFmsg = (EditText) findViewById(R.id.TFmsg);
phone = (TextView) findViewById(R.id.phone);
btnsend = (Button) findViewById(R.id.btnsend);
Button mBtnContacts = (Button) findViewById(R.id.mBtnContacts);
Button btnLogout = (Button) findViewById(R.id.btnlogout);
mBtnContacts.setOnClickListener(this);
btnsend.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
showSelectedNumber(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(String number) {
phone.setText(number);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.mBtnContacts) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
if (v.getId() == R.id.btnsend) {
String reciever = phone.getText().toString();
String message = TFmsg.getText().toString();
if (reciever.length() > 0 && message.length() > 0)
try {
sendSMS(reciever, message);
} catch (Exception e) {
e.printStackTrace();
}
else
Toast.makeText(getBaseContext(),
"Please enter both reciever number and message.",
Toast.LENGTH_SHORT).show();
}
if (v.getId() == R.id.btnlogout) {
logoutUser();
}
}
private void logoutUser() {
Intent intent = new Intent(LaunchSMS.this, Sendsms.class);
startActivity(intent);
finish();
}
public static void sendSMS(String reciever, String message) throws Exception {
System.out.println("Welcome to eSMS");
//To establish the connection and perform the post request
URLConnection connection = new URL(url + "?" + buildRequestString(reciever,message)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
//This automatically fires the request and we can use it to determine the response status
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
//System.out.println(br);
System.out.println(br.readLine());
}
private static String buildRequestString(String reciever, String message) throws UnsupportedEncodingException {
String [] params = new String [5];
params[0] = username;
params[1] = password;
params[2] = message;
params[3] = reciever;
params[4] = "esmsafrica";
String query = String.format("uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
URLEncoder.encode(params[0],charset),
URLEncoder.encode(params[1],charset),
URLEncoder.encode(params[2],charset),
URLEncoder.encode(params[3],charset),
URLEncoder.encode(params[4],charset)
);
return query;
}
public static void main(String [] args) throws Exception {
System.out.println("enter Mobile No:");
Scanner scanIn = new Scanner(System.in);
String testPhoneNo = scanIn.nextLine();
scanIn.close();
String testMessage = "Sending Messages";
sendSMS(testPhoneNo, testMessage);
}
}
I have implemented Send SMS from MSG91 messaging service.
public static void sendSMS(String reciever, String message) {
URLConnection myURLConnection=null;
URL myURL=null;
BufferedReader reader=null;
try
{
//prepare connection
myURL = new URL(buildRequestString(reciever, message));
myURLConnection = myURL.openConnection();
myURLConnection.connect();
reader= new BufferedReader(new
InputStreamReader(myURLConnection.getInputStream()));
//reading response
String response;
while ((response = reader.readLine()) != null)
//print response
Log.d("RESPONSE", ""+response);
//finally close connection
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String buildRequestString(String reciever, String message){
//encoding message
String encoded_message=URLEncoder.encode(message);
//Send SMS API
String mainUrl="http://api.msg91.com/sendhttp.php?";
//Prepare parameter string
StringBuilder sbPostData= new StringBuilder(mainUrl);
sbPostData.append("authkey="+authkey);
sbPostData.append("&mobiles="+reciever);
sbPostData.append("&message="+encoded_message);
sbPostData.append("&route="+"4");
sbPostData.append("&sender="+"CustomSenderID");
return sbPostData.toString();
}

Categories