Hello Guys I received a a big problem in my project. I make the OkHttp request i receive response from server all is perfect. the problem is why i can't display data, i made a model item in xml and listview(this is the required view) and when i acces the page is blank.
Can anyone help me with this issue?
code for page is the following:
package com.example.socceraplication;
import static android.content.ContentValues.TAG;
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.util.ArrayList;
public class TeamInfo extends AppCompatActivity {
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_info);
resultList = 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(TeamInfo.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name=Liverpool")
.get()
.addHeader("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
String jsonStr=response.body().string();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray records = jsonObj.getJSONArray("records");
// looping through All items
for (int i = 0; i < records.length(); i++) {
JSONObject c = records.getJSONObject(i);
String league = c.getString("league");
String season = c.getString("season");
String name = c.getString("name");
String officialName = c.getString("officialName");
String address = c.getString("address");
String telephone = c.getString("telephone");
String fax = c.getString("fax");
String website = c.getString("website");
String founded = c.getString("founded");
String teamSize = c.getString("teamSize");
String averageAge = c.getString("averageAge");
String foreigners = c.getString("foreigners");
String nationaTeamPlayers = c.getString("nationaTeamPlayers");
String teamValue = c.getString("teamValue");
String venue = c.getString("venue");
String venueCapacity = c.getString("venueCapacity");
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("league",league);
result.put("season",season);
result.put("name",name);
result.put("officialName",officialName);
result.put("address",address);
result.put("telephone",telephone);
result.put("fax",fax);
result.put("website",website);
result.put("founded",founded);
result.put("teamSize",teamSize);
result.put("averageAge",averageAge);
result.put("foreigners",foreigners);
result.put("nationaTeamPlayers",nationaTeamPlayers);
result.put("teamValue",teamValue);
result.put("venue",venue);
result.put("venueCapacity",venueCapacity);
resultList.add(result);
}
} 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(TeamInfo.this, resultList,
R.layout.list_item_team, new String[]{ "league","season","name","officialName","address","telephone","fax","website","founded","teamSize","averageAge","foreigners","nationaTeamPlayers","teamValue","venue","venueCapacity"},
new int[]{R.id.league, R.id.season,R.id.name,R.id.officialName,R.id.address,R.id.telephone,R.id.fax,R.id.website,R.id.founded,R.id.teamSize,R.id.averageAge,R.id.foreigners,R.id.nationaTeamPlayers,R.id.teamValue,R.id.venue,R.id.venueCapacity});
lv.setAdapter(adapter);
}
}
}
The enqueue call is asynchronous, which means it queues up work to be run in the background at some point in the future, and when it is complete then it runs the callback you supply (onResponse). This means in your case the order of calls is
Start doInBackground
Add your Http call to the queue
Return from doInBackground
Run onPostExecute
Post empty list to the adapter
... some time later ...
Run the onResponse callback when it gets data
To fix this, you can remove the async task entirely and just queue the work from the main thread, since it already handles actually doing the request in the background.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_info);
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
startRequest();
}
private void startRequest() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//...
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) {
showResult(response);
}
});
}
private void showResult(Response response) {
// show the result here - no need to runOnUiThread
// set the adapter, put text in views, etc from in here
}
If you really want to make the call from your own AsyncTask in the background, you should use the synchronous API, not the asynchronous API. This means calling execute instead of enqueue, like this:
// this MUST run on a background thread or it will block the UI thread
Response response = client.newCall(request).execute();
Related
I'm trying to build a simple phonebook application where I can perform a search and an API will return the information. So far this is the part that I've got working.
I also want incoming caller to be identified with the same API, that would require the incoming number from Broastcastreceiver to be put into the API query and the returned information should be displayed in a toast. This is the part I'm having problems with.
So far this is what I have. Apologize if its really messy, this is what I've been playing around with recently and made small adjustments. Also its alot of copy-paste, I'm a beginner at java/Android and trying to learn.
HttpHandler.java
package se.xx.api_test;
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 extends PhoneCallReceiver {
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();
}
}
PhoneCallReceiver.java
package se.xx.api_test;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.util.Log;
public class PhoneCallReceiver extends BroadcastReceiver {
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
public static String savedNumber; //because the passed incoming is only valid in ringing
#Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start){}
protected void onOutgoingCallStarted(Context ctx, String number, Date start){}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onMissedCall(Context ctx, String number, Date start){}
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if(lastState == state){
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
}
else if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
else{
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
}
MainActivity.java
package se.xx.api_test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
public class MainActivity extends AppCompatActivity {
private TextView tv;
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);
tv = (TextView) findViewById(R.id.textInput);
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
contactList.clear();
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) {
String id = tv.getText().toString();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+id;
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("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// 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[]{ "namn","avdelning","mobil", "telnr"},
new int[]{R.id.email, R.id.mobile, R.id.mobil, R.id.telnr});
lv.setAdapter(adapter);
}
}
}
CallReceiver.java (this is what I've been playing around with)
package se.xx.api_test;
import java.util.Date;
import java.util.HashMap;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import android.widget.ListAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.lang.String;
import android.telephony.TelephonyManager;
public class CallReceiver extends PhoneCallReceiver {
#Override
public void onIncomingCallStarted(Context ctx, String number, Date start) {
final String phnr = String.valueOf(R.id.mobile);
Toast toast = Toast.makeText(ctx.getApplicationContext(), , Toast.LENGTH_SHORT);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(25);
toast.show();
}
#Override
public void onOutgoingCallStarted(Context ctx, String number, Date start) {
}
#Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onMissedCall(Context ctx, String number, Date start) {
}
private class APICall extends MainActivity {
String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
protected Void doInBackground(Void... arg0) {
String TAG = MainActivity.class.getSimpleName();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+number;
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("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
final String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// 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;
}
}
}
which part you got an error ?
with your Api ? or while receive you phone number from service ?
put your error to clarify the situation
When I'm trying to send post request using OkHttp, the app on my phone (LG g3) crashes without an error.
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "login=test&pasword=test");
Request request = new Request.Builder()
.url("http://myUrl")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
txtRequest.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
What am I doing wrong?
you are executing the network call on main thread, this is the exception i guess you are getting. Use AsyncTask and your problem is solved. here is corrected version of your code.
Edited
package com.example.nisu.postrequest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class SendPost extends AppCompatActivity {
Button btnSend;
TextView txtRequest;
OkHttpClient client = new OkHttpClient();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_post);
btnSend = (Button) findViewById(R.id.btnSend);
txtRequest = (TextView) findViewById(R.id.txtRequest);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Request request = new Request.Builder()
.url("http://httpbin.org/ip").get()
.build();
new MyAsyncTask().execute(request);
}
});
}
class MyAsyncTask extends AsyncTask<Request, Void, Response> {
#Override
protected Response doInBackground(Request... requests) {
Response response = null;
try {
response = client.newCall(requests[0]).execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(Response response) {
super.onPostExecute(response);
try {
txtRequest.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have an activity with 2 EditText.
When the user is clicking on the Send button, I want to send EditText value to my server.
i tried to make a POST request when the user clicking on the button.
The problem is when the user is clicking on the button He get a error, and the application closing automatically.
This is my code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class register extends AppCompatActivity {
private EditText nameE,l_nameE;
private Button registerE;
private String name,l_name,token;
boolean thread_running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
FirebaseMessaging.getInstance().subscribeToTopic("test");
token = FirebaseInstanceId.getInstance().getToken();
Toast.makeText(this, token, Toast.LENGTH_LONG).show();
final Button register = (Button)findViewById(R.id.button);
nameE = (EditText)findViewById(R.id.editText);
l_nameE = (EditText)findViewById(R.id.editText2);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerToken();
}
});
}
public void intialize(){
name = nameE.getText().toString().trim();
l_name = l_nameE.getText().toString().trim();
}
public boolean validate(){
boolean e=true;
if(name.equals("")){
e=false;
nameE.setError("enter name");
}else if(l_name.equals("")){
e=false;
l_nameE.setError("enter l_name");
}
return e;
}
private void registerToken() {
intialize();
if (!validate()) {
Toast.makeText(this, "err", Toast.LENGTH_LONG).show();
}else{
reg();
}
}
public void reg(){
Toast.makeText(this, "reg", Toast.LENGTH_LONG).show();
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("name",name)
.add("l_name",l_name)
.build();
Request request = new Request.Builder()
.url("http://192.168.0.106/fcm/register.php")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
thank you
You are doing a network call on the main thread. That is not allowed on Android as it will block your whole application until the request is completed.
A solution will be to wrap your network call in an AsyncTask for example.
But as you are using OKHttpClient, they are offering an async api for such things.
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
//something went wrong
Log.e(YOUR_TAG, e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Response not sueccessful " + response);
}
//success do whatever you want. for example -->
Log.d(YOUR_TAG, response.body().string());
}
}
So in your example instead of an synchronous call like
client.newCall(request).execute();
you have to use the async callback version like shown above.
hopefully that helps
Edit: For more recipes take a look at the wiki page: https://github.com/square/okhttp/wiki/Recipes
ive got a working listview which receives JSON from my DB. But when i try with this link: I get "Error parsing data org.json.JSONException: Value
The JSON output is clean and should work! My activitiy
package com.spxc.ssa.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;
public class ListShowsController extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Shows");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("items");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
map.put("video_id", String.valueOf(i));
map.put("video_title", "" + e.getString("video_title"));
//map.put("season", "Season: " + e.getString("season"));
map.put("video_location", "" + e.getString("video_location"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Intent myIntent = new Intent(ListShowsController.this,
ShowsController.class);
myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("season", o.get("season"));
myIntent.putExtra("video_location", o.get("video_location"));
startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
AsyncTask
package com.spxc.ssa.streaming.task;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class JsonAsync extends AsyncTask<String, Void, JSONObject> {
public interface JsonListener {
public void onObjectReturn(JSONObject object);
}
public void setJsonListener(JsonListener jsonListener) {
mListener = jsonListener;
}
private JsonListener mListener;
public static final String TAG = JsonAsync.class.getSimpleName();
#Override
protected JSONObject doInBackground(String... params) {
// The argument passed into tasks are arrays. So you can pass 0 or more
// arguments, when calling from activity, it's really up to you. They
// just have to be separated by commas. Like this :
// new JsonAsync.execute("thisUrl", "thatUrl", "anotherUrl");
// Although I am only grabbing the first item in the array, by calling
// params[0] below.
JSONObject object = null;
if (params != null && params.length > 0) {
object = JSONfunctions.getJSONfromURL(params[0]);
} else {
Log.e(TAG, "Task needs an argument to be able to retrieve data.");
}
// I return the item out of this method, because it is happening of the
// UI thread, so it can;t update items on the screen. You can work with
// a database from this method. That is actually recommended.
return object;
}
#Override
protected void onPostExecute(JSONObject result) {
// This method can touch UI components without throwing an error.
if (result != null && mListener != null) {
mListener.onObjectReturn(result);
}
super.onPostExecute(result);
}
}
I've never seen this error before! What is the problem?
Any help is much appreciated ! Thanks
EDIT:
My other activity which works:
package com.spxc.ssa.streaming;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.ssa.streaming.task.JsonAsync;
import com.spxc.ssa.streaming.task.JsonAsync.JsonListener;
public class ListMoviesController extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Movies");
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://strongpixel.com/java/movies.php");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("items");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "" + e.getString("name"));
//map.put("date", "Released: " + e.getString("date"));
map.put("path", "" + e.getString("path"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { "name", "path" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Intent myIntent = new Intent(ListMoviesController.this,
MoviesController.class);
myIntent.putExtra("name", o.get("name"));
myIntent.putExtra("season", o.get("season"));
myIntent.putExtra("path", o.get("path"));
startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Logcat:
03-12 08:35:18.722: E/log_tag(25208): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
03-12 09:06:52.877: V/CustomViewAbove(26397): Received ACTION_DOWN
03-12 09:06:52.920: V/CustomViewAbove(26397): onInterceptTouch moved to:(30.26232, 662.0), diff:(29.26232, 1.0), mLastMotionX:1.0
03-12 09:06:52.936: V/CustomViewAbove(26397): onInterceptTouch moved to:(73.95948, 663.08905), diff:(72.95948, 0.08905029), mLastMotionX:1.0
03-12 09:06:52.940: V/CustomViewAbove(26397): this slide allowed true dx: 72.95948
03-12 09:06:52.940: V/CustomViewAbove(26397): Starting drag! from onInterceptTouch
03-12 09:06:52.993: V/SlidingMenu(26397): changing layerType. hardware? true
03-12 09:06:53.229: V/SlidingMenu(26397): changing layerType. hardware? false
03-12 09:06:54.214: V/CustomViewAbove(26397): Received ACTION_DOWN
03-12 09:06:54.450: D/dalvikvm(26397): GC_CONCURRENT freed 73K, 7% free 4495K/4812K, paused 3ms+6ms, total 24ms
03-12 09:06:55.025: E/log_tag(26397): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Edit:
I tried the same JSON, but just in a txt file strongpixel.com/java/JSON.txt, this works without any problem, it takes some time to load, but it works.
You can't get it work cause your code can't load proper JSON String. There is only one place where you make download:
JSONfunctions.getJSONfromURL(params[0])
You get the obvious error: JSON object can't be created from string like <!doctype html>. It means that you download HTML data instead of JSON. For simple test you can try next code and you will get the same error:
JSONObject object = new JSONObject("<!DOCTYPE html>");
You can get this wrong response from numerous reasons: wrong request, your fire wall, proxy, even server might return wrong result if you don't specify User-Agent header or doesn't perform authorization. I do recommend using some web debug tools that will help you to handle such situations and make sure that your app receive valid data.
If you are using Windows i would recommend you to use Fiddler, it is free. Here is example how you can setup fiddler for your test device: http://www.cantoni.org/2011/06/28/debug-http-android-fiddler
Anyway there is alternative tools for other operating system.
I got it working! It was a simple and idiotic mistake. The server i was connecting to didnt allow POST so in the adapter i changed Httppost to Httpget
I am trying to get an Android device to send some HTTP request using GET method.
Here is my code:
package com.kde.httprequest;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class main2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edit1 = (EditText) findViewById (R.id.editText1);
Button btn1 = (Button) findViewById (R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
grabURL(edit1.getText().toString());
}
});
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(main2.this);
final TextView text1 = (TextView) findViewById (R.id.textView1);
protected void onPreExecute() {
Dialog.setMessage("Downloading source..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(main2.this, Error, Toast.LENGTH_LONG).show();
text1.setText(Error);
} else {
Toast.makeText(main2.this, "Source: " + Content, Toast.LENGTH_LONG).show();
text1.setText(Content);
}
}
}
}
My simple PHP test:
<?php
$a = $_GET['user'];
$b = $_GET['pass'];
if ($a=="usr" && $b=="pass") {
echo "success";
} else {
echo "fail";
}
?>
My code is running smoothly when send to this URL:
digitalzone-btm.com/test2.php?user=user&pass=pass
The response from my PHP is a string say "success" or "fail", that is what I am expected.
But I am getting a different response from my local webserver with a same Android app and PHP file.
Ex url:
http://192.168.1.8/test2.php?user=user&pass=pass
The response is exactly my PHP source code.
How can I get a "success" or "fail" response from my local webserver?
It would appear your local web server doesn't have php installed or configured right. Check here for help.
PHP: Installation and Configuration - Manual