ProgressDialog is showing only if I am sending text but when I sent images it gave me an error which tells that there are lot of activities running or the app can't handle all of it, the solution is to add StrictMode.ThreadPolicy before invoking those tasks but the problem is ProgressDialog is not showing anymore which is important to tell the user about the ongoing process.
I believe it is StrictMode.ThreadPolicy that causes the ProgressDialog to disappear. I am not using Asynctask that's why I haven't found solution on the Internet yet because most of them are using it. I am also planning to use Asynctask but my boss did not approve it, he's afraid that it will ruin the app.
{
private void upLoadImage(String path){
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().penaltyDialog().build();
StrictMode.setThreadPolicy(policy);
uploadMedia(path);}}
{
private void uploadMedia(String path) {
String ImageName = "image_name";
String ImagePath = "image_path";
try {
String charset = "UTF-8";
File uploadFile1 = new File(path);
String requestURL= "http://myurl";
MultipartUtility multipart = new MultipartUtility(requestURL,
charset);
multipart.addFormField(ImageName, "iName");
multipart.addFormField(ImagePath, "iPath");
multipart.addFilePart("uploadedfile", uploadFile1);
List<String> response = multipart.finish();
Log.v("rht", "SERVER REPLIED:");
for (String line : response) {
Log.v("rht", "Line : "+line);
if(line=="true"||line=="Saved"){
progressDialog.dismiss();
}
}
// Toast.makeText(this, ""+response, Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if you access Network in UI thread the error is shown.You cannot do the network operations in the main thread.It is better to use a worker thread or ayntask. But if you are willing to accept the consequences, and must do network operations on the main thread, you can override the default behavior:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Related
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
I have an app that users can upload file. Right now it works.
They can upload files and it received in server side.
Now I want show upload percent to users while uploading.
I used below code to upload files on server.
here is my java code:
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
new MaterialFilePicker().
withActivity(AddActivity.this).
withRequestCode(10).
start();
}
catch (Exception e){
return;
}
}
});
and this is my method:
ProgressDialog progress;
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode==10 && resultCode==RESULT_OK){
progress = new ProgressDialog(AddActivity.this);
progress.setTitle("Uploading");
progress.setMessage("please wait...");
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
file_size = String.valueOf(f.length()/1024);
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("upload_file",code+file_path.substring(file_path.lastIndexOf(".")),file_body)
.build();
code2 = code+file_path.substring(file_path.lastIndexOf("."));
Request request = new Request.Builder()
.url("http://api.mysite.com/api/uploadfile")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("msg",request_body.toString());
Log.d("msg",f.getPath().toString());
Log.d("msg",getMimeType(f.getPath()));
Log.d("msg33",code+file_path.substring(file_path.lastIndexOf(".")));
if (!response.isSuccessful()){
throw new IOException(("Error:"+response));
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
Please help me to add upload percentage.
Thank you
You are doing a lot of things wrong here:
Logic responsible for uploading file should not be located in onActivityResult()
You should seperate it into different method
Using thread like that is not a good idea
If you want to upload file or large file you should do it in IntentService class (You will have to create Your own class and extend IntentService), it is something that is meant for things like that. I suggest You to learn about Retrofit2 and OkHttp library cause it will make it a lot of easier.
An example where you can find a one of the ways how to do it is here: Is it possible to show progress bar when upload image via Retrofit 2?
Asking ppl at stackoverflow to write code completly for you is not a good way to improve your skills. Check this link which I gave You.
Good luck
EDIT:
Android Services: http://www.vogella.com/tutorials/AndroidServices/article.html and https://developer.android.com/training/run-background-service/create-service
Retrofit 2: http://www.vogella.com/tutorials/Retrofit/article.html
OkHttp: https://www.journaldev.com/13629/okhttp-android-example-tutorial
Sample: Is it possible to show progress bar when upload image via Retrofit 2?
These link provides all the information You need in order to write this functionality. I don't have videos on YouTube with things like this. I'm never using YouTube to get this kind of information.
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...
I'm stuck on one problem... I try to load FB profile pic in Android:
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
public void onCompleted(GraphUser user, Response response) {
if (user != null)
{
userInfoTextView.setText(fb.buildUserInfoDisplay(user));
profilePhoto.setImageBitmap(fb.getUserPic());
}
}
});
The problem is, I get NetworkOnMainThreadException. Now I know, that I have to use AsyncTask, but if I do, I can't modify the view, because it was not created on that thread. Any ideas?
for network on main thread exception write this code before setting your layout file
if (android.os.Build.VERSION.SDK_INT > 9(minimum sdk target that you have given in your manifest file))
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
whoaa
i really need help, why my code result like that?
this is my code :
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try{
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = convertStreamToString((response.getEntity().getContent())).toString();
JSONObject obj = (JSONObject) new JSONTokener(jsonResult).nextValue();
JSONObject obj2 = obj.getJSONObject("GetRingkasObjekPajak_SingleResult");
String nameWP = obj2.getString("NM_WP");
TextView tv = (TextView)findViewById(R.id.dummy_text_three);
tv.setText(jsonResult);
}catch (MalformedURLException e) {
// URL is invalid
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("url invalid");
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("RTO");
} catch (IOException e) {
// could not read response body
// (could not create input stream)
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("couldnt read response");
} catch (JSONException e) {
// response body is no valid JSON string
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("json response fail");
}catch (Exception e) {
// TODO: handle exception
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText(e.toString());
}
i also have added internet permission
please help me
how to improve my code, so this problem solved.
Here is an example of Async task... Hope it will be helpfull to you.
private class YourAsyncTaskClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//your http network call here.
return null;
}
#Override
protected void onPostExecute(String result) {
//update your ui here
}
#Override
protected void onPreExecute() {
//do any code before exec
}
#Override
protected void onProgressUpdate(Void... values) {
//If you want to update a progress bar ..do it here
}
}
Finally call this class from anywhere you want like..
new YourAsyncTaskClass().execute();
you can not perform network operations from main UI thread. you need to do networking related tasks in different thread. Better use AsyncTask
According to the doc
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged.
NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
There is an article about Painless Threading on the Android developer site which is a good introduction to this, and will provide you with much better depth of answer than can be realistically provided here.
Run your code in AsyncTask.
You can learn about asyncTask here is best explanation with good example .
call your webservice inside aynctask.
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// call your network operation here
}
}