How to update/refresh TextView to show updated Json data every second? - java

I want to create an online queue monitoring application which it will show the new data entered to the database.The UI sample is below
I want the Current Serving Ticket to update every second if there is a new data entered(Json).
Here the MainActivity.java
public class MainActivity extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button input_number = (Button) findViewById(R.id.button2);
Button reminder = (Button) findViewById(R.id.button);
final TextView userinputtext = (TextView) findViewById(R.id.textView6);
data = (TextView)findViewById(R.id.textView10);
Here is the data.java that i created.
public class data extends AsyncTask<Void,Void,Void> {
String data=" ";
String singleParsed = " ";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("url/SamplePage.php");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line ="";
while(line!=null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for (int i =0; i<JA.length();i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = JO.get("ticket_number")+"";
//dataParsed = dataParsed + singleParsed;
}
}catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.singleParsed);
}
}
If there is any comment or help I would appreciate. Thanks.

The fastest answer would be setting a timer each second to query the database for data, and update the view.
If you're looking for a more optimized, complete, documented and easier solution, I suggest you use firebase, which offers services like Realtime database : https://youtu.be/U5aeM5dvUpA
Of course there are other alternatives like RethinkDB.
You should also look up websocket since they are similar approach to this kind of real time update problem.
But firebase is perfect for this in my opinion.

You can use SyncAdapter and LiveData. If you use Room, it will be more easier to handle.

Related

I want to pass the string that I got from the string to the onPostExecute method

I am New to the android studio and want to something more. Actually, I am trying to pass the string that I got from the spinner in onCreateMethod and pass to the onPostExecute function. I will be grateful for the help. Bellow is my code.
I tried making a global variable called First and store the string from spinner and pass it on the onPostExecute function.
public class Convert extends AppCompatActivity implements LocationListener
{
Spinner dropdown;
Button btn;
String text;
String first;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
dropdown = (Spinner) findViewById(R.id.spinner1);
btn = (Button)findViewById(R.id.btn);
String[] items = new String[]{"United States,USD", "Nepal,NPR", "Bangladesh,BDT","Brazil,BRL"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text = dropdown.getSelectedItem().toString();
first = text.substring(text.length()-3);
Log.i("her", first);
}
});
new DownloadTask().execute("http://openexchangerates.org/api/latest.json?
app_id=XXXXXXXXXX");
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char counter = (char) data;
result += counter;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
JSONObject jsonObject = new JSONObject(result);
JSONObject curr = jsonObject.getJSONObject("rates");
String npr = curr.getString(first);
Log.i("money", npr );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
What I want is to pass the string first on the onPostExecute function.
When you will call your DownloadTask, asyncTask fires with method execute, just pass param though him. Example:
How to pass url
new DownloadTask().execute("url for download");
How to receive url
protected String doInBackground(String... urls) {
String url = urls[0]; // url for download
}
Also you could send and array of params. Also be careful with AsyncTask, do not pass your context/view variable, it could arise memory leaks, read docs.

Where should I put my AsyncTask class for my app?

So I have been trying to make a feature in my app where I can login and then fetch data from my database through the Django REST Framework. My logging in works as it only uses POST, but retrieving items does not work.
For some reason my AsyncTask does not get called for retrieving posts.
I have placed my AsyncTask for both activities, which are login and posts, on a separate java file only for handling Web Server stuff.
I am wondering if this is because I should put AsyncTask on each activities.
login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Yes, you can and should put the network calls functions in a separate java file for better readability and test-coverage.
Apart from that, i would suggest to use Retrofit as your HTTP client. It helps you to manage all the dirty things like headers and converters etc, so you can put all your effort on your logic and implementing your callback actions.

On retrieving images from json get "The application may be doing too much work on its main thread" error

I want to retrieve photos in background using AsyncTask. I get photo as string in base64 encoded form. However, I have "The application may be doing too much work on its main thread" error message.
My activity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ItemClickHandler{
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private LayoutManager layoutManager;
private ArrayList<Device> devices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action_bar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(devices, this);
recyclerView.setAdapter(adapter);
initImages();
}
private void initImages() {
Thread thread = new Thread() {
#Override
public void run() {
for(int i = 0; i < devices.size(); i++){
final int pos = i;
GetImageJSON getImage = new GetImageJSON(MainActivity.this){
#Override
protected void onPostExecute(final String result) {
Log.d(TAG, result);
if(pos <= recyclerView.getLayoutManager().getChildCount()){
adapter.updateItem(ImageManager.convertToBitmap(result), pos);
}
}
};
getImage.execute(ConnectionConfig.getUserItemImage(devices.get(i).getId()));
}
}
};
thread.start();
}
}
GetImageJSON class:
public class GetDataJSON extends AsyncTask<String, Void, String> {
private static String charset = "UTF-8";
#Override
protected String doInBackground(String... args) {
String result = parseJSONString(args[0]);
if(!result.isEmpty()){
try{
JSONObject json = new JSONObject(result);
JSONObject jsonObject = json.getJSONObject(ConnectionConfig.TAG_RESULT);
String base64String = jsonObject.getString("image");
Log.d(TAG, base64String);
Bitmap bitmap = ImageManager.convertToBitmap(base64String);
bitmap = ImageManager.scaleDownBitmap(bitmap, context);
Log.d(TAG, "got result: " + result);
return ImageManager.convertBitMapToString(bitmap);
}catch (JSONException e){
e.printStackTrace();
}
}
return result;
}
public static String parseJSONString(String... args){
String result = "";
InputStream inputStream = null;
Log.d(TAG, args[0]);
try {
URL url = new URL(args[0]);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
try {
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
} catch (Exception e) {
Log.d(TAG, "Exception", e);
} finally {
try{
if(inputStream != null)
inputStream.close();
}catch(Exception e){
Log.d(TAG, e.getMessage());
}
}
return result;
}
}
I could not find any solution. Please, suggest any one. How I can optimize the process of retrieving data.
I can't tell for sure without a runnable version of your code, but I would guess that having the line ImageManager.convertToBitmap(result)
in onPostExecute() is causing the "too much work on main thread" problem. Anything that happens in onPostExecute() happens on the main thread, so you want to keep that method as light as possible. As SRB suggested, you could avoid this by having doInBackground return the bitmap, instead of a String that needs to be converted back into a bitmap. Note that to change the return type, you'll need to change String to Bitmap in two places:
public class GetDataJSON extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... args) {
// TODO return the bitmap
}
//...the rest of your code
}
On a separate note, it looks like there's some room for improvement in your code. These are things that aren't directly related to your question but that it'd be good to understand.
When you call getImage.execute(), doInBackground method of the GetDataJSON class will be executed. The doInBackground method always runs on background thread (see "The 4 steps" section here), so there's no reason to create a new thread in the initImages() method.
One of benefits of using a recyclerview is that you don't need to load everything when recyclerview appears on the screen. If there are views that are off screen, those views can be created when the user scrolls towards them. By retrieving all the images when the activity is created, you're losing that benefit.
There are image loading libraries like Picasso and Glide that will do background image fetches for you. I don't know what your web API looks like, but if you're able to, using a preexisting library can make it simple to quickly deal with issues like placeholders, caching, resizing, etc.

Trying to load JSON from a URL and don't know how to handle Exceptions

I'm trying to load JSON from a URL in an Android app (the URL only links to JSON data, there is nothing else).
For now I'm only trying to load the content of the URL into a String.
The problem I have is that I need to handle the Exceptions, but I'm not too familiar with that.
Here is the relevant part of my 'Functions' class:
static public String loadURL(String inputURL) throws Exception {
String fullString = "";
URL url = new URL(inputURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
This is what I'm currently using (in a different class) for testing purposes:
Toast.makeText(Setup.this, Functions.loadURL("http://www.exampleJSON.com"), Toast.LENGTH_LONG).show();
I'm planning on using the output to extract JSON data for if-statements, saving in sharedPreferences and displaying.
EDIT
Here what I'm using to call the method:
public class Setup extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
final SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final EditText editText = (EditText) findViewById(R.id.editText);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.setup_region_spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//BUTTON PRESS
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("Server", String.valueOf(spinner.getSelectedItem()));
if (String.valueOf(spinner.getSelectedItem()).equals("EUW")) {
}
else if (String.valueOf(spinner.getSelectedItem()).equals("NA")) {
try {
Toast.makeText(Setup.this, Functions.loadURL("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" +
editText.getText().toString().replaceAll("\\s", "") +
"?api_key=cbc50791-3c4d-45e6-b0c1-8aa204ced475"), Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
}
//ERROR
else {
Toast.makeText(Setup.this, "Server selection error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
The try-block was just added after reading through the answers. Another one was added in my loadURL method. It seems to work for now.
I'm now getting errors because I was trying to run this on the main thread. I'll have to read more about that.
Put your code inside try block and catch the exception:
try {
String fullString = "";
URL url = new URL(inputURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
First, go through the basic JSON format. There are basically two things to look at :
JSONObject
JSONArray
Once you are comfortable with these two, try parsing the response using :
try{
JSONObject jsonObject = new JSONObject(<your_response_string_here>);
//Your parsing logic here
}catch(JSONException ex){
ex.printStackTrace();
}
Lets say your json was :
{
"some_status": 200,
"my_data": {
"param1": "value1",
"param2": "value2"
},
"my_array": ["arrayvalue1", "arrayvalue2"]
}
Your code should look somehting like this:
try{
JSONObject jsonObject = new JSONObject(<your_response_string_here>);
//Your parsing logic here
int status = jsonObject.optString("some_status");
JSONObject my_data = jsonObject.optJSONObject("my_data");
//Here parse your "my_data" object to get "param1" and "param2"
JSONArray my_array = jsonObject.optJSONArray("my_array");
//Here parse your "my_array" array to get "arrayvalue1" and "arrayvalue2"
}catch(JSONException ex){
ex.printStackTrace();
}
Please go through Android DOCS: http://developer.android.com/reference/org/json/JSONObject.html
And some examples like : http://www.tutorialspoint.com/android/android_json_parser.htm
I hope this helps.

Any way to edit a URI based on User Input?

I have an HTTP GET that is receiving information from a URI. The URI is for Google Shopping.
https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom
(Left my key out).
Is there a way that I can change it from
q=digital+camera
to anything a user puts in an EditText?
So basically, I want the EditText to change what is searched on Google Shopping.
First screen, ProductSearchEntry with EditText for search query:
Code for ProductSearchEntry
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
startActivity(searchIntent);
}
});
}
}
Then, I have a second class, ProductSearch, with no picture, but just this code:
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Which references the ProductSearchMethod class which consists of a TextView that is changed to the code recieved in the HTTP GET:
Code:
public class ProductSearchMethod {
public String getSearchData(String query) throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
HttpGet request = new HttpGet();
request.setURI(site);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
ProductSearchMethod comes up great, but it doesn't change the text from "Loading Items" to the website code. I had it working before but then I tried to edit what it searched (all this ^) and now it doesn't change.
Make changes in your code like
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
EditText etSearch = (EditText) findViewById(id of your edittext);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//while calling intent
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
searchIntent.putExtra("searchText",etSearch.getText().toString());
startActivity(searchIntent);
}
});
}
}
and another activity like this,
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
String searchQuery = getIntent().getStringExtra("searchText");
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery);
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Yeah... Change your getSearchData() method to include a string as a parameter
public String getSearchData(String query) throws Exception{
Then, insert that string into the query URL, replacing spaces with "+". You may want to do further conditioning to the string, for instance URL encoding it.
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
In your XML, create a button that contains the following line:
android:onClick="search"
In your ProductSearch activity, add the following method, and move the code in onCreate into it. You will also need to create an EditText in your XML for input.
public void search(View v)
{
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String returned;
try {
returned = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Finally, you will probably want to read up on running asynchronous tasks so that the query won't freeze your app while performing.
May be I got you wrong, but why don't you just pass it as a parameter in
getSearchData() => getSearchData(string query)
Then you can change the line
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom");
to
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=+ URLEncoder.encode(query, "UTF-8")+&alt=atom");
Check out http://androidforums.com/developer-101/528924-arduino-android-internet-garage-door-works-but-could-use-input.html I use Asynctask to trigger a get command on a local Arduino server. It appends the Arduino's pin number and, depending on if it's needed, a port number to the end of the URL. I'm sure you could use it to help you out.

Categories