inside oncreate method can't read the content of php file? - java

I created an android app. I try to get content from a PHP file. I wrote the logic in below getCont() method, but it doesn't work. It always returns null in Android. When I do the same with Java it returns the PHP content. How to solve this, so no exception is thrown.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String dbcont = getCont();
tone = (TextView)findViewById(R.id.textView1);
tone.setText("usean :-)"+dbcont);
}
public String getCont() {
String mit = null;
try {
URL oracle = new URL("http://localhost/grace/conn.php");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
StringBuilder sb = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
mit = sb.toString();
System.out.println(mit);
}
catch(Exception e){
e.printStackTrace();
}
return mit;
}

You're saying you're not getting an exception? You're opening a URL connection on the UI Thread. This is restricted on android. I'm surprised the app isn't crashing.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
You have to use a separate thread to perform network functions. Read this
http://developer.android.com/reference/android/os/AsyncTask.html
You need to create a class that extends ASyncTask, then in the doInBackground() method, you can open the connection to fetch your PHP file.
You can then return the results which will be passed on to the onPostExecute() method. That will allow you to pass the data from the connection (i.e. the PHP file) back to your UI thread.
Let me know if this helps.

Related

How to get logcat -v time in an Android App?

I need to get logcat -v time from a device and save it to a text file in a SD Card. The problem is that my application freezes when I press the button to do it.
I understand that it might happen because logcat -v time keeps getting the log of all actions of the device, nonstop. And I need all this information. But I don't know how to code it correctly. Would anyone could help me, please?
Thanks in advance!
Here is my code:
btn_comeca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Process process = Runtime.getRuntime().exec("logcat -v");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
try {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
//Verifica permissão de gravar/ler
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MODE_ENABLE_WRITE_AHEAD_LOGGING);
}
}
File caminho_arquivo = new File("/sdcard/ARQUIVOFINAL.txt");
caminho_arquivo.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(caminho_arquivo);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
TextView tv = (TextView)findViewById(R.id.texttext);
String texto = "";
//tv.setText(log.toString());
texto = log.toString();
//outputStreamWriter.append(tv.getText());
outputStreamWriter.append(texto);
outputStreamWriter.close();
fileOutputStream.close();
Toast.makeText(getBaseContext(), "Text File Saved!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {}
}
The problem may be: your logic works synchronously. You should never execute work like that in main thread, since it can lead to ANR (Android Not Responding).
There is plenty of ways to fix that, though. Since you are not using frameworks for multithreading (e.g. RxJava, you can read about it, if you are interested), you can use AsyncTask. You can place this in your listener.
EDIT: However, take a look at MVVM or MVP pattern and multithreading frameworks later. These things are widely used in production for executing different kinds of asynchronous tasks.
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
// Place your logic here
return;
}
}.execute();
Normal invocation of logcat won't every exit by itself.
Therefore your code will be forever stuck in your while loop.
As per https://developer.android.com/studio/command-line/logcat
Use the -d "Dump the log to the screen and exits." commandline option.
This is what I use in a similar method to display the logcat output in to a TextView

SQLite to Register on multiple device- Android

I'm developing a course selection app for a university. Students must register to application. I'm using SQLlite by using db helper, my table contains studentID,password,name etc.
My question is this sqlite db stays on only local ? I mean, how can i reach student table on multiple device, read and write at the same time. When it puts on the play store thousand of student will use it.
Which technologies should i use, where should i put the db ?
I'm really confused about it, thanks for advance.
By sqlite it is not possible. You have to create the database on server. For that thing you can use mysql, oracle etc. So from server n number of students can access the data.
There are many times when your Android app will need to fetch data from the internet, to provide users with fresh information and/or data. There are different ways your app could achieve this. You could set up your own web service/API, or you could be fetching from an already existing service/API.
1) To get the data from API Luckily, there is a class just for this, called AsyncTask. From the Android documentation, AsyncTask facilitates the proper and easy use of the UI thread, by allowing the performance of background operations, and publishing the results on the UI thread without the need for manipulating threads and handlers. In simple words, AsyncTask handles all the complexity for you.
2) To make use of the AsyncTask features, you must subclass it, and provide 3 generic types, called Params, Progress and Result. Params refers to the parameters that would be parsed to your Task, Progress refers to the progress indicator/counter type, and Result is what would be returned on completion of the task. AsyncTask has 4 important methods, onPreExecute (what to do before the expensive task begins), doInBackground (the actual expensive operation goes in here), onProgressUpdate (what to do to show progress), and onPostExecute (what to do when the task is complete).
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
Read this tutorial to use this feature: http://www.androidauthority.com/use-remote-web-api-within-android-app-617869/
Also see this documentation: http://developer.android.com/reference/android/os/AsyncTask.html

Android - AsyncTask or Thread while recovering data to SQLite

I'm having trouble figuring out how to make this work.
I'm developing an app in which I download data from a online txt, parse it and add it to my database. This is taking +-30 seconds, and there is only one part of the updater implemented.
When I try to use a Thread or Asynctask, I have problems when trying to pass the arguments to the void which is updating the Database.
How can I implement it on the good way?
Here is my code:
Main activity class:
public class Androideye_principal extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//WhazzupUpdate.DownloadWhazzup(AllUsers, TotalConnections);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_androideye_principal);
PilotsSQLiteHelper pdbh = new PilotsSQLiteHelper(this, "PilotsDB", null, 1);
SQLiteDatabase dbPilots = pdbh.getWritableDatabase();
Context context = getApplicationContext();
String TotalConnections = new String();
WhazzupUpdate.DownloadWhazzup(dbPilots, TotalConnections, context);
dbPilots.close();
CharSequence text = "Total Users: " + TotalConnections;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
[Continues with Buttons stuff and so on...]
Parser class:
public class WhazzupUpdate {
public static void DownloadWhazzup (SQLiteDatabase PilotsDB, String TotalConnections, Context context) {
try {
// Create a URL for the desired page
URL url = new URL("This is my url/whazzup.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
for (int i = 0; i<=4; i++) {
in.readLine(); } // Go to the number of connections
TotalConnections = in.readLine();
for (int i = 0; i<=3; i++) {
in.readLine(); } // Go to !CLIENTS
PilotsDB.execSQL("DELETE FROM Pilots");
while (((str = in.readLine()) != null) && !(in.readLine().contains("!AIRPORTS"))) {
// str is one line of text; readLine() strips the newline character(s)
String[] dataRow = str.split(":");
if (str.contains("PILOT")) {
ContentValues NewValue = new ContentValues();
NewValue.put("VID", dataRow[1]);
[More NewValue puts...]
PilotsDB.insert("Pilots", null, NewValue);
} //End IF Pilot
} // End While
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}}
As you see, I call WhazzupUpdate.DownloadWhazzup Method in the main activity, and this is when all is getting frozen, but don't know how to derivate it to another threat and keep the references to the Data Bases and so on...
Hope anyone can help me. Thanks in advance.
A Thread or AsyncTask would be fine here. I prefer using AsyncTask for most of my heavy-lifting. You can create an AsyncTask and do your work in doInBackground() as it works on a background Thread. Then you can update your UI elements if needed in any of its other methods.
onPostExecute() will run after a result is passed from doInBackground()
onProgressUpdate() will run if you need to update UI during doInBackground() operations by calling publishProgress(). Here you can show a ProgressBar if you need to
and
onPreExecute() will run when you first call your task before doInBackground() runs.
Running the code in a background thread using Thread or AsyncTask will allow your UI to be free while the heavy work is being done.
Example of AsyncTask
Using interface with AsyncTask to post data back yo UI
AsyncTask Docs

create an android app that reads text from url

I found the answer
Include the following two lines in your “onCreate” method of the Main Activity:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
I created an android app that will read text from a URL and display the text on the screen. It crashes when my input is "http://web.njit.edu/~halper/it114/l2d.txt" but does nothing when my input is "http://web.njit.edu/~halper/it114/l2d.txt". I tried to add android.permission.INTERNET to Manifest.xml and I still get the same result.
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
Caused by: java.lang.reflect.InvocationTargetException
Caused by: android.os.NetworkOnMainThreadException
Thank you very much for your time
public void enter(View v) {
EditText input = (EditText) findViewById(R.id.edit_file);
TextView tv = (TextView) findViewById(R.id.text_main);
try {
URL url = new URL( input.getText().toString() );
Scanner scan = new Scanner( url.openStream() );
while( scan.hasNext() )
tv.append( scan.nextLine() );
}
catch(MalformedURLException e) { e.printStackTrace(); }
catch(IOException e) {e.printStackTrace();}
}
This is working for me:
public String getTextFromTheMagicKingom() throws ClientProtocolException, IOException {
String url = "http://web.njit.edu/~halper/it114/l2d.txt";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
And please correct the format in your comment. Have a nice day ._./
Caused by: android.os.NetworkOnMainThreadException
Since HoneyComb we've no longer been allowed to make network calls on the UI thread because they're potentially slow and it would be silly to hang the UI while waiting on a server. You need to place your network code in a separate Thread, or use AsyncTask, or a library such as Volley.
If this is just to test things out then you could also turn of StrictMode which is what disallows network access from that thread...
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); //Disabling StrictMode is not recommended. It is much better to make Asynchronous network calls...
You should have posted the code where you make the network request as well. It seems you're doing exercises for yourself, so I would recommend just using a Thread and using its runOnUiThread() method when you get your response. AsyncTask has much more functionality than you need...

FileNotFoundException in HttpRequest every second time

In my android app, i want to let the user fetch data from a website (by sending an http request). The http-response is then sent to another activtiy which shows the data. (i made this a bit simplier in this example code. In real, the data is parsed into an object and the object is sent).
This all works good with my code. But when the user goes back to the main activity by pressing the back key, and trys another request, the application throws an java.io.FileNotFoundException while getting the input stream from the URLConnection. If the app is closed (by pressing back again) and then reopend, all works well again.
Im pretty sure its a problem with a connection not being closed properly or something like that but i cant find the error in my code.
Any idea whats wrong here?
MainActivity.java
*no interessting code here.
it just calls the static function from MainMethods.java
when a button is pressed*
MainFunctions.java - I want to call the methods from several classes so its in an extra class
class MainFunctions {
public static void search(final Activity, final String searchString) {
new AsyncTast<String, String, String>() {
protected void onPreExecute() {
// im opening a progress dialog for the activity here
}
protected String doInBackground(String... searchString) {
try{
return new HttpUtils().sendRequest(searchString)
} catch (Exception e) {
// print a dialog, stacktrace and stuff
return null;
}
}
protected void onPostExecute(String result) {
if(result != null) {
// dismiss the dialog etc..
Intent i = new Intent("packagename");
i.putExtra("key", result);
activity.startActivity(i);
}
}
}.start(searchString)
}
}
HttpUtils.java
public class HTTPUtils {
public String sendRequest(String data)
throws IOException {
String answer = "";
URL url = new URL("http://myURL.com/" + data);
URLConnection conn = url.openConnection();
conn.setReadTimeout(5000);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
answer += inputLine;
in.close();
return answer;
}
}
The Stacktrace shows that the Exception is thrown while conn.getInputStream() is called.
java.io.FileNotFoundException: http://myURL.com/danijoo
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java)
at com.elophant.utils.HTTPUtils.sendRequest(HTTPUtils.java:20)
at com.elophant.Elophant.getSummoner(Elophant.java:183)
at com.lolsummoners.datacollector.Collecter.getSummonerInfo(Collecter.java:39)
at com.lolsummoners.utils.MainFunctions$1.doInBackground(MainFunctions.java:106)
at com.lolsummoners.utils.MainFunctions$1.doInBackground(MainFunctions.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java)
at java.lang.Thread.run(Thread.java)
The Methods getSummoner() and getSummonerInfo() are methods to parse objects out of the response string. i let that out to make the problem easier to undearstand.
Thanks!

Categories

Resources