java.lang.NoClassDefFoundError: org.apache.http.Consts - java

I am converting my project in Studio from eclipse.I am sending image in multi part to sever using httpmime 4.5.1 jar file. This is my code.it gives me NoClassDefFoundError: org.apache.http.Consts error.
Please help me.
This is my code.
new AsyncTask<String, Integer, Void>() {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
progressBar.setProgress(progress[0]);
txtPercentage.setText(progress[0] + "%");
}
#SuppressWarnings("deprecation")
#Override
protected Void doInBackground(String... params) {
for (i = 0; i < allPath.length; i++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
txtCount.setText((i + 1) + "/"
+ allPath.length);
}
});
allPath[i] = selected.get(i).sdcardPath;
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(
compressImage(allPath[i]));
// Adding file data to http body
entity.addPart("tag", new StringBody(
"productAdd"));
// Adding file data to http body
entity.addPart("image",
new FileBody(sourceFile));
entity.addPart(
"seller_id",
new StringBody(
CommonUtilities
.getSellerId(getApplicationContext())));
entity.addPart(
"shop_id",
new StringBody(
CommonUtilities
.getCurentShopId(
getApplicationContext())
.toString()));
entity.addPart(
"product_pId",
new StringBody(
CommonUtilities
.getMaxProductId(
getApplicationContext())
.toString()));
entity.addPart("cat_id", new StringBody(cat_id));
entity.addPart("product_image", new StringBody(
allPath[i]));
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;
flagForError = true;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
flagForError = true;
} catch (IOException e) {
responseString = e.toString();
flagForError = true;
}
if (flagForError == false) {
updateAfterResponse(responseString);
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
uploadDialog.cancel();
dialogForError();
}
});
task.cancel(true);
break;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
});
if (i == allPath.length - 1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
txtCount.setText("Done");
}
});
}
// return responseString;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// showing the server response in an alert
// dialog
super.onPostExecute(result);
// if (i == (allPath.length - 1)) {
if (uploadDialog.isShowing()) {
uploadDialog.dismiss();
}
}
}.execute();
and it is giving me error
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: Process: com.elsner.orderlite, PID: 10320
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:300)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: a`enter code here`t java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: Caused by: java.lang.NoClassDefFoundError: org.apache.http.Consts
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:147)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at com.elsner.sellerproduct.CustomGalleryActivity$2$1.doInBackground(CustomGalleryActivity.java:311)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at com.elsner.sellerproduct.CustomGalleryActivity$2$1.doInBackground(CustomGalleryActivity.java:221)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
12-10 17:35:58.710 10320-10340/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841) 

in bundle.gradle use
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

To do multipart POST calls, you need to get three additional Apache
open source projects: Apache Commons IO, Mime4j, and HttpMime. You can
download these projects from the following web sites: Commons IO:
http://commons.apache.org/io/ Mime4j: http://james.apache.org/mime4j/
HttpMime: http://hc.apache.org/downloads.cgi (inside of HttpClient)

If you are using sdk version 23, you have to add to your gradle:
android {
compileSdkVersion 23
...
useLibrary 'org.apache.http.legacy'
...
}

Related

Android - Error when uploading multiple images

I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
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;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
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;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).

Async task doinbackground exception

My async function is this:
class ProfileCategoryCall extends AsyncTask<String, String, String>{
public ProfileCategoryCall() {
// TODO Auto-generated constructor stub
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
JSONObject HomeCardString = new JSONObject();
JSONObject ABC = new JSONObject();
try {
responseString = result;
joiningYear = new JSONObject(responseString);
HomeCardString = joiningYear.getJSONObject("CategoryLikesResult");
ABC = HomeCardString.getJSONObject("CategoryLikesResult");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Gson gson = new Gson();
try
{
((ProfileActivity)getActivity()).interestResult = gson.fromJson(ABC.toString(), LikeCategorySummaryResult.class);
}
catch(Exception e)
{
Log.i("myyyy", e.getMessage());
e.printStackTrace();
}
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + responseString + "\"" + t.getMessage());
}
PopulateData();
progress.setVisibility(View.GONE);
super.onPostExecute(result);
//Do anything with response..
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
While Calling async service call this error occurs.
08-28 11:15:38.140: E/AndroidRuntime(14310): FATAL EXCEPTION: AsyncTask #1
08-28 11:15:38.140: E/AndroidRuntime(14310): java.lang.RuntimeException: An error occured while executing doInBackground()
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.lang.Thread.run(Thread.java:856)
08-28 11:15:38.140: E/AndroidRuntime(14310): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 355: http://example.net/Service.svc/android/Profile/1361769105/Like/EXAMPLE?category=Public
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.net.URI.create(URI.java:727)
08-28 11:15:38.140: E/AndroidRuntime(14310): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
08-28 11:15:38.140: E/AndroidRuntime(14310): at com.stalker.androidapp.InterestTabFragment$ProfileCategoryCall.doInBackground(InterestTabFragment.java:308)
08-28 11:15:38.140: E/AndroidRuntime(14310): at com.stalker.androidapp.InterestTabFragment$ProfileCategoryCall.doInBackground(InterestTabFragment.java:1)
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-28 11:15:38.140: E/AndroidRuntime(14310): ... 5 more
I have seen other similar questions, but answers were to remove code which is using UI from doInBackground() and I don't think I have any unnecessary code in it. So please tell me if I am wrong.

AsyncTask error occured while executing doInBackground()

I'm getting an error in following code, calling asyn method for http request. It gives me a java.lang.RuntimeException error inside doInBackground() method.
_____________MAIN class____________
TextView testoInput = (TextView) findViewById(R.id.input);
final String località = testoInput.getText().toString();
bottone1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
TaskAsincrono nuovo = new TaskAsincrono();
nuovo.execute(località);
}
__________ASYNC Class________
public class TaskAsincrono extends AsyncTask > {
protected ArrayList<String> doInBackground(String...params) {
String s = params[0];
ArrayList<String> risultato =null;
//Inizio sessione di invio dati rest con sistema GET
DefaultHttpClient client = new DefaultHttpClient();
String url ="http://www.replycoupon.it/php/rest_Server/index.php?nome="+s;
try {
URI uri = new URI(url);
HttpGet get = new HttpGet(uri);
HttpResponse res = client.execute(get);
InputStream data = res.getEntity().getContent();
//Inizio l'operazione di buffering per la lettura
BufferedReader streamReader = new BufferedReader(new InputStreamReader(data));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr =null;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jObj = new JSONObject(responseStrBuilder.toString());
String clima = jObj.getString("clima");
String temperatura = jObj.getString("temperatura");
//Prima di inviare alla main metto il risultato in un arrylist
risultato.add(clima);
risultato.add(temperatura);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return risultato;
}
protected void onPostExecute(final ArrayList<String> risultato) {
final TextView testoClima = (TextView) findViewById(R.id.Output);
final TextView testoTemp = (TextView) findViewById(R.id.Output2);
testoClima.setText(risultato.get(0).toString());
testoTemp.setText(risultato.get(1).toString());
}
}
LOG
10-02 20:53:07.068: D/dalvikvm(4050): GC_FOR_ALLOC freed 234K, 4% free 7914K/8188K, paused 16ms, total 16ms
10-02 20:53:09.728: W/dalvikvm(4050): threadid=11: thread exiting with uncaught exception (group=0x41800ba8)
10-02 20:53:09.728: E/AndroidRuntime(4050): FATAL EXCEPTION: AsyncTask #1
10-02 20:53:09.728: E/AndroidRuntime(4050): Process: luca.tirocinio.client_json, PID: 4050
10-02 20:53:09.728: E/AndroidRuntime(4050): java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.lang.Thread.run(Thread.java:841)
10-02 20:53:09.728: E/AndroidRuntime(4050): Caused by: java.lang.NullPointerException
10-02 20:53:09.728: E/AndroidRuntime(4050): at luca.tirocinio.client_json.MainActivity$TaskAsincrono.doInBackground(MainActivity.java:117)
10-02 20:53:09.728: E/AndroidRuntime(4050): at luca.tirocinio.client_json.MainActivity$TaskAsincrono.doInBackground(MainActivity.java:1)
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-02 20:53:09.728: E/AndroidRuntime(4050): ... 4 more
10-02 20:53:13.768: I/Process(4050): Sending signal. PID: 4050 SIG: 9
You're trying to add results to ArrayList<String> risultato which is null. Just replace it with ArrayList<String> risultato = new ArrayList<String>();

Gson and Google

I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Code keeps thowing a NPE, cannot find the cause

i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
 Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.

Categories

Resources