Using Azure Bing Search API in Android - android

I am trying to make an app which executes an image search and displays the image results in a grid. Since the Google Image Search API is deprecated and will no longer be available shortly, I am trying to use the Bing Search API.
However, I am getting the following error:
java.io.IOException: No authentication challenges found
at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:427)
at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:407)
at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:356)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:292)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
I am following the example in http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html. If anyone has experienced this issue, or can help me out, that would be much appreciated. Thanks!
Here is my code thus far:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTask <Void, Void, Void> task = new AsyncTask <Void, Void, Void> () {
protected Void doInBackground(Void... args) {
// Uri uri = Uri.parse("https://www.google.com/search?tbm=isch&q=penguin");
// Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// startActivity(intent);
/*-------------------------Bing search-------------------------*/
String searchText = "Hello World";
searchText = searchText.replace(" ", "%20");
String accountKey = "MY_APP_ID";
accountKey = accountKey.replace("+", "%2B");
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/"
+ "Image?Query=%27" + searchText + "%27");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
task.execute();
}
}

The following code worked for me:
public class SearchAsyncTask extends AsyncTask<Void, Void, Void> {
private final String TAG = getClass().getName();
private String mSearchStr;
private int mNumOfResults = 0;
private Callback mCallback;
private BingSearchResults mBingSearchResults;
private Error mError;
public SearchAsyncTask(String searchStr, int numOfResults, Callback callback) {
mSearchStr = searchStr;
mNumOfResults = numOfResults;
mCallback = callback;
}
#Override
protected Void doInBackground(Void... params) {
try {
String searchStr = URLEncoder.encode(mSearchStr);
String numOfResultsStr = mNumOfResults <= 0 ? "" : "&$top=" + mNumOfResults;
String bingUrl = "https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27" + searchStr + "%27" + numOfResultsStr + "&$format=json";
String accountKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url = null;
url = new URL(bingUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
InputStream response = urlConnection.getInputStream();
String res = readStream(response);
Gson gson = (new GsonBuilder()).create();
mBingSearchResults = gson.fromJson(res, BingSearchResults.class);
Log.d(TAG, res);
//conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
mError = new Error(e.getMessage(), e);
//Log.e(TAG, e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (mCallback != null) {
mCallback.onComplete(mBingSearchResults, mError);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
//System.out.println(line);
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public interface Callback {
void onComplete(Object o, Error error);
}
}
To parse the result:
public class BingSearchResults {
public ResultsContent d;
public static class ResultsContent {
public Result[] results;
public String __next;
}
public static class Result {
public String ID;
public String Title;
public String Description;
public String DisplayUrl;
public String Url;
public Metadata __metadata;
}
public static class Metadata {
public String uri;
public String type;
}
public Result[] getResults(){
if (d == null)
return null;
return d.results;
}
public String getNextUrl(){
if (d == null)
return null;
return d.__next;
}
public boolean isEmpty(){
return (d == null || d.results == null || d.results.length == 0);
}
public int size(){
if (d == null || d.results == null)
return 0;
return d.results.length;
}
}
You also need to include the external jars commons-codec-1.9.jar and gson-2.2.4.jar

Little bit change occur in this code sometimes compilation bug of encoder generate problem byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());

Related

Android Studio: setOnItemClickListener

I have two AppCompatActivitys, both should have an onItemClickListener, but one of them doesn't do anything on click. I've just added a Toast for test reason, later on it should call a function to delete an item from list (with an ajax request)
What am I doing wrong?
I have made custom list and custom adapter for this - I know, I am new to Android Studio, but the other Activity works fine, and I cant find any differences.
public class ActivityListofProducts extends AppCompatActivity {
ProgressDialog pd;
SharedPreferences preferences;
String userid;
String session;
String list_id = "-1"; // or other values
String appVersion = "";
private ArrayList<listProductItem> myProducts = new ArrayList<listProductItem>();
private ArrayList<listProductItem> groceryFilterProducts = new ArrayList<listProductItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
setContentView(R.layout.activity_list_of_products);
this.setTitle(getString(R.string.grocery_list));
Bundle b = getIntent().getExtras();
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
if (b != null)
list_id = b.getString("list_id");
Toast.makeText(this, "List to open " + " " + list_id, Toast.LENGTH_SHORT).show();
preferences =
getSharedPreferences(this.getPackageName(), this.MODE_PRIVATE);
userid = preferences.getString("userid", "");
session = preferences.getString("session", "");
appVersion = preferences.getString("appVersion", "");
getData();
swipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
swipeRefreshLayout.setRefreshing(false);
}
}
);
}
public void getData() {
AsyncTask<String, String, String> Task_GetListofProducts = new Task_GetListofProducts();
Task_GetListofProducts.execute("https://get-some-json.com");
}
public void initListofProducts(String jsonString) {
Log.i("jsonString",jsonString);
try {
JSONObject jsonResponse = new JSONObject(jsonString);
JSONObject jsonListMode = jsonResponse.getJSONObject("list");
String ListName = jsonListMode.optString("name");
this.setTitle(ListName);
JSONArray jsonMainNode = jsonResponse.optJSONArray("data");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
int item_amount = jsonChildNode.optInt("item_amount");
int id = jsonChildNode.optInt("id");
String item_name = jsonChildNode.optString("item_name",">Name<");
int done = jsonChildNode.optInt("done", 0);
String timestamp = jsonChildNode.optString("timestamp", "");
String item_scale = jsonChildNode.optString("item_scale", "x");
String img = jsonChildNode.optString("img", "x");
double bestprice = jsonChildNode.optDouble("bestprice");
//int oitems = jsonChildNode.optInt("oitems", 0);
//int shared = jsonChildNode.optInt("shared", 0);
String outPut = "item_amount:"+ item_amount +" id:"+ id +" item_name:"+ item_name +" done:"+ done +" timestamp:"+ timestamp +" item_scale:"+ item_scale +" img:"+ img;
Log.i("outPut",outPut);
myProducts.add(new listProductItem(id, item_name, item_amount, item_scale, img, done, timestamp, bestprice));
}
final ListView lv = findViewById(R.id.grocery_list_of_products);
lv.setAdapter(new listofProductsAdapter(this, myProducts));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
/*
!! HERE is my problem. This Code seems not to be executed !!
*/
Toast.makeText(ActivityListofProducts.this, "Should handle click now.", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
public void setProductDone(int pid, int done) {
String url = "put-some-json.com";
new ActivityListofProducts.Task_SetProductDone().execute(url);
}
private class Task_SetProductDone extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
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");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
Toast.makeText(ActivityListofProducts.this, "No Internet?", Toast.LENGTH_SHORT).show();
} 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();
}
Log.i("onPostExecute", result);
}
}
private class Task_GetListofProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
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");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
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();
}
initListofProducts(result);
}
}
private class Task_FindProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
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");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
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();
}
setFilterProducts(result);
}
}
}

Android - Call Thread synchronized on UI thread

I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
                         #Override
                         public void run () {
                             synchronized (syncJob) {
                                 String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
                                 txtState.setText (s);
                             }}});
                         }
                     });
                     t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
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("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} 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();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
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("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} 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();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.

read from json (string) android with Gson

its my json file
{"VisitorsList":[{"VisitorID":"09005451","VisitorName":" xxxx","VisitorPhon":"","VisitorAddr":"xxxx","GeoCode":"","AutoKey":1},{"VisitorID":"09005468","VisitorName":"xxxxxx","VisitorPhon":"09005468","VisitorAddr":"xxxx","GeoCode":"","AutoKey":2}]}
and i wanna read and show information from this file to a ListView
my VisitorsListActivity is:
public class VisitorsListActivity extends AppCompatActivity {
public ListView lstVisitors;
static VisitorsList visitorsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor_list);
try {
//********************************** COMELETE THIS SECTION *********************************************
new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
if (output == null) output = "";
if (output.equals("")) {
Toast.makeText(getApplicationContext(),
"No Visitor Founded",
Toast.LENGTH_LONG)
.show();
return;
}
//960105--------------------
else if (output.equals("401")) {
Toast.makeText(getApplicationContext(),
"Error 401",
Toast.LENGTH_LONG)
.show();
return;
}
//--------------------------------------
Log.i("LOG", "output" + output);
Gson gson = new Gson();
output = output.substring(1, output.length() - 1);
/*Toast.makeText(getApplicationContext(),
output,
Toast.LENGTH_LONG)
.show();*/
visitorsList = new VisitorsList();
visitorsList = gson.fromJson(output, VisitorsList.class);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"exception",
Toast.LENGTH_LONG)
.show();
}
}
}).execute("http://192.168.1.162:8014/api/Visitors");
//************************************ visitor list is null :| *******************************************
/*if( visitorsList == null) {
Toast.makeText(getApplicationContext(),
"data is nul",
Toast.LENGTH_LONG)
.show();
}*/
AdapterVisitor customAdapter = new AdapterVisitor(this, R.layout.visitor_list, visitorsList.VisitorsList);
customAdapter.notifyDataSetChanged();
lstVisitors.setAdapter(customAdapter);
lstVisitors.requestFocus();
final ViewGroup layoutClear = (ViewGroup) findViewById(R.id.layoutClear);
layoutClear.setVisibility(View.GONE);
} catch (Exception e) {
e.getMessage();
}
} }
and VisitorsList:
public class VisitorsList {
public VisitorsList() {}
public ArrayList<Visitors> VisitorsList;}
Visitors:
public class Visitors {
public String VisitorID;
public String VisitorName;
public String VisitorPhon;
public String VisitorAddr;
public String GeoCode;
public int AutoKey;}
and always visitor list which created by Gson is null. i dont know maybe my problem is in reading from json or maybe visitors class ...
jsonhelper :
public class JsonHelper {
public static class GetJsonData extends AsyncTask<String, Void, String> {
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public GetJsonData(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected String doInBackground(String... strUrl) {
String str = strUrl[0];
URLConnection urlConn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(str);
urlConn = url.openConnection();
urlConn.setReadTimeout(300000);
urlConn.setConnectTimeout(5000);
bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"), 8);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String tmpJson = stringBuffer.toString().replace("\\", "");
return tmpJson;
} catch (Exception ex) {
ex.getMessage();
return null;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String response) {
delegate.processFinish(response);
}
}
public static class SetJsonData extends AsyncTask<String, Void, String> {
String responseServer;
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public SetJsonData(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = null;
try {
url = new URL(param[0]);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000);
conn.setConnectTimeout(10000);//950718
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(param[1]);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = (String.valueOf(responseCode));
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));//950427
while ((line = br.readLine()) != null) {
}
}
return response;
} catch (IOException e1) {
e1.getMessage();
return null;
} catch (Exception e) {
e.getMessage();
return null;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
super.onPostExecute(result);
delegate.processFinish(result);
} catch (Exception e) {
e.getMessage();
}
}
}}
your visitors class is missing annotations.
use this to convert it properly:
http://www.jsonschema2pojo.org/
Check this https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
to read the JSON with GSON.
well at first read AsyncResponse so you are using asynchronous request is that what are doing ?
An asynchronous request doesn't block the client so it continue executing the code when the response is back it will execute what is inside the callback.
But you are calling the customAdapter.notifyDataSetChanged(); outside processFinish() you need to call it inside or call the Adapter work inside the processFinish method.
public class VisitorsList {
public VisitorsList() {}
public ArrayList VisitorsList= new ArrayList<>();}
Should be like this... Intialization is missing.
VisitorsList class :
public class VisitorsList {
#SerializedName("VisitorsList")
public List<VisitorsList> VisitorsList;
public static class VisitorsList {
#SerializedName("VisitorID")
public String VisitorID;
#SerializedName("VisitorName")
public String VisitorName;
#SerializedName("VisitorPhon")
public String VisitorPhon;
#SerializedName("VisitorAddr")
public String VisitorAddr;
#SerializedName("GeoCode")
public String GeoCode;
#SerializedName("AutoKey")
public int AutoKey;
}
}
delete this line
output = output.substring(1, output.length() - 1);
and get your result:
Gson gson = new Gson();
visitorsList=gson.fromJson(output), new TypeToken<VisitorsList>() { }.getType());
i change VisitorsListActivity same as below . and set a condition before call adapter to be sure reading information from json has been finished, this worked correctly :
new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
if (output == null) output = "";
if (output.equals("")) {
Toast.makeText(getApplicationContext(),
"No Visitor Founded",
Toast.LENGTH_LONG)
.show();
return;
}
else if (output.equals("401")) {
Toast.makeText(getApplicationContext(),
"Error 401",
Toast.LENGTH_LONG)
.show();
return;
}
Log.i("LOG", "output" + output);
Gson gson = new Gson();
output = output.substring(1, output.length() - 1);
try {
visitorsList = new VisitorsList();
visitorsList = gson.fromJson(output, VisitorsList.class);
if(visitorsList != null) {
d.cancel();
adapter = new AdapterVisitor(visitorsList.VisitorsList);
adapter.notifyDataSetChanged();
lstVisitors.setAdapter(adapter);
lstVisitors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ******
Object o = lstVisitors.getItemAtPosition(position);
Intent i = new Intent(getApplicationContext(),DateSelectorActivity.class);
Visitors v = (Visitors) o;
i.putExtra("VisitorID", v.VisitorID);
startActivity(i);
}
});
}
}catch (Exception e) {
Log.i("LOG", getAssets().toString() + "exception" + e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).execute(url);

Informationparsing from URL-Request not working / Didn't found TextView

i need your help. I want to send a URL Request, get response and create a JSON Object. My first try was totally wrong. Now I found a tutorial and made a new try.
My Activity looks like:
public class Patienten extends Activity {
//Beacon Elemente
private String UUID;
private String Major;
private String Minor;
private TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patienten);
output = (TextView) findViewById(R.id.output);
UpdateBeaconInformation();
Button cmdHit = (Button) findViewById(R.id.cmd_hit);
cmdHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
}
});
setTitle(Surname + ", " + FirstName);
// output.setText(output.getText().toString() + "Gefundener Patient:\n" + "Name: " + Surname + ", " + FirstName + "\nGeb.-Dat: " + Birthdate);
}
Then I created a new Java Class and built an asyncTask with it. But I can't access to the textview output in onPostExecute to update it.
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//http://kusber-web.de/JsonTest.txt
//http://nilsbenning.selfhost.me/PatientFinder.php?beacon_comID=5181f8a3-7354-46ac-b22d-952ec395ab06&beacon_major=12&beacon_minor=249
URL url = new URL(urls[0]);
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);
}
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);
output.setText(result);
}
}
What is my mistake? Why I can't access to it? I saw it as a solution here but didn't get it to work:
https://stackoverflow.com/a/12252717/5743912
Hope you can help me now! :)
You probably want to fix this (remove leading slashes):
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
In your JSONTask you can reference members of Patienten by using Patienten.this. So in onPostExecute you should change this:
output.setText(result);
to:
Patienten.this.output.setText(result);

Converting a J2ME URLCaller Class to Android equivalent

I got a Class from a friend for a URlCaller class for connecting to a webservice. My assumption was that all will work well, but it contains error below is the J2ME implementation
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class URLCaller extends Thread{
private String url ;
private String action;
private URLEncoder urle;
private String res;
public URLCaller() {
}
public URLCaller(String action,String url) {
urle = new URLEncoder();
this.url = url;
this.action = action;
start();
}
//replace
void authenticate(String action,String url) {
HttpConnection connection = null;
InputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
res = stringBuffer.toString() ;
System.out.println(res);
//textBox = new TextBox("Simple GET Test", stringBuffer.toString(), 1024, 0);
}
catch(Exception e ){
}
finally {
try{
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(connection != null) {
connection.close();
}
//display.setCurrent(textBox);
}
catch(Exception e ){
}
}
}
void sendSMS(String action,String url) {
HttpConnection connection = null;
InputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
//TextBox textBox = null;
try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
res = stringBuffer.toString() ;
System.out.println(res);
//textBox = new TextBox("Simple GET Test", stringBuffer.toString(), 1024, 0);
}
catch(Exception e ){
}
finally {
try{
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(connection != null) {
connection.close();
}
//display.setCurrent(textBox);
}
catch(Exception e ){
}
}
}
public void run(){
//http://message url?user=mu&password=my&from=Muyiwa&to=23475061254040&message=i+love+this.
System.out.println(Thread.currentThread().toString() + " is running...") ;
if (action.equals("login")){
System.out.println(action);
authenticate(action,url);
}
else if(action.equals("sendsms")) {
System.out.println(action);
sendSMS(action,url);
}
}
public void callURL(){
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try{
System.out.println(url);
//url = (urle.encode(url,"UTF-8"));
//System.out.println(url);
c = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
c.setRequestMethod(HttpConnection.POST); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for(int ccnt=0; ccnt < 150; ccnt++) { // get the title.
ch = is.read();
if (ch == -1){
break;
}
sb.append((char)ch);
}
res = sb.toString();
}catch(Exception e){
e.printStackTrace();
}
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public URLEncoder getUrle() {
return urle;
}
public void setUrle(URLEncoder urle) {
this.urle = urle;
}
}
Ps could someone convert this to an android implementation. Currently facing a deadline
In android there are classes, HttpClient and DefaultHttpClient. So you make a web request using these.
Same as your code make a HttpGet request, And also in Like your J2ME code, instead of Thread class you can use AsyncTask (You can also use Thread, Handler but Asynctask is better to use) to perform a web request in Non-UI thread.
Example:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
Now from your Android activity code you have to just execute() this DownloadWebPageTask.
Like,
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { url });
For more information look at this Tutorial

Categories

Resources