android set data in external database - java

i would like to write data in an external mysql database with my android app.
this class works for that:
public class SendingData extends AppCompatActivity {
Intent intent = null;
private class LoadingDataURL extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
String responseString = readStream(urlConnection.getInputStream());
intent = new Intent(SendingData.this, Overview.class);
startActivity(intent);
response = new JSONArray(responseString);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_data);
String firstname = "Max";
String secondname= "Mustermann";
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname="+fristname+
"&secondname="+secondname);
}
}
My Problem is, that if in my strings (fristname, secondname) is an & or ? or any special characters, the entry will not be save correctly.
any ideas? :)

Use the URLEncoder class.
Try this please
String fn = URLEncoder.encode(fristname, "utf-8");
String sn = URLEncoder.encode(secondname, "utf-8");
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname=" + fn + "&secondname=" + sn);
Note: Don't encode the full url, just the parameter values.

Related

Get Int from AsyncTask

class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://192.168.0.100/index.php?kod=1eba7936&mode=1");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
super.onPostExecute(result);
}
}
I got such class, its work great exept i cannot catch variable as it returns void. The result its single integer value. And System.out.println(result) display proper value on console.
I call function from MainActivity with
new GetData().execute();
My goal is to have result from GetData as integer variable in MainActivity.
I made new class with public string
public class Data {
public static String data;
}
In onPostExecute i add:
Data.data = result.toString();
And now i can use Data.data as string whetever i want.

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

JSON retriving data from HttpURLConnection

I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
#Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
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);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.

Using HttpUrlconnection in Rss Reader causes Android to hang

I put together an RSS reader that works as-is but, I want to setup the connection to the RSS URL using HttpUrlConnection method. When I tried it, the program locked up after I clicked Read Rss button:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
HttpURLConnection urlIn = (HttpURLConnection) rssUrl.openConnection();
InputStream in = new BufferedInputStream(urlIn.getInputStream());
String line;
feed = "";
while ((line = in.toString()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
This is the connection method I am stuck using which works:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
feed = "";
while ((line = in.readLine()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
Thanks for any help you can provide!
What you need to do is put it into a string I called it results. I have attached my code for the doInBackground. By adding it to a string it has a place to store the feed. And it works for the rss reader.
public String doInBackground(String... urls){
String result = "";
try{
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
conn.disconnect();
}
catch(Exception e){
Log.e("ERROR Fetching ", e.toString());
}
return result;
}

Getting text from internet

If you go to http://www.elven.ee/ip/ - you can see it gives ip. If you refresh, it gives different port.
How can I get that IP into android? I don't know how to make it also update after like every 5 seconds, but right now I want to know how can i get it into my phone. I want to display it as TextView :).
#mopsled solution did not work for me, so here is mine:
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
String ip = "";
final DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://www.elven.ee/ip/");
try {
final HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
ip = getString(response);
}
} catch (final ClientProtocolException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
tv.setText(ip);
}
private static String getString(HttpResponse response) {
final HttpEntity retEntity = response.getEntity();
if (retEntity != null) {
InputStream instream = null;
try {
instream = retEntity.getContent();
} catch (final IllegalStateException ise) {
ise.printStackTrace();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
final String result = convertStreamToString(instream);
return result;
} else {
return "";
}
}
private static String convertStreamToString(final InputStream is) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (final IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
return sb.toString().trim();
}
}
EDIT: Fixed code
Try a HTTPURLConnection (a simplified version of an example found here):
StringBuilder content = new StringBuilder();
try {
URL url = new URL("http://www.elven.ee/ip/");
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
String myIp = content.toString();

Categories