Android app can not connect to localhost server - java

I've created Database in my localhost, and want parse data from it with android app.I Create server with NodeJS and it works i can see the Database in browser, but my android app can't connect with this localhost server.
Here is my Java code.
public class MainActivity extends AppCompatActivity {
protected TextView tvData;
public static ArrayList<String> titleList = new ArrayList<String>();
private static ArrayAdapter<String> adapter;
private static ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.tvJsonItem);
// adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listView1, titleList);
// lv = (ListView) findViewById(R.id.listView1);
new JSONTask().execute("http://10.0.2.2:3000/api/people");
}
public class JSONTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
int statusCode = 0;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
connection.connect(); //connect to server
statusCode = connection.getResponseCode();
if (statusCode == 200) {
System.out.println("Server responded with code: " + statusCode);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("people");
StringBuffer finalBufferdData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObj = parentArray.getJSONObject(i);
String peopleName = finalObj.getString("name");
Integer age = finalObj.getInt("age");
finalBufferdData.append(peopleName + "-->" + age + "\n");
Log.i("Hakob_log",peopleName + "-->" + age + "\n");
}
return finalBufferdData.toString(); //pases result to POstExecute
}else{
Log.i("Hakob_log","Error");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(JSONException 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);
tvData.setText(result);
}
}
}
I thnk something wrong with this line
new JSONTask().execute("http://localhost:3000/api/people");
Thanks

Use the IP-address of the computer that you are referring to as localhost instead, this should solve your problem e.g.:
new JSONTask().execute("http://10.0.0.100:3000/api/people");

Related

How to update listview in for loop in asynk task

I'm reading some text from HttpUrlConnection request and putting it in ArrayList every iteration of a loop.
All works perfect, except items in ListView don't updating in UI after every iteration of a loop (only at the end).
I'm tried next 4 methods: arrayAdapter.notifyDataSetChanged(), listView.invalidateViews(), runOnUiThread(), onPostExecute() nothing helps.
Here is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> news = new ArrayList<>();
ArrayList<String> headers = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
static JSONArray array;
NewsUnpacker unpacker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String link = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
NewsLoader newsLoader = new NewsLoader();
array = null;
try {
array = newsLoader.execute(link).get();
} catch (Exception e) {
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, headers);
listView.setAdapter(arrayAdapter);
final int size = 15;
for (int i = 0; i < size; i++) {
try {
unpacker = new NewsUnpacker(this);
String info = unpacker.execute("https://hacker-news.firebaseio.com/v0/item/" + array.get(i) + ".json?print=pretty").get();
if (info == null) {
unpacker.cancel(true);
return;
}
news.add(info);
headers.add(info.split(System.lineSeparator())[0]);
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
unpacker.cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
static class NewsUnpacker extends AsyncTask<String, Void, String> {
MainActivity activity;
NewsUnpacker(MainActivity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... urls) {
String info = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
String title, urlParam;
JSONObject object = new JSONObject(builder.toString());
title = object.get("title").toString();
urlParam = object.get("url").toString();
info = title + System.lineSeparator() + urlParam;
System.out.println(info);
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
static class NewsLoader extends AsyncTask<String, Void, JSONArray> {
JSONArray array = null;
#Override
protected JSONArray doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
array = new JSONArray(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
}
}

Android App - HttpURLConnection in onCreateView

I just started to learn developing android app, and I need to call an URL to get the JSON response.
Here is my java class :-
public class SpeakersFragment extends Fragment {
List<String> titles;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_speakers, container, false);
initData();
RecyclerView rv = (RecyclerView)view.findViewById(R.id.info_speaker_recycler);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
RecyclerAdapter adapter = new RecyclerAdapter(getActivity(), titles);
rv.setAdapter(adapter);
new GetSpeakersList().execute(URL);
return view;
}
public class GetSpeakersList extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
When I checked the logs, the response is not there at all. I tried creating a new project, it works fine if I call the GetSpeakersList in onCreate() instead of onCreateView.
Can guide me how to get this to work? Thanks!
Using an AsyncTask can be quite cumbersome to use for constant Network requests: Try using a popular, well-supported library for networking: Here are two popular ones:
1) Retrofit
OR
2) Volley
this is how i ask for data hope you can use it to your means
urlConnection = new URL("www.example.com");
connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type","application/json;charset=UTF-8");
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
connection.connect();
dataOutputStream = new
DataOutputStream(connection.getOutputStream());
Log.d("OUTPUT :",param);
dataOutputStream.writeBytes(param);
dataOutputStream.flush();
dataOutputStream.close();
//incoming data
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new
InputStreamReader(in));
result = new StringBuilder(16384);
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
Log.d("INPUT :",result.toString());

Fetching Data from JSON using AsyncTask

I have created a fragment which if it is activated it will show MySQL data but it takes time to fetch the data and show it on a custom ListView.
I tried to implement AsyncTask so that while fetching the data you can do something else on the fragment while waiting but am having this error.
"FATAL EXCEPTION: main java.lang.NullPointerException"
Here is the code
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_markets,container,false);
//lvMarkets.setAdapter(new CustomAdapter(getActivity().getApplicationContext(),Symbols,Prices,Balances));
DBHelper db = new DBHelper(getActivity().getApplicationContext());
final ListView lvMarkets = (ListView)getActivity().findViewById(R.id.lvMarkets);
final String c_androidid = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
final Cursor rs = db.getID(c_androidid);
rs.moveToFirst();
final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));
AsyncTaskRunner taskRunner = new AsyncTaskRunner();
taskRunner.execute(c_login);
lvMarkets.setAdapter(jAdapter);
return rootView;
}
private class AsyncTaskRunner extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params)
{
final String fin_login=params[0];
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
Log.d(debug,response);
try
{
jsonArray =new JSONArray(response);
jAdapter= new JsonAdapter(getActivity(),jsonArray,login);
}
catch (JSONException e)
{
Log.d(debug,e.toString());
}
}
}, new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
Log.d(debug,error.toString());
}
}){
#Override
protected Map<String,String>getParams()
{
Map<String,String> params=new HashMap<String,String>();
params.put("c_login",fin_login);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
return fin_login;
}
}
Hope someone could point out what went wrong with my code and someone could also point out on how to fetch data on online much more faster.
Thanks...
Try this:
private void parsingValues() {
URL obj = null;
HttpURLConnection con = null;
String USER_AGENT = "Mozilla/5.0";
try {
//parameter to post
String POST_PARAMS = "deviceos=" + deveiceOs + "&devicetype=" + deviceType +"&deviceid=" ;
obj = new URL("Your URI");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//getResponse
String subsResponse = response.toString();
final JSONObject responsesubs = new JSONObject(subsResponse);
//Here your parsing process
}
}
});
} else {
System.out.println("POST request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Call this method to your doinbackground of Asynhronous Task(parsingValues())

How to pass data into string where the string will be access in another class?

I have been intending to pass co.user_id to public static String USER_ID, so that the data in string user_id can be sent to another class from the onPostExecute function. However, from the another class i get null value, which means the value didnt sent to that class. How should i store my value in string so that the value can also be access in another class?
public class connect3 extends AsyncTask<String, Void, String> {
View view;
Activity activity;
public static String USER_ID = " ";
public connect3(Activity activity, View v) {
this.activity = activity;
view = v;
}
String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
protected String doInBackground(String... arg0) {
String ipAddress = "http://192.168.1.3/apexStore2/";
try {
URL url = new URL(ipAddress +"receipts.php");
String urlParameters =
URLEncoder.encode("user_name", "UTF-8") + "=" +
URLEncoder.encode(arg0[0], "UTF-8") + "&" +
URLEncoder.encode("user_id", "UTF-8") + "=" +
URLEncoder.encode("???", "UTF-8");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
//System.out.println(response.toString());
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("results");
for(int i = 0; i < uniObject.length(); i++) {
ContactReceipt co = new ContactReceipt();
JSONObject rowObject = uniObject.getJSONObject(i);
//EventObject co = new EventObject();
co.user_id = rowObject.getString("user_id");
USER_ID = co.user_id;
System.out.println("hi1" + co.user_id);
}
//To further break down JSON
//JSONObject oneObject = mainObject.getJSONObject("1");
//String id = oneObject.getJSONObject("id");
try{
}
finally{
connection.disconnect();
}
} catch (Exception e){
System.out.println(e.toString());
}
return USER_ID;
//return "";
}
protected void onPreExecute(){
}
#Override
protected void onPostExecute(String result){
// receipt1.user_id = user_id;
// String search = USER_ID;
// Intent intent = new Intent(activity.getApplication(),receipt1.class);
//intent.putExtra(USER_ID, search);
//activity.startActivity(intent);
Intent intent = new Intent(activity.getApplication(),receipt1.class);
intent.putExtra("USER_ID", result);
activity.startActivity(intent);
}
}
This is how i call the value in another class.
Intent intent = getIntent();
String cats = intent.getStringExtra("USER_ID");
Since there are more than one UserIds this is how you should pass it to your activity see below complete code:
public class Connect3 extends AsyncTask<String, Void, List<String>> {
View view;
Activity activity;
public static String USER_ID = "yourpackagename.USER_ID";
private List<String> listUserIds;
public Connect3(Activity activity, View v) {
this.activity = activity;
view = v;
}
String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
protected List<String> doInBackground(String... arg0) {
String ipAddress = "http://192.168.1.3/apexStore2/";
try {
URL url = new URL(ipAddress +"receipts.php");
String urlParameters =
URLEncoder.encode("user_name", "UTF-8") + "=" +
URLEncoder.encode(arg0[0], "UTF-8") + "&" +
URLEncoder.encode("user_id", "UTF-8") + "=" +
URLEncoder.encode("???", "UTF-8");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
//System.out.println(response.toString());
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
if(uniObject != null && uniObject.length() > 0) {
listUserIds = new ArrayList<>(uniObject.length());
for (int i = 0; i < uniObject.length(); i++) {
ContactReceipt co = new ContactReceipt();
JSONObject rowObject = uniObject.getJSONObject(i);
//EventObject co = new EventObject();
co.user_id = rowObject.getString("user_id");
System.out.println("hi1" + co.user_id);
listUserIds.add(co.user_id);
}
}
connection.disconnect();
} catch (Exception e){
System.out.println(e.toString());
}
return listUserIds;
}
protected void onPreExecute(){
}
#Override
protected void onPostExecute(List<String> result){
// receipt1.user_id = user_id;
Intent intent = new Intent(activity.getApplication(),receipt1.class);
if(result != null){
intent.putStringArrayListExtra(USER_ID, (ArrayList<String>) result);
}
activity.startActivity(intent);
}
}
And you will get it like this in your Activity class
if(getIntent() != null){
ArrayList<String> listUserIds = getIntent().getStringArrayListExtra(Connect3.USER_ID);
}
just check before pass the value
Intent intent = new Intent(activity.getApplication(),receipt1.class);
if( !result.equalsIgnoreCase("") && search !=null ){
intent.putExtra("USER_ID", result);
} else{
intent.putExtra("USER_ID", "result is null or empty");
}
and try to get value like this
Intent intent = getIntent();
if(intent !=null){
String cats = intent.getStringExtra("USER_ID");
Log.e("value",cats);
// if cats prints "result is null or empty" that means problem inside your doinback.....
}

How to start an Activity from AsyncTask?

I've build an AsyncTask and want to start another Activity when it ends (onPostExecute) but it won't work and I can't find the problem. Maybe there is a problem with String, String, String ?
Here is my code:
public class StartSearch extends AsyncTask<String, String, String> {
private Activity activity;
#Override
protected String doInBackground(String... strings) {
StringBuilder sb = new StringBuilder();
String http = "https://list-creater-service.herokuapp.com/api/v1/search";
HttpURLConnection urlConnection = null;
JSONObject json = null;
HttpResponse response = null;
try {
//connect to server
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "list-creater-service.herokuapp.com");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("gamemode", gametype);
jsonParam.put("country", selCountry);
jsonParam.put("min_size", minSize);
jsonParam.put("max_size", maxSize);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String jsonS = sb.toString();
JSONArray jsonArray = new JSONArray(jsonS);
int length = jsonArray.length();
String[] names = new String[length];
for (int i = 0; i < length; i++) {
JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
ArrayList serverList = new ArrayList();
serverList.add(jsonObject.getString("name"));
serverData = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = serverData.edit();
Set<String> set = new HashSet<String>();
set.addAll(serverList);
editor.putStringSet("name", set);
editor.commit();
System.out.println(jsonObject.getString("name"));
names[i] = jsonObject.getString("name");
}
//String name = jsonObject.getString("name");
System.out.println("" + sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
activity.startActivity(new Intent(activity, ServerIndex.class));
}
}
Need some help!
Thx :)
You have Activity activity declared , but you have not assigned your current activity context to it . Assign the current activity context to it.
Like
activity=currentContext;
You should use runOnUIThread in your onPostExecute
runOnUiThread(new Runnable() {
public void run() {
activity.startActivity(new Intent(activity, ServerIndex.class));
}});
And as Raghunandan said, activity is not initialized. You can access the startActivity method from your StartSearch class by using
SomeActivity.this.startActivity (SomeActivity has to be initialized)
And since onPostExecute runs on the UI thread, you may or may not call runOnUIThread.

Categories