I'm following this tutorial (http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/) to uploading photo. And I'm using header authentication in httppost. But, why when uploading didn't work.
I using 'org.apache.httpcomponents:httpmime:4.3.6' in my dependencies.
Anyone can help me.
This my Activity.
public class SendReportActivity extends Activity {
private static final String TAG = SendReportActivity.class.getSimpleName();
private String filePath = null;
private ImageView imgPreview;
private ProgressBar progressBar;
private TextView txtPercentage;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_report);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnUpload = (Button) findViewById(R.id.btnKirim);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
Intent i = getIntent();
filePath = i.getStringExtra("filePath");
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConfig.URL_LAPOR);
httppost.addHeader("Authorization", "Basic " +
Base64.encodeToString((AppConfig.USER_API + ":" + AppConfig.PASSWORD_API).getBytes(), Base64.DEFAULT));
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
entity.addPart("data_des", new StringBody("OK"));
entity.addPart("data_upload", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
This error log.
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.Consts
at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:148)
at com.company.report.activity.SendReportActivity$UploadFileToServer.uploadFile(SendReportActivity.java:232)
at com.company.report.activity.SendReportActivity$UploadFileToServer.doInBackground(SendReportActivity.java:208)
at com.company.report.activity.SendReportActivity$UploadFileToServer.doInBackground(SendReportActivity.java:186)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to create an Android app for weather. After some failed results, I decided to try a code from the internet. It still doesn't work.
I found it here: https://androstock.com/tutorials/create-a-weather-app-on-android-android-studio.html
The error I'm getting is:
I have checked the url with my actual API key - in browser it works.
MainActivity:
public class MainActivity extends AppCompatActivity {
TextView selectCity, cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
ProgressBar loader;
Typeface weatherFont;
String city = "Rome, IT";
/* Please Put your API KEY here */
String OPEN_WEATHER_MAP_API = "f2b6e17d5a21b6580934286ac8fa696a";
/* Please Put your API KEY here */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loader = (ProgressBar) findViewById(R.id.loader);
selectCity = (TextView) findViewById(R.id.selectCity);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
weatherIcon = (TextView) findViewById(R.id.weather_icon);
weatherFont = Typeface.createFromAsset(getAssets(), "fonts/weathericons-regular-webfont.ttf");
weatherIcon.setTypeface(weatherFont);
taskLoadUp(city);
selectCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Change City");
final EditText input = new EditText(MainActivity.this);
input.setText(city);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
alertDialog.setPositiveButton("Change",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
city = input.getText().toString();
taskLoadUp(city);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
}
public void taskLoadUp(String query) {
if (Function.isNetworkAvailable(getApplicationContext())) {
Log.w("myApp", "network available in main 91");
DownloadWeather task = new DownloadWeather();
task.execute(query);
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
class DownloadWeather extends AsyncTask < String, Void, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
loader.setVisibility(View.VISIBLE);
}
protected String doInBackground(String...args) {
String xml = Function.excuteGet("http://api.openweathermap.org/data/2.5/weather?q=" + args[0] +
"&units=metric&appid=" + OPEN_WEATHER_MAP_API);
Log.w("myApp", "xml is " +xml);
return xml;
}
#Override
protected void onPostExecute(String xml) {
try {
JSONObject json = new JSONObject(xml);
if (json != null) {
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
cityField.setText(json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country"));
detailsField.setText(details.getString("description").toUpperCase(Locale.US));
currentTemperatureField.setText(String.format("%.2f", main.getDouble("temp")) + "°");
humidity_field.setText("Humidity: " + main.getString("humidity") + "%");
pressure_field.setText("Pressure: " + main.getString("pressure") + " hPa");
updatedField.setText(df.format(new Date(json.getLong("dt") * 1000)));
weatherIcon.setText(Html.fromHtml(Function.setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000)));
loader.setVisibility(View.GONE);
}else{
Toast.makeText(getApplicationContext(), "Json variable is null", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error, Check City", Toast.LENGTH_SHORT).show();
}
}
}
}
Function:
public class Function {
// Project Created by Ferdousur Rahman Shajib
// www.androstock.com
public static boolean isNetworkAvailable(Context context)
{
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
public static String excuteGet(String targetURL)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("content-type", "application/json; charset=utf-8");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(false);
InputStream is;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = connection.getErrorStream();
else
is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
}
The output:
FATAL EXCEPTION: main
Process: com.example.weatherapp, PID: 30032
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:176)
at com.example.weatherapp.MainActivity$DownloadWeather.onPostExecute(MainActivity.java:117)
at com.example.weatherapp.MainActivity$DownloadWeather.onPostExecute(MainActivity.java:101)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-02-09 18:27:45.489 30032-30032/com.example.weatherapp I/Process: Sending signal. PID: 30032 SIG: 9
The app begins to start, but then closes immediately.
EDIT: The question should not be a duplicate, in my opinion, as the problem is not from wrong initialization of an object, but from not adding a specific line in the manifest file
The issue can be with the permission for internet and permission for cleartext HTTP traffic value in your manifest.
Please make sure to add
?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
I want to Upload file to server by selecting the file from file manager So I have opened file manager by clicking on Button using this code,
button_upload_attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] galleryPermissions = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(CIBILCaptureandUPLOAD.this, galleryPermissions)) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
} else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}
}
});
and onActivityResult method i have done something like this to get path of the file and had make UploadToserver function for uploading
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//ImagesData = data;
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri contentUri=data.getData();
Log.e("bbbbbbbbbbbbbb", contentUri.toString());
if(contentUri.toString().endsWith(".png")||contentUri.toString().endsWith("jpg") ||
contentUri.toString().endsWith(".pdf")){
photoFile= new File(contentUri.getPath());
if (photoFile.exists()) {
Log.e("photoFile", "File Exists");
}
if (photoFile != null) {
new AsyncTask<String, String, File>() {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
Log.e("PreExecute", "Compressing");
}
#Override
protected File doInBackground(String[] params) {
return photoFile;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result != null) {
new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
}
}
}.execute("");
}
}else {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri,
filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = "";
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
Log.e("PATH", filePath);
photoFile = new File(filePath);
if (photoFile.exists()) {
Log.e("photoFile", "File Exists");
}
if (photoFile != null) {
new AsyncTask<String, String, File>() {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
Log.e("PreExecute", "Compressing");
}
#Override
protected File doInBackground(String[] params) {
return photoFile;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result != null) {
new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
}
}
}.execute("");
}
}
}
It works well in other devices but in samsung devices i have got
java.io.FileNotFoundException: /document/primary:Xender/other/When Strangers Meet_ 3 in 1 Box - John Harker.pdf: open failed: ENOENT (No such file or directory)
And my upload code is
private class UploadFileToServer extends AsyncTask {
private static final String TAG = "UploadFileToServer";
// private ProgressBar progressBar;
// private String filePath = null;
// private TextView txtPercentage;
private ProgressDialog pd;
long totalSize = 0;
#Override
protected void onPreExecute() {
// setting progress bar to zero
// progressBar.setProgress(0);
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Loading...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
pd.setMessage("Loading..." + progress[0]);
// progressBar.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(File... params) {
return uploadFile1(params[0]);
}
#SuppressWarnings("deprecation")
private String uploadFile1(File file) {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppUtill.URL_CIBIL_imageupload);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = file;// new File(filePath);
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("mid", new StringBody(memberid));
entity.addPart("did", new StringBody("0"));
entity.addPart("fid", new StringBody(formtypeid));
if (app_loadid == null) {
SharedPreferences sharedPreferences = getSharedPreferences("LID", MODE_PRIVATE);
app_loadid = sharedPreferences.getString("lid", "");
entity.addPart("lid", new StringBody(app_loadid));
} else {
entity.addPart("lid", new StringBody(app_loadid));
}
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode +statusCode");
if (statusCode == 200) {
// Server response
System.out.println("statusCode +statusCode");
responseString = EntityUtils.toString(r_entity);
String success = String.valueOf(responseString.contains("1"));
if (success.matches("true")) {
uploadedFileCount++;
} else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "File not uploaded. Please upload again...", Toast.LENGTH_SHORT).show();
}
});
}
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
pd.dismiss();
if (uploadedFileCount == MAX_COUNT) {
AlertDialog.Builder alert = new AlertDialog.Builder(CIBILCaptureandUPLOAD.this);
alert.setTitle(R.string.app_name);
alert.setMessage("Reach to max upload limit");
alert.setCancelable(false);
alert.setPositiveButton("OK", null);
alert.create().show();
}
// showing the server response in an alert dialog
showAlert(result);
AppUtill.deleteFolderAndAllFile(CIBILCaptureandUPLOAD.this);
super.onPostExecute(result);
}
}
photoFile= new File(contentUri.getPath());
Have a look at the value of contentUri.getPath() and see that it is not a valid file system path.
Instead you should open an InputStream for the obtained uri and read the file content from the stream.
InputStream is = getContentResolver().openInputStream(contentUri);
I'm using a MySQL server to fetch images from database to android to display in an ImageView. However, I receive the following error:
SkImageDecoder:: Factory returned null
This has been answered before, but I call .decodeStream once? It would be appreciated if you could help me
MainActivty.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://thakurnigamananda.com/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
Logcat:
12-25 22:01:30.150 30009-30009/com.example.ayush.testingfordata I/ViewRootImpl: ViewRoot's Touch Event : Touch Down
12-25 22:01:30.180 30009-30009/com.example.ayush.testingfordata I/ViewRootImpl: ViewRoot's Touch Event : Touch UP
12-25 22:01:30.340 30009-30225/com.example.ayush.testingfordata D/libc: getaddrinfo called from pid =30009
12-25 22:01:30.340 30009-30225/com.example.ayush.testingfordata E/DataScheduler: isDataSchedulerEnabled():false
12-25 22:01:30.340 30009-30225/com.example.ayush.testingfordata D/libc: getaddrinfo called from pid =30009
12-25 22:01:31.080 30009-30225/com.example.ayush.testingfordata D/libc: dnsproxy getaddrinfo returns 0
12-25 22:01:31.800 30009-30282/com.example.ayush.testingfordata D/skia: --- SkImageDecoder::Factory returned null
fixed, error in PHP scripts and database.
I am using okhttp for network requests and responses.I have searched alot on the web and also on github about this issue but i did not get any clean solution, I don't know what is wrong in the code. I am getting NullPointerException when i click on Btn_Proceed. The code is provided and also the stacktrace. Thank you.
07-28 02:11:18.407 16167-17029/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.donateblood.blooddonation, PID: 16167
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.NullPointerException
at okhttp3.HttpUrl.canonicalize(HttpUrl.java:1853)
at okhttp3.FormBody$Builder.add(FormBody.java:110)
at com.donateblood.blooddonation.UploadImage$AddUserAsync.doInBackground(UploadImage.java:203)
at com.donateblood.blooddonation.UploadImage$AddUserAsync.doInBackground(UploadImage.java:173)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)
public class UploadImage extends AppCompatActivity {
#InjectView(R.id.imageView) ImageView ImageUpload;
#InjectView(R.id.upload) Button Btn_Upload;
#InjectView(R.id.proceed) Button Btn_Proceed;
EditText code;
public ProgressDialog pDialog;
public String bloodgroup,name,password,number,email,age,ID;
public String encodedPhotoString=null;
GPSTracker gps; public Bitmap myimage=null;
public JSONObject json =null;
public double latitude;
public double longitude;
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.uploadimage);
ButterKnife.inject(this);
}catch (OutOfMemoryError e){
Toast.makeText(getBaseContext(), "Sorry,Something went wrong", Toast.LENGTH_SHORT).show();
}
code = (EditText) findViewById(R.id.code);
myimage = CroppingActivity.finalImage;
CheckImage();
// Upload image ====================================
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UploadImage.this.finish();
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(code.length()==0){
Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
}
else {
Prcoess();
}
}
});
}
public void CheckImage(){
if(myimage!=null){
Uri uri = getImageUri(myimage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Glide.with(UploadImage.this).load(file).asBitmap().diskCacheStrategy( DiskCacheStrategy.NONE ).skipMemoryCache( true ).override(300,300)
.transform(new CenterCrop(UploadImage.this),new CustomCenterCrop(UploadImage.this)).into(ImageUpload);
}else {
encodedPhotoString= null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UploadImage.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
// Processing and adding user to database from here ====================================
public void Prcoess(){
String userentered=code.getText().toString();
String sentcode = SignupActivity.Code;
setPhoto();
if(userentered.equals(sentcode) && encodedPhotoString!=null ){
new AddUserAsync().execute();
}
else {
Toast.makeText(getBaseContext(), "Oopps...Sorry...Upload Again", Toast.LENGTH_LONG).show();
}
}
public void setPhoto() {
// resize the image to store to database
myimage= getResizedBitmap(myimage,400,400);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
Log.e("photo string ", encodedPhotoString);
}
public class AddUserAsync extends AsyncTask<Void,Void,Void> {
JSONObject json = null;
String fromServer = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
GenerateGCMID();
email= email.trim().toLowerCase();
//HashMap<String ,String> userDetails = new HashMap<>();
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.writeTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
FormBody.Builder formBuilder = new FormBody.Builder() // Null pointer exception is thrown here
.add("ID",ID)
.add("Name",name)
.add("email",email)
.add("password",password)
.add("age",age)
.add("number",number)
.add("bloodgroup",bloodgroup)
.add("lat",latitude+"")
.add("longi",longitude+"")
.add("image",encodedPhotoString);
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url("http://faceblood.website/blood_app/Adduser.php")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
String res = response.body().string();
json = new JSONObject(res);
fromServer = json.getString("added");
Log.e("stringtest",json.getString("added"));
// Do something with the response.
} catch (IOException e) {
Log.e("stringtest IO",e.toString());
e.printStackTrace();
} catch (JSONException e) {
Log.e("stringtest JSON",e.toString());
e.printStackTrace();
}
//json = new HttpCall().postForJSON("http://faceblood.website/blood_app/Adduser.php",userDetails);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Log.e("fromServer",fromServer);
if(fromServer.equals("addeduser")){
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}else {
Toast.makeText(getBaseContext(), "Network problem. Click again", Toast.LENGTH_LONG).show();
}
}
}
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
// Go to another activity on success ====================================
public void onSignupSuccess() {
// stop the service we got the latitude and longitude now
myimage.recycle();
myimage = null;
ImageUpload.setImageResource(0);
stopService(new Intent(this, GPSTracker.class));
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
Hint
at okhttp3.FormBody$Builder.add(FormBody.java:110)
at ...UploadImage$AddUserAsync.doInBackground(UploadImage.java:203)
You have added a null value to the Form here (at line 203)
FormBody.Builder formBuilder = new FormBody.Builder()
.add("ID",ID)
.add("Name",name)
.add("email",email)
.add("password",password)
.add("age",age)
.add("number",number)
.add("bloodgroup",bloodgroup)
.add("lat",latitude+"")
.add("longi",longitude+"")
.add("image",encodedPhotoString);
Which I am guessing starts from either here, where you are doing another asynchronous request.
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
Or here because static values are not how you pass data between Activities. You cannot "reach" for a EditText value from the current Activity to a different one.
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
You can refer to How do I pass data between Activities
I've builded Updates class for my Android app. It works fine except Download inner AsyncTask-class.
I wanted to display progress dialog in LoadingActivity while file is downloading.
Firstly, I invoke the Updates class in onCreate method. As a parameter I send activity context. Then in Updates class constructor I invoke Check inner class (AsyncTask), which parse JSON response from URL (works properly) and invoke Download (next Updates inner class) and here it's problem.
When I'm trying to create ProgressDialog object, the compiler throws:
04-01 02:53:56.864 24393-24425/pl.com.mpkostrowiec.schedule E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:197)
at android.os.Handler.<init>(Handler.java:111)
at android.app.Dialog.<init>(Dialog.java:107)
at android.app.AlertDialog.<init>(AlertDialog.java:114)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at pl.com.mpkostrowiec.schedule.DownloadAsync.<init>(DownloadAsync.java:30)
at pl.com.mpkostrowiec.schedule.Updates$Check.doInBackground(Updates.java:128)
at pl.com.mpkostrowiec.schedule.Updates$Check.doInBackground(Updates.java:74)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
I thought that ProgressDialog constructor can't access context variable from Updates class, so I tried to send it as parameter, but it doesn't resolve the problem.
LoadingActivity class:
package pl.com.mpkostrowiec.schedule;
import ...
public class LoadingActivity extends Activity {
private final Preferences preferences = new Preferences(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
preferences.savePreference("Preferences", "firstRun", "1");
// Check if first run
if (preferences.readPreference("Preferences", "firstRun").equals("0")) {
System.out.println("****************** Not first run");
} else {
// Create directory
File dir = this.getDir("Versions", MODE_PRIVATE);
new Updates(this);
}
}
}
Update class:
package pl.com.mpkostrowiec.schedule;
import ...
interface AfterExecuteListener {
public void afterDownload(String[] versionData, int type);
}
public class Updates implements AfterExecuteListener{
private static VersionsTable versionsTable;
private Context context;
public static Boolean status_current = false;
public static Boolean status_new = false;
private final int TYPE_CURRENT = 0;
private final int TYPE_NEW = 1;
private static final String URL = "http://www.mpkostrowiec.com.pl/preview/";
private static final String GET_VERSIONS = "includes/android/versions.php";
private static final String RESOURCES = "resources/android/versions/";
private static final String EXTENSION = ".db";
public Updates(Context context) {
this.context = context;
versionsTable = new VersionsTable(this.context);
new Check(TYPE_CURRENT).execute();
}
public final void afterDownload(String[] versionData, int type) {
// Add version data to DB
versionsTable.open();
versionsTable.add(versionData);
versionsTable.close();
// Set status
if (type == TYPE_CURRENT) {
System.out.println("****************** Downloaded: " + type);
status_current = true;
} else if (type == TYPE_NEW) {
System.out.println("****************** Downloaded: " + type);
status_new = true;
}
Schedule();
}
private void Schedule() {
if (status_current) {
if (status_new) {
System.out.println("****************** SUCCESS");
} else {
new Check(TYPE_NEW).execute();
}
}
}
private class Check extends AsyncTask<String, Integer, String> {
public AfterExecuteListener mListener;
private int type;
public Check(int type) {
this.type = type;
}
#Override
protected String doInBackground(String... Url) {
String[] typeStr = {"current", "new"};
// Get versions form URL
JSONObject json = null;
String versions = null;
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(URL + GET_VERSIONS);
try {
response = myClient.execute(myConnection);
versions = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject jObject = new JSONObject(versions);
json = jObject.getJSONObject(typeStr[type]);
if (json.length() > 1) {
String[] versionData = {json.getString("id"),
json.getString("name"),
json.getString("expDate")};
versionsTable.open();
Boolean idExist = versionsTable.check(versionData[0]);
versionsTable.close();
// Check version
if (!idExist) {
// Start downloading
Download download = new Download(versionData, type);
download.setListener(Updates.this);
download.execute(URL + RESOURCES + versionData[0] + EXTENSION);
}
} else {
// If array contains only false field then do not update
if (type == TYPE_CURRENT) {
Updates.status_current = true;
} else if (type == TYPE_NEW) {
Updates.status_new = true;
}
Schedule();
}
} catch ( JSONException e) {
e.printStackTrace();
}
return null;
}
}
private class Download extends AsyncTask<String, Integer, String> {
public ProgressDialog mProgressDialog;
public AfterExecuteListener mListener;
private String[] versionData;
private int type;
public Download(String[] versionData, int type) {
this.versionData = versionData;
this.type = type;
// Create progress dialog
mProgressDialog = new ProgressDialog(context);
// Set your progress dialog Title
mProgressDialog.setTitle("Updating...");
// Set your progress dialog Message
mProgressDialog.setMessage("Update in progress. Please wait.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... Url) {
try {
java.net.URL url = new URL(Url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// Detect the file lenghth
int fileLength = connection.getContentLength();
// Locate storage location
String filepath = context.getApplicationInfo().dataDir + "/Versions";
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// Save the downloaded file
OutputStream output = new FileOutputStream(filepath + "/" + versionData[0] + ".db");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
} catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// Update the progress dialog
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// Dismiss the progress dialog
mProgressDialog.dismiss();
mListener.afterDownload(versionData, type);
}
private void setListener(AfterExecuteListener listener) {
mListener = listener;
}
}
}