Android Studio OnCreate Never used warning - android

This is an rssfeed and everything compiles and I don't think i am missing anything but my app wont launch and there is a warning about my OnCreate never being used. I am unsure if this is related to the problem.
public class MainActivity extends AppCompatActivity {
private TextView src;
private Button btn;
protected void OnCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.activity_main);
src = (TextView) findViewById(R.id.text);
btn = (Button)findViewById(R.id.Fetch);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch();
}
});
}
public void fetch() {
Downloader d = new Downloader();
d.execute("https://en.wikipedia.org/wiki/Main_Page");
try {
src.setText(d.get());
} catch (Exception e) {
Log.e("Error to thread", e.toString());
}
}
class Downloader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = null;
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 = null;
while ((line = reader.readLine()) != null) {
result = result + line;
}
conn.disconnect();
reader.close();
} catch (Exception e) {
Log.e("error to fetching", e.toString());
}
return result;
}
}

The correct writing is onCreate, not OnCreate. Try to change that.

OnCreate --> onCreate and use #Override

Related

Parse Json data into a Json object

I have a problem with parsing a tag inside a Json object.
My json code is structured like that:
{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}
I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object.
This is the code I got:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://api.myjson.com/bins/177dpo");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
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+"\n");
Log.d("Response: ", "> " + 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);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
I've never worked with this type of file so I'll really appreciate your help!
You can use something like this:
try {
String servResponse = response.toString();
JSONObject parentObj = new JSONObject(servResponse);
JSONArray parentArray = parentObj.getJSONArray("giocatori");
if (parentArray.length() == 0) {
//if it's empty, do something (or not)
} else {
//Here, finalObj will have your jsonObject
JSONObject finalObj = parentArray.getJSONObject(0);
//if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
nomeGiocatori = finalObj.getString("nome");
}
} catch (Exception e) {
Log.d("Exception: ", "UnknownException");
}
I use this kind of code all the time, works like a charm.

Call Textview in Thread on Android

This is my code.when I click on button ,it call yourcountry() function then yourcountry() in a thread call location(). I get data from http://192.168.4.1/led/0 with WIFI connection. while-loop runs about 25 times and then it appears Unfortunately app has stopped .I think the problem is in :
runOnUiThread(new Runnable() {
public void run() {
country.setText(show);
}
});
This is my code:
public class MainActivity extends AppCompatActivity {
public Button button;
public TextView country;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
country=(TextView) findViewById(R.id.country);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourcountry();
}
});
} // end of oncreate
public void yourcountry() {
new Thread(new Runnable() {
#Override
public void run() {
location();
}
}).start();
}
private void location() {
// while (true) {
while (true){
try {
URL url = new URL("http://192.168.4.1/led/0");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String data = "", line = "";
while ((line = bufferedReader.readLine()) != null) {
data += line+"\n" ;
}
show = data;
runOnUiThread(new Runnable() {
public void run() {
country.setText(show);
}
});
sleep(50);
} catch (MalformedURLException e)
{
Log.e("error", e.toString());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}//end of while
} //end location
}//end of class
Calling a runnable from a new thread doesn't put it in the main thread.
I think you would have better luck wrapping your functions in an AsyncTask. You can do all of your UI work in the
onPostExecute()
Otherwise, you need to wrap your runnable in a handler to ensure you're running it on the UI thread.
Edit::
public class MainActivity extends AppCompatActivity {
public TextView country;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
country=(TextView) findViewById(R.id.country) ;
new MyAsyncTask().execute();
}//on creaate
static boolean shouldRun = true;
class MyAsyncTask extends AsyncTask<Void, Void, String> {
boolean firstRun = true;
#Override
protected String doInBackground(Void... params) {
if (!firstRun) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
} else {
firstRun = false;
}
String data = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL("http://192.168.4.1/led/0");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
data = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
data += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
data = null;
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
if (data != null) {
country.setText(data);
}
if (shouldRun) {
new MyAsyncTask().execute();
}
}
}
}
Then you can call:
new MyAsyncTask().execute();
And Permission:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit::
While(true) isn't good practice, since you have no breaks set. This will run forever (which you don't want).
You can spin off another async task when the first one finishes under some condition.

App not able to extract json data

I am trying to extract Json data, but somehow the code is not working.
Can somebody please help me ? Can't seem to understand what i am doing wrong.
(I dont really hav any more details to add)
public class MainActivity extends AppCompatActivity{
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.exchangeRate);
Anindya task = new Anindya();
task.execute("xyz");
}
public class Anindya extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(System.in);
int data = reader.read();
while (data!= 0)
{
char current = (char)data;
result += current;
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);
Log.i("website content",result);
}
}
}
Try replacing InputStreamReader reader = new InputStreamReader(System.in) with InputStreamReader reader = new InputStreamReader(in)
If it still doesn't solve your problem then try to check the value of data and post details about returned value.

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);

Android Programming: HTTP GET REQUEST NOT WORKING

I require a GET reequest from my own server to be extracted from the web and then displayed on screen with a TextView.
I have set up a GET Request.
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
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();
}
}
}
}
}
And I have set up on my main thread to extract the information and display it in a text view.
public class Home extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
httpStuff = (TextView) findViewById(R.id.tvhttp);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
However, the Textview doesnt seem to change?
Can someone help me please.
Change your code using AsyncTask if you want to make any network operation from Ui Thread as:
public class Home extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
httpStuff = (TextView) findViewById(R.id.tvhttp);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returned;
}
#Override
protected void onPostExecute(String result) {
// Update Ui here
httpStuff.setText(result);
}
}
}
Android OS > = 3.0
does not allow NetworkRequest on main UI thread.
Use AsyncTask to call webrequest.

Categories

Resources