I am new to all of this android programming. After working out a few codes, I get the following string called ipString. I would like to display the string in a textview.
Here is what I have for now.
What should I add to make it work?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Rami","Rami");
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://jsonip.com");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jObject = new JSONObject(result);
String ipString = jObject.getString("ip");
Log.d("ip", ipString);
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
TextView myTextView = (TextView) findViewById(R.id.textview1);
Use setText() this way:
TextView myTextView = (TextView) findViewById(R.id.textview1);
myTextView.setText(ipString);
Anyway you should put those two lines inside your try, that way it would only print the String if the HTTP Request was successful.
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jObject = new JSONObject(result);
String ipString = jObject.getString("ip");
Log.d("ip", ipString);
TextView myTextView = (TextView) findViewById(R.id.textview1);
myTextView.setText(ipString);
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
BTW you should really read (and try to understand) the documentation and learn how to use your IDE.
Use setText() it will display your response text.
TextView myTextView = (TextView) findViewById(R.id.textview1);
myTextView.setText(ipString);
use setText() method like this :
String yourstringvalue;
TextView text = (TextView) findViewById(R.id.textviewID);
text.setText(yourstringvalue);
Related
i want to show a txt file by a text view and i use of this code
TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);
InputStream iFile = getResources().openRawResource(R.raw.quizhelp);
String strFile = inputStreamToString(iFile);
helpText.setText(strFile);
in api 8 i have tested and this code works fine but in my new project that i have setted min sdk to 15 , can NOT recognize inputStreamToString method ! what method i should use instead this ?
tnx
You can use BufferedReader:
TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);
InputStream iFile = getResources().openRawResource(R.raw.quizhelp);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iFile));
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
String line;
try {
while ((line = bufferReader.readLine()) != null) {
sb.append(line);
sb.append(newline);
}
} catch (IOException e) {
e.printStackTrace();
}
helpText.setText(sb.toString());
You can do it this way
TextView helpText = (TextView) findViewById(R.id.TextView_HelpText);
try {
Resources res = getResources();
InputStream ins = res.openRawResource(R.raw.quizhelp);
byte[] b = new byte[ins.available()];
ins.read(b);
helpText.setText(new String(b));
} catch (Exception e) {
e.printStackTrace();
}
I want to read XML file which is store in editTextxml.setText(xml).
In that rss xml tags are there and i want to use XML parser to display this tags.
view-source:http://syndication.indianexpress.com/rss/latest-news.xml
public class XmlDownloader extends Activity {
LoginDataBaseAdapter loginDataBaseAdapter;
InputStream in;
String xml;// = onGet
// ("http://syndication.indianexpress.com/rss/latest-news.xml");
Button downloadxml;
Button parsingXML;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xmldownloader);
downloadxml = (Button) findViewById(R.id.downloadxml);
final EditText editTextxml = (EditText) findViewById(R.id.editTextXml);
parsingXML = (Button) findViewById(R.id.ParsingXMLData);
downloadxml.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onGet("http://syndication.indianexpress.com/rss/latest-news.xml");
Log.d("test", xml);
editTextxml.setText(xml);
}
});
}
private String onGet(String url) {
// TODO Auto-generated method stub
/* String result = null; */
HttpResponse response;
HttpEntity entity;
try {
HttpPost httppost = new HttpPost(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(httppost);
entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 8 * 1024);
while ((line = reader.readLine()) != null) {
sb.append(line); // .append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
}
xml = sb.toString();
}
entity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return xml;
}
I want to use editTextxml.setText(xml) to get XML parsing in another Button
What is the XML parsing for this code
I am trying to get the data from URL and convert it into String Array, but when I try to show it on TextView its show nothing. The link and itemId that I use is already right.
There's no Error warning on logcat.
I can't figure it out why.
Is there anyone can't help me?
Here's my json data
[{"image":"http://cdn-data.apps.com/category_item/05d92b217f916c9b9d87ab9121662d87.jpg"},
{"image":"http://cdn-data.apps.com/category_item/0424ef5a980255ff989fe5b20eaa5dcd.jpg"},
{"image":"http://cdn-data.apps.com/category_item/02b5bce4a9ca8fa3e53ceea2c7e273ff.jpg"},
{"image":"http://cdn-data.apps.com/category_item/dd15419113c091c93eafb3695eb65153.jpg"},
{"image":"http://cdn-data.apps.com/category_item/1ddfd2d7a489678e3c66e7f012ceb951.jpg"}]
Here's my Java code
if(in.getStringExtra("TAG_IMAGE_COUNT").equals("0")) {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.GONE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.GONE);
}
else {
ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
imagePager.setVisibility(View.VISIBLE);
CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
imageIndicator.setVisibility(View.VISIBLE);
try {
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String json = reader.readLine();
//JSONObject jsonObject = new JSONObject(json);
JSONArray arr = new JSONArray(httpResponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
String[] stringArr = list.toArray(new String[list.size()]);
TextView array = (TextView)findViewById(R.id.testarray);
array.setText(Arrays.toString(stringArr));
Log.d("", json);
//Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I try to show it on testarray but its show nothing.
First of all your have to parse a String not Httpresponse:
here you do:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
JSONArray arr = new JSONArray(httpResponse);
Change a little like:
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
And finally set the list data as you want in your textView out of the background thread.
you should not use any UI thread views (e.g button, textview, edittext ..) in background thread.
EDIT:
private class GetImages extends AsyncTask<String, Integer, ArrayList<String>>{
ArrayList<String> list = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(String... params) {
try {
HttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String returnValues = "";
while((returnValues = reader .readLine()) != null){
JSONArray arr = new JSONArray(returnValues);
//Define this list globally ,so you can use it any where of this class after adding data
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("image"));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
//use this result and put in your textView
}
}
I am trying to execute the following code for retrieving data from database using web services:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getData(){
TextView resultView = (TextView) findViewById(R.id.textView1);
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag","Error in http connection"+e.toString());
resultView.setText("Couldnt connect to database");
}
//converting to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result"+ e.toString());
}
//parse data
try{
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i = 0;i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s + "St.ID" + json.getString("StId") + "\n " +json.getString("StName") + "\n" + json.getString("StMail");
}
resultView.setText(s);
}
catch(Exception e){
Log.e("Log_tage", "Error Parsing Data"+e.toString());
}
}
But an error returns : Couldn't connect to database.
And here's the output LogCat:
11-14 20:10:35.057: E/log_tag(5323): Error in http connectionandroid.os.NetworkOnMainThreadException
11-14 20:10:35.057: E/log_tag(5323): Error converting resultjava.lang.NullPointerException: lock == null
11-14 20:10:35.057: E/Log_tage(5323): Error Parsing Dataorg.json.JSONException: End of input at character 0
I've added a php file on some web service and it's working well, but i think it's about the HttpPost URL, is there a specific format for the HttpPost URL or is it just the same URL as given in the web service ?
PHP file:
<?php
$con = mysql_connect("HOST","USERNAME","PASSWORD");
if (!$con)
{
die('Could not Connect:'. mysql_error());
}
mysql_select_db("database_name",$con);
$result = mysql_query("SELECT * FROM table_name");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
Please help with that.
There is no specific format for the HttpPost URL, it is just the same URL as given in the web service.
You must use AsyncTask to solve the "Couldn't connect to database" error.
Here is your code using AsynTask, also you have to set the text of the TextView in the onPostExecute method, like shown:
RetrievingDataFromDatabase retrievingTask;
TextView resultView;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrievingTask = new RetrievingDataFromDatabase();
retrievingTask.execute((Void) null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getData(){
resultView = (TextView) findViewById(R.id.textView1);
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Couldnt connect to database");
}
//converting to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
//parse data
try {
s = "";
JSONArray jArray = new JSONArray(result);
for(int i = 0; i < jArray.length(); i++){
JSONObject json = jArray.getJSONObject(i);
s = s + "St. ID" + json.getString("StId") + "\n " + json.getString("StName") + "\n" + json.getString("StMail");
}
}
catch(Exception e) {
Log.e("Log_tage", "Error Parsing Data" + e.toString());
}
}
class RetrievingDataFromDatabase extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
resultView.setText(s);
}
}
Problem solved and data retrieved by using #Carlo 's code and editing the following line of code:
HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
to:
HttpGet httppost = new HttpGet("http://HOSTNAME/FILENAME.php");
as mentioned in my code, i wanted to retrieve data from the URL not posting data.
HttpPost > used for submitting data to a specified resource.
HttpGet > used for retrieving data from a specified resource.
Thanks all for your help.
I execute by new CreateNewThread().execute();
class CreateNewThread extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateThread.this);
pDialog.setMessage("Creating Thread..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
tittel = inputTitle.getText().toString();
tekst = inputText.getText().toString();
if (!tittel.equals("") && !tekst.equals("")) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://.../createthread?title="
+ tittel + "&text=" + tekst);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
is,"iso-8859-1"));
System.out.println(tittel);
System.out.println(tekst);
System.out.println(in);
String line;
while ((line = in.readLine()) != null) {
JSONObject jo = new JSONObject(line);
System.out.println(jo.getString("svar"));
}
} catch (Exception e) {
System.out.println("catchgreiene" + e);
}
}
else {
System.out.println();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
I'm trying just to run an url. The php-file runs in browser.. This is 2.2 Froyo.
What am I missing here?
I've tried other methods, but this works for a friend. So it should work.
I don't know if it's the problem, but you should NEVER do a System.out.println in android. Use Log.w("tag","key") instead!