• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Json parser; URL question

This is MainActivity.java

Code:
package com.tomtom.jsonreader;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private ListView lv;

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            // Making a request to url and getting response
           // String url = "http://10.0.2.2/mydocs/test_data.json";
           // String url = "https://api.myjson.com/bins/xalc8";
            String url = "http://api.androidhive.info/contacts/";
             //String url = "https://teamtreehouse.com/matthew.json";
            // String url = "http://api.openweathermap.org/data/2.5/weather?q=cape%20town&units=metric&appid=f8d99ec86985a645328e23aad42c07d8/";
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("contacts");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        String id = c.getString("id");
                        String name = c.getString("name");
                        String email = c.getString("email");
                        String address = c.getString("address");
                        String gender = c.getString("gender");

                        // Phone node is JSON Object
                        JSONObject phone = c.getJSONObject("phone");
                        String mobile = phone.getString("mobile");
                        String home = phone.getString("home");
                        String office = phone.getString("office");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("name", name);
                        contact.put("email", email);
                        contact.put("mobile", mobile);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
                    R.layout.list_item, new String[]{ "email","mobile"},
                    new int[]{R.id.email, R.id.mobile});
            lv.setAdapter(adapter);
        }
    }
}
This is HttpHandler.java
Code:
package com.tomtom.jsonreader;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

The logcat result is as shown in my post, not sure if there's any other useful response to show.

Help Lagging and closing out apps and processes

How can I go about finding out exactly which app or apps are causing my phone to freeze in the middle of, close out my texting window, and pretty much any other window I have open at the time. Even when I am recording a video or creating my next beat....it will lag and/or completely close out. I went about using the king root to root by phone, but I'm not sure if I didn't do it correctly and maybe that's causing the issues??
King root doesn't root the S8 +. You should back up anything important to you and reflash the correct firmware.

F-droid info

"?"-droid...too much noise and not enough info. I was taught to never install anything NOT from Play Store. So, where does one get educated on all things NOT GPS? Does this stuff work with non-rooted phones? No nag screens from not going thru GPS?

Russ

You make a good point. It is wise not to download from unknown sources (third party). That is the best policy, however some of use like myself choose to venture outside the PS and download from reputable sites like APKmirror, G-droid,F-droid, XDA..... I'm rooted but the alternative app stores don't require root.

Swipe with OnFling in Listview

I am working on swipe between app screens. App screen has list view with vertical scrolling. I want to swipe horizontally(left to right & right to left)
Used Library for list view: com.handmark.pulltorefresh.library, implemented swipe with OnFlingListener.

When I try to swipe from right to left, it able to swipe. But in sometime swipe from right to left and hold the finger, it detects swipe as left to right.

onInterceptTouchEvent override method called automatically for left to right swipe.

How to solve this issue.

If anyone please help me to solve this

Trusted feac unlock

I think they meant "Trusted face unlock". Even so, that's not a question so I don't know how anyone is supposed to help.

Anyway I'm going to guess that (a) this is intended to be a question, and (b) the question is "why can't I find it?". If the question was anything else you'll have to tell us what it was if you want an answer.

"Trusted face unlock" is an insecure screen lock method that was introduced in 2014. It's officially unsupported now, though there are probably still some old phones out there that have it (my Pixel, bought in 2017, never supported it). So if the question is "why can't I find it?" then probably the answer is that your phone's software is new enough that it doesn't have this option (though as that's an old phone and won't have had an update recently I'm slightly surprised it doesn't).

Why do I have 250 apps

You should be able to see all of the apps via Settings > Apps, show all, and tell it to show system apps.

That will show you everything. I suspect that a lot of your 250 are system apps, including services which don't show in the app drawer. My Pixel 2 is much lighter on pre-installed apps that most phones, and even so I'm pretty sure that it came with rather more than 50 when all of the system apps were included. LG are not noted for being parsimonious with pre-installed apps (though not as extreme as Samsung), so I expect you have more.

Help How to enable unknown sources to play Days After on my Samsung Galaxy S9+?

Personally I've authorised one of my file managers to install apps, but none of my browsers. My thinking is that I know that dodgy ads have pushed downloads to people in the past and so I'm happier with the browser itself not being authorised to install anything (I don't know whether some ad script could make it do that without my intervention, but why take a chance).

FDR-persistent: The ID survives factory reset.

Hi,
I need a device identifier that persists after the app is uninstalled and reinstalled. I know that UUID class provides an identifier with the method

String uniqueID = UUID.randomUUID().toString();

but Android guideline is unclear about its scope and persistence. In next paragraph it says:

Resettability and persistence

Resettability and persistence define the lifespan of the identifier and explain how it can be reset. Common reset triggers include: in-app resets, resets via System Settings, resets on launch, and resets on installation. Android identifiers can have varying lifespans, but the lifespan is usually related to how the ID is reset:

  • Session-only: A new ID is used every time the user restarts the app.
  • Install-reset: A new ID is used every time user uninstalls and reinstalls the app.
  • FDR-reset: A new ID is used every time the user factory-resets the device.
  • FDR-persistent: The ID survives factory reset.
Resettability gives users the ability to create a new ID that is disassociated from any existing profile information. The longer, and more reliably, an identifier persists, such as one that persists across factory resets, the greater the risk that the user may be subjected to long-term tracking. If the identifier is reset upon app reinstall, this reduces the persistence and provides a means for the ID to be reset, even if there is no explicit user control to reset it from within the app or System Settings.

Please tell me how can I use FDR-persistent: The ID survives factory reset.

Help Application for managing and allocating maximum RAM for heavy application acceleration

Hi Mikedt ,

True it is slow, but surprisingly the app (which is used as a virtual machine) is built really well in a way that works quite reasonably and quickly, but I have heavy software (with a lot of information) that I open in windows (which is installed on this virtual machine app) that slows me down In any case, I'm really looking for a solution to speed up the work (whether it's through some Android settings or downloading an app that can manage RAM)

Thanks in advance ,

Maybe it could be done with rooting and something custom?

If you really do need your memory hungry Windows software on a mobile device, perhaps a small Windows tablet would be a better option for you? Or even a GPD mini laptop, some of which are not much bigger than a phone.

Apps Learning about Tabs in Android, have a couple questions

At Developer.Android.com, I've been reading, practicing and trying to learn about Android development. In working with some built-in activity resources available through the Android Studio, I've been trying to learn how to use and code multiple tab activities. I'm sure there is a good resource for these but I just hadn't found it yet.

My question(s):
What is the purpose of PageViewModel class? I assume I build out each UI tab through it's corresponding XML and JAVA class files, but I'm unclear on how I should use the PageViewModel class. It appears that is simply manages the calls to the separate tabs (fragments) and I leave it alone.

The built-in example I have has a "Live Data" feature... I'm not sure if that is something I need or not?

Thanks

Updating from 5.01 to something higher.

As far as I can tell 5.0.1 was the last official release for the S4, so it's probably correct when it says it's up to date. Though I've not gone through all of the many models of S4, as there are too many: if you can tell us which model you have it will be easier to be definitive.

It may be that there are custom ROMs based on later Android versions (though not necessarily using the Samsung user interface). So if you are willing to get into rooting and modifying the phone there may be options.

Help Notifications missing from status bar

I don't use Galaxy S9+, but I think some way bellow from my Xiaomi experience can help you in some way:
- Restart the device:
Old but gold :v you should do it first before coming to the next way.
- Check the "Do not disturb" status:
Most Android phones come with a Do Not Disturb mode. This mode allows your Android device to block all notifications, spam emails, etc. except applications or software that you allow. So please check the Do not disturb mode to turn it off.
Settings > Sound & vibration > Sound. Turn of the DND – Do Not Disturb if it's turned on.
With S9 or some modern Android devices, you can search DND on the search bar on the top in Settings
- Check App notifications:
Settings > Notifications & status bar > App notifications
.Here you select the application to check the notification in the section Show notifications
- Check out the manufacturer's exclusive battery savers:
Some manufacturers have added more battery-saving tools, automatically blocking applications that are deemed unimportant. So you need to check if your Android device comes with any other internal optimization features. You can check it in the Security section os the Battery section.
- Check whether the background data is enabled:
You can restrict applications to access mobile data in the background. This makes the application unable to connect to the internet, thereby potentially not showing notifications on your phone.
Settings > Data usage > Choose an app > Check Background data.
=====
If you can make it, you can reinstall the old version or do a warranty check. Hope you will make it. Good luck!

Mr.M

No, pressing and holding the power button forces a restart, it doesn't put you into safe mode by itself. Try for longer, since it really should be extremely difficult for an app to disable this feature (unless the power button itself is broken?).

To get into safe mode you need to press some other buttons when rebooting. Since you've not told us what model tablet this is there is no way of telling you which buttons (the manufacturer isn't enough, since different models of different ages have different buttons available).

In the extreme you can force a reboot by just not charging the tablet and letting it shut down when the battery runs out. Then when it's recharged you can turn it on, and try to enter safe mode as it restarts.

Can you tell us more about this app? Because that's the other way we can try to learn something about the problem, but all we currently know is that "some app" is blocking the screen.

Unfortunately it's no longer possible to uninstall an app over the internet from the play store website (it used to be, about 5-7 years ago, but not now). If there's really no way of getting past this, i.e. even after powering down it just comes back up with this app, safe mode won't work, and you can't get into recovery mode, you may be able to use Google's "find my device" (formerly Android Device Manager) to factory reset it, but as that wipes everything it's a bit of a last resort.

Apps Android Studio - how to enable code changes button

Hi
I am using 3.5.3 and was wanting to enable the "Apply Code Changes" - (it is greyed out.) the popup message reads: "apply code changes disabled incompatible device api level"
My compile Sdk version is: 28(API 28: Android 9.0 {Pie))
My build tools version is 29.0.2
Is the problem that I need Sdk version 29 to match the build tools version ?
Thanks all
Russell

Filter

Back
Top Bottom